The recursive internet scanner for hackers. 🧡
Python asmattack-surface-managementautomationbugbountyclieasmhackingneo4josintosint-frameworkpentestingpythonreconrecursionscannersubdomain-enumerationsubdomain-scannersubdomainsthreat-intelligencethreatintel
Resolve excavated relative URLs against <base href> (#3522)
Paul Muellerfb27e8d10217
diff --git a/bbot/core/helpers/regexes.py b/bbot/core/helpers/regexes.pyindex 15226ed9d..62d6505f1 100644--- a/bbot/core/helpers/regexes.py+++ b/bbot/core/helpers/regexes.py@@ -203,6 +203,7 @@ button_tag_regex2 = re.compile(r"<button[^>]*?value=[\"\']?([\-%\._=+\/\w]*)[\"\']?[^>]*?name=[\"\']?([\-\._=+\/\w]+)[\"\']?[^>]*?>")tag_attribute_regex = re.compile(r"<[^>]*(?:href|action|src)\s*=\s*[\"\']?(?!mailto:)([^\'\"\>]+)[\"\']?[^>]*>")+base_href_regex = re.compile(r"<base\b[^>]*?\shref\s*=\s*[\"\']?([^\'\"\>\s]+)", re.I)_invalid_netloc_chars = r"\s!@#$%^&()=/?\\'\";~`<>"# first char must not be a colon, even though it's a valid char for a netlocdiff --git a/bbot/modules/internal/excavate.py b/bbot/modules/internal/excavate.pyindex fce36cf15..01b4d8495 100644--- a/bbot/modules/internal/excavate.py+++ b/bbot/modules/internal/excavate.py@@ -640,6 +640,15 @@ class excavate(BaseInternalModule, BaseInterceptModule):path = event.data.get("path", event.parsed_url.path)return urlparse(f"{scheme}://{host}{path}")+ async def _document_base_url(self, event, document_url):+ """The URL relative references in the body resolve against: the page's <base href> if it has one, else document_url."""+ m = await self.helpers.re.search(bbot_regexes.base_href_regex, getattr(event, "body", "") or "")+ if m:+ base_url = urljoin(document_url, html.unescape(m.group(1)))+ if urlparse(base_url).scheme in ("http", "https"):+ return base_url+ return document_url+def url_unparse(self, param_type, parsed_url):# Reconstructs a URL, optionally omitting the query string based on remove_querystring configuration value.if param_type == "GETPARAM":@@ -828,9 +837,6 @@ class excavate(BaseInternalModule, BaseInterceptModule):if not form_action or form_action == "#":form_action = None- elif form_action.startswith("./"):- form_action = form_action.lstrip(".")-form_parameters = {}for form_content_regex_name, form_content_regex in self.form_content_regexes.items():input_tags = await self.excavate.helpers.re.findall(form_content_regex, form_content)@@ -942,6 +948,8 @@ class excavate(BaseInternalModule, BaseInterceptModule):# Use event.body (property) so we hit the body-spill store; event.data["body"] is# popped at spill time and would be empty here.response_body = getattr(event, "body", "") or ""+ # resolved on the first relative endpoint; RAW_TEXT events have no URL to resolve against+ document_url = base_url = Nonefor identifier, results in yara_results.items():if identifier not in self.parameterExtractorCallbackDict.keys():raise ExcavateError("ParameterExtractor YaraRule identified reference non-existent submodule")@@ -977,14 +985,23 @@ class excavate(BaseInternalModule, BaseInterceptModule):if endpoint and endpoint.startswith(("http://", "https://")):url = endpoint- # The endpoint is usually a form action - we should use it if we have it. If not, default to URL.+ elif not hasattr(event, "parsed_url"):+ self.excavate.debug(+ f"Skipping parameter [{parameter_name}] with relative endpoint: {event.type} has no URL"+ )+ continue++ # The endpoint is usually a form action - we should use it if we have it.+ # A form with no action submits to the document URL, not <base href>.else:- # Use the effective base URL (which may differ from parsed_url for archived content)- event_base = self.excavate._event_base_url(event)- base_url = f"{event_base.scheme}://{event_base.netloc}{event_base.path}"- if not self.excavate.remove_querystring and len(event.parsed_url.query) > 0:- base_url += f"?{event.parsed_url.query}"- url = urljoin(base_url, endpoint)+ if document_url is None:+ # Use the effective base URL (which may differ from parsed_url for archived content)+ event_base = self.excavate._event_base_url(event)+ document_url = f"{event_base.scheme}://{event_base.netloc}{event_base.path}"+ if not self.excavate.remove_querystring and len(event.parsed_url.query) > 0:+ document_url += f"?{event.parsed_url.query}"+ base_url = await self.excavate._document_base_url(event, document_url)+ url = urljoin(base_url, endpoint) if endpoint else document_urltry:# Validate the URL before using it@@ -1254,6 +1271,7 @@ class excavate(BaseInternalModule, BaseInterceptModule):tag_attribute_regex = bbot_regexes.tag_attribute_regexasync def process(self, yara_results, event, yara_rule_settings, discovery_context):+ source_url = Nonefor identifier, results in yara_results.items():urls_found = 0final_url = ""@@ -1276,7 +1294,8 @@ class excavate(BaseInternalModule, BaseInterceptModule):)continueunescaped_url = html.unescape(m.group(1))- source_url = event.parsed_url.geturl()+ if source_url is None:+ source_url = await self.excavate._document_base_url(event, event.parsed_url.geturl())final_url = urldefrag(urljoin(source_url, unescaped_url)).urlif not await self.helpers.re.search(self.full_url_regex_strict, final_url):self.excavate.debug(diff --git a/bbot/test/test_step_2/module_tests/test_module_excavate.py b/bbot/test/test_step_2/module_tests/test_module_excavate.pyindex e86845d26..75be5576f 100644--- a/bbot/test/test_step_2/module_tests/test_module_excavate.py+++ b/bbot/test/test_step_2/module_tests/test_module_excavate.py@@ -932,6 +932,130 @@ class TestExcavateParameterExtraction_relativeurl(ModuleTestBase):assert parameter_extraction_found, "Excavate failed to extract parameter after traversal"+class TestExcavateBaseHref(ModuleTestBase):+ """Relative references resolve against <base href>, not the page URL; a form with no action still uses the page URL."""++ targets = [f"{HTTPSERVER_URL}/app/sub/"]+ modules_overrides = ["http", "excavate", "hunt"]++ base_href_html = """+<html>+<head>+ <base href="/">+ <link href="app/theme/getui?ver=1" rel="stylesheet" />+</head>+<body>+ <a href="app/page.html">page</a>+ <form action="app/search" method="get"><input type="text" name="q" value="1"></form>+ <form method="post"><input type="text" name="token" value="abc"></form>+</body>+</html>+"""++ async def setup_after_prep(self, module_test):+ module_test.httpserver.expect_request("/app/sub/").respond_with_data(+ self.base_href_html, headers={"Content-Type": "text/html"}+ )++ def check(self, module_test, events):+ urls = {e.url for e in events if e.type == "URL_UNVERIFIED"}+ assert f"{HTTPSERVER_URL}/app/page.html" in urls+ assert not any("/app/sub/app/" in u for u in urls), f"Resolved against page URL instead of <base>: {urls}"++ params = {e.data["name"]: e.data["url"] for e in events if e.type == "WEB_PARAMETER"}+ assert params.get("ver") == f"{HTTPSERVER_URL}/app/theme/getui", params+ assert params.get("q") == f"{HTTPSERVER_URL}/app/search", params+ assert params.get("token") == f"{HTTPSERVER_URL}/app/sub/", params+++class TestExcavateFormActionRelative(ModuleTestBase):+ """Form actions on a nested page resolve against the page's directory, the same way a browser submits them."""++ targets = [f"{HTTPSERVER_URL}/app/sub/page"]+ modules_overrides = ["http", "excavate", "hunt"]++ base_tag = ""+ expected = {+ "dot_post": "/app/sub/dotpost",+ "dot_get": "/app/sub/dotget",+ "up_post": "/app/uppost",+ "bare_post": "/app/sub/barepost",+ "root_post": "/rootpost",+ }++ async def setup_after_prep(self, module_test):+ html = f"""+<html>+<head>{self.base_tag}</head>+<body>+ <form action="./dotpost" method="post"><input type="text" name="dot_post" value="1"></form>+ <form action="./dotget" method="get"><input type="text" name="dot_get" value="1"></form>+ <form action="../uppost" method="post"><input type="text" name="up_post" value="1"></form>+ <form action="barepost" method="post"><input type="text" name="bare_post" value="1"></form>+ <form action="/rootpost" method="post"><input type="text" name="root_post" value="1"></form>+</body>+</html>+"""+ module_test.httpserver.expect_request("/app/sub/page").respond_with_data(+ html, headers={"Content-Type": "text/html"}+ )++ def check(self, module_test, events):+ params = {e.data["name"]: e.data["url"] for e in events if e.type == "WEB_PARAMETER"}+ for name, path in self.expected.items():+ assert params.get(name) == f"{HTTPSERVER_URL}{path}", f"{name}: {params}"+++class TestExcavateFormActionRelativeBaseHref(TestExcavateFormActionRelative):+ """With <base href>, form actions resolve against the base instead of the page."""++ base_tag = '<base href="/other/dir/">'+ expected = {+ "dot_post": "/other/dir/dotpost",+ "dot_get": "/other/dir/dotget",+ "up_post": "/other/uppost",+ "bare_post": "/other/dir/barepost",+ "root_post": "/rootpost",+ }+++class TestExcavateFormActionRelativeNonHttpBaseHref(TestExcavateFormActionRelative):+ """A non-http <base href> is ignored, so form actions resolve against the page."""++ base_tag = '<base href="javascript:void(0)">'+++class TestExcavateParameterExtractionRawText(ModuleTestBase):+ """RAW_TEXT has no URL: absolute endpoints are still extracted, relative ones are skipped, and the rest of the event is still processed."""++ class DummyModule(BaseModule):+ watched_events = ["URL"]+ _name = "dummy_module"++ async def handle_event(self, event):+ raw_text = (+ f'<a href="{HTTPSERVER_URL}/absolute?abs_param=1">a</a>\n'+ '<a href="relative?rel_param=1">r</a>\n'+ f"{HTTPSERVER_URL}/fromtext"+ )+ await self.emit_event(raw_text, "RAW_TEXT", parent=event)++ targets = [f"{HTTPSERVER_URL}/"]+ modules_overrides = ["http", "excavate", "hunt"]++ async def setup_after_prep(self, module_test):+ module_test.scan.modules["dummy_module"] = self.DummyModule(module_test.scan)+ module_test.httpserver.expect_request("/").respond_with_data("hi")++ def check(self, module_test, events):+ raw_text_children = [e for e in events if getattr(e.parent, "type", "") == "RAW_TEXT"]+ params = {e.data["name"]: e.data["url"] for e in raw_text_children if e.type == "WEB_PARAMETER"}+ assert params.get("abs_param") == f"{HTTPSERVER_URL}/absolute", params+ assert "rel_param" not in params, params+ urls = {e.url for e in raw_text_children if e.type == "URL_UNVERIFIED"}+ assert f"{HTTPSERVER_URL}/fromtext" in urls, urls++class TestExcavateParameterExtraction_getparam_novalue(TestExcavateParameterExtraction_getparam):getparam_extract_html = """<section class=search>