SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.
Python attacksurfacecticybersecurityfootprintinghackinginformation-gatheringinformation-securityinfosecintelligence-gatheringosintosint-frameworkosint-reconnaissanceosint-toolpentestingpythonreconsecurity-toolsthreat-intelligencethreatintel
sfscan: validate configured proxy (#1228)
bcoles65b154cef9b1
diff --git a/sflib.py b/sflib.pyindex 589073bc..071ae0a1 100644--- a/sflib.py+++ b/sflib.py@@ -27,7 +27,6 @@ import tracebackimport urllib.errorimport urllib.parseimport urllib.request-import uuidfrom copy import deepcopyfrom datetime import datetime@@ -185,15 +184,6 @@ class SpiderFoot:return val- def genScanInstanceId(self):- """Generate an globally unique ID for this scan.-- Returns:- str: scan instance unique ID- """-- return str(uuid.uuid4()).split("-")[0].upper()-def _dblog(self, level, message, component=None):"""Log a scan event.@@ -366,8 +356,9 @@ class SpiderFoot:Returns:str: SpiderFoot cache file system path"""-- path = self.myPath() + '/cache'+ path = os.environ.get('SPIDERFOOT_CACHE')+ if not path:+ path = self.myPath() + '/cache'if not os.path.isdir(path):os.mkdir(path)return path@@ -2201,6 +2192,9 @@ class SpiderFoot:Returns:bool: should the configured proxy be used?++ Todo:+ Allow using TOR only for .onion addresses"""host = self.urlFQDN(url).lower()@@ -2217,7 +2211,7 @@ class SpiderFoot:if not proxy_port:return False- # Never proxy requests to the proxy+ # Never proxy requests to the proxy hostif host == proxy_host.lower():return False@@ -2264,7 +2258,7 @@ class SpiderFoot:timeout (int): timeoutuseragent (str): user agent headerheaders (str): headers- noLog (bool): do not log+ noLog (bool): do not log requestpostData (str): HTTP POST datadontMangle (bool): do not manglesizeLimit (int): size threshold@@ -2298,16 +2292,14 @@ class SpiderFoot:self.debug(f"Invalid URL scheme for URL: {url}")return None+ request_log = []+proxies = dict()if self.useProxyForUrl(url):- proxy_url = f"socks5h://{self.opts['_socks2addr']}:{self.opts['_socks3port']}"- self.debug(f"Using proxy {proxy_url} for {url}")proxies = {- 'http': proxy_url,- 'https': proxy_url+ 'http': self.socksProxy,+ 'https': self.socksProxy,}- else:- self.debug(f"Not using proxy for {url}")header = dict()btime = time.time()@@ -2322,9 +2314,14 @@ class SpiderFoot:for k in list(headers.keys()):header[k] = str(headers[k])+ request_log.append(f"proxy={self.socksProxy}")+ request_log.append(f"user-agent={header['User-Agent']}")+ request_log.append(f"timeout={timeout}")+ request_log.append(f"cookies={cookies}")+if sizeLimit or headOnly:if not noLog:- self.info(f"Fetching (HEAD only): {self.removeUrlCreds(url)} [user-agent: {header['User-Agent']}] [timeout: {timeout}]")+ self.info(f"Fetching (HEAD): {self.removeUrlCreds(url)} ({', '.join(request_log)})")try:hdr = self.getSession().head(@@ -2361,7 +2358,7 @@ class SpiderFoot:if result['realurl'] != url:if not noLog:- self.info(f"Fetching (HEAD only): {self.removeUrlCreds(result['realurl'])} [user-agent: {header['User-Agent']}] [timeout: {timeout}]")+ self.info(f"Fetching (HEAD): {self.removeUrlCreds(result['realurl'])} ({', '.join(request_log)})")try:hdr = self.getSession().head(@@ -2388,14 +2385,10 @@ class SpiderFoot:return result- if not noLog:- if cookies:- self.info(f"Fetching (incl. cookies): {self.removeUrlCreds(url)} [user-agent: {header['User-Agent']}] [timeout: {timeout}]")- else:- self.info(f"Fetching: {self.removeUrlCreds(url)} [user-agent: {header['User-Agent']}] [timeout: {timeout}]")-try:if postData:+ if not noLog:+ self.info(f"Fetching (POST): {self.removeUrlCreds(url)} ({', '.join(request_log)})")res = self.getSession().post(url,data=postData,@@ -2407,6 +2400,8 @@ class SpiderFoot:verify=verify)else:+ if not noLog:+ self.info(f"Fetching (GET): {self.removeUrlCreds(url)} ({', '.join(request_log)})")res = self.getSession().get(url,headers=header,diff --git a/sfscan.py b/sfscan.pyindex 5b1bd0df..1a1d0bb0 100644--- a/sfscan.py+++ b/sfscan.py@@ -131,31 +131,52 @@ class SpiderFootScanner():# Process global options that point to other places for data- # If a SOCKS server was specified, set it up- if self.__config['_socks1type']:- socksAddr = self.__config['_socks2addr']- socksPort = int(self.__config['_socks3port'])- socksUsername = self.__config['_socks4user'] or ''- socksPassword = self.__config['_socks5pwd'] or ''-- proxy = f"{socksAddr}:{socksPort}"-- if socksUsername or socksPassword:- proxy = "%s:%s@%s" % (socksUsername, socksPassword, proxy)-- if self.__config['_socks1type'] == '4':- proxy = 'socks4://' + proxy- elif self.__config['_socks1type'] == '5':- proxy = 'socks5://' + proxy- elif self.__config['_socks1type'] == 'HTTP':- proxy = 'http://' + proxy- elif self.__config['_socks1type'] == 'TOR':- proxy = 'socks5h://' + proxy+ # If a proxy server was specified, set it up+ proxy_type = self.__config.get('_socks1type')+ if proxy_type:+ # TODO: allow DNS lookup to be configurable when using a proxy+ # - proxy DNS lookup: socks5h:// and socks4a://+ # - local DNS lookup: socks5:// and socks4://+ if proxy_type == '4':+ proxy_proto = 'socks4://'+ elif proxy_type == '5':+ proxy_proto = 'socks5://'+ elif proxy_type == 'HTTP':+ proxy_proto = 'http://'+ elif proxy_type == 'TOR':+ proxy_proto = 'socks5h://'else:- raise ValueError(f"Invalid SOCKS proxy type: {self.__config['_socks1ttype']}")+ self.__sf.status(f"Scan [{self.__scanId}] failed: Invalid proxy type: {proxy_type}")+ self.__setStatus("ERROR-FAILED", None, time.time() * 1000)+ raise ValueError(f"Invalid proxy type: {proxy_type}")- self.__sf.debug(f"SOCKS: {socksAddr}:{socksPort} ({socksUsername}:{socksPassword})")+ proxy_host = self.__config.get('_socks2addr', '')+ if not proxy_host:+ self.__sf.status(f"Scan [{self.__scanId}] failed: Proxy type is set ({proxy_type}) but proxy address value is blank")+ self.__setStatus("ERROR-FAILED", None, time.time() * 1000)+ raise ValueError(f"Proxy type is set ({proxy_type}) but proxy address value is blank")++ proxy_port = int(self.__config.get('_socks3port') or 0)++ if not proxy_port:+ if proxy_type == '4' or proxy_type == '5':+ proxy_port = 1080+ elif proxy_type.upper() == 'HTTP':+ proxy_port = 8080+ elif proxy_type.upper() == 'TOR':+ proxy_port = 9050++ proxy_username = self.__config.get('_socks4user', '')+ proxy_password = self.__config.get('_socks5pwd', '')++ if proxy_username or proxy_password:+ proxy_auth = f"{proxy_username}:{proxy_password}"+ proxy = f"{proxy_proto}{proxy_auth}@{proxy_host}:{proxy_port}"+ else:+ proxy = f"{proxy_proto}{proxy_host}:{proxy_port}"++ self.__sf.debug(f"Using proxy: {proxy}")self.__sf.socksProxy = proxyelse:self.__sf.socksProxy = Nonediff --git a/test/unit/test_spiderfootscanner.py b/test/unit/test_spiderfootscanner.pyindex 1f36ec39..e3bbb233 100644--- a/test/unit/test_spiderfootscanner.py+++ b/test/unit/test_spiderfootscanner.py@@ -116,7 +116,7 @@ class TestSpiderFootScanner(unittest.TestCase):with self.assertRaises(TypeError):SpiderFootScanner("example scan name", scan_id, "spiderfoot.net", invalid_type, module_list, self.default_options, start=False)- def test_init_argument_targetType_as_empty_string_should_raise_ValueError(self):+ def test_init_argument_targetType_invalid_value_should_raise_ValueError(self):"""Test __init__(self, scanName, scanId, scanTarget, targetType, moduleList, globalOpts)"""@@ -127,6 +127,10 @@ class TestSpiderFootScanner(unittest.TestCase):with self.assertRaises(ValueError):SpiderFootScanner("example scan name", scan_id, "spiderfoot.net", target_type, module_list, self.default_options, start=False)+ target_type = "INVALID_TARGET_TYPE"+ with self.assertRaises(ValueError):+ SpiderFootScanner("example scan name", scan_id, "spiderfoot.net", target_type, module_list, self.default_options, start=False)+def test_init_argument_moduleList_of_invalid_type_should_raise_TypeError(self):"""Test __init__(self, scanName, scanId, scanTarget, targetType, moduleList, globalOpts)@@ -172,6 +176,66 @@ class TestSpiderFootScanner(unittest.TestCase):with self.assertRaises(ValueError):SpiderFootScanner("example scan name", scan_id, "spiderfoot.net", "IP_ADDRESS", module_list, dict(), start=False)+ def test_init_argument_globalOpts_proxy_invalid_proxy_type_should_raise_ValueError(self):+ """+ Test __init__(self, scanName, scanId, scanTarget, targetType, moduleList, globalOpts)+ """+ opts = self.default_options+ opts['_socks1type'] = 'invalid proxy type'+ opts['__modules__'] = dict()+ scan_id = str(uuid.uuid4())+ module_list = ['sfp__stor_db']++ with self.assertRaises(ValueError):+ SpiderFootScanner("example scan name", scan_id, "spiderfoot.net", "IP_ADDRESS", module_list, opts, start=False)++ def test_init_argument_globalOpts_proxy_type_without_host_should_raise_ValueError(self):+ """+ Test __init__(self, scanName, scanId, scanTarget, targetType, moduleList, globalOpts)+ """+ opts = self.default_options+ opts['_socks1type'] = 'HTTP'+ opts['__modules__'] = dict()+ scan_id = str(uuid.uuid4())+ module_list = ['sfp__stor_db']++ with self.assertRaises(ValueError):+ SpiderFootScanner("example scan name", scan_id, "spiderfoot.net", "IP_ADDRESS", module_list, opts, start=False)++ def test_init_argument_globalOpts_proxy_should_set_proxy(self):+ """+ Test __init__(self, scanName, scanId, scanTarget, targetType, moduleList, globalOpts)+ """+ opts = self.default_options+ opts['_socks1type'] = 'HTTP'+ opts['_socks2addr'] = '127.0.0.1'+ opts['_socks3port'] = '8080'+ opts['_socks4user'] = 'user'+ opts['_socks5pwd'] = 'password'+ opts['__modules__'] = dict()+ scan_id = str(uuid.uuid4())+ module_list = ['sfp__stor_db']++ SpiderFootScanner("example scan name", scan_id, "spiderfoot.net", "IP_ADDRESS", module_list, opts, start=False)++ self.assertEqual('TBD', 'TBD')++ def test_init_argument_globalOpts_proxy_without_port_should_set_proxy(self):+ """+ Test __init__(self, scanName, scanId, scanTarget, targetType, moduleList, globalOpts)+ """+ opts = self.default_options+ opts['_socks1type'] = 'HTTP'+ opts['_socks2addr'] = '127.0.0.1'+ opts['_socks3port'] = ''+ opts['__modules__'] = dict()+ scan_id = str(uuid.uuid4())+ module_list = ['sfp__stor_db']++ SpiderFootScanner("example scan name", scan_id, "spiderfoot.net", "IP_ADDRESS", module_list, opts, start=False)++ self.assertEqual('TBD', 'TBD')+def test_attribute_scanId_should_return_scan_id_as_a_string(self):opts = self.default_optionsopts['__modules__'] = dict()