Skip to content

armgit / bbot

Public Imported from GitHub
0

The recursive internet scanner for hackers. 🧡

Fix unbounded lightfuzz queue growth from parameter re-discovery loop (#3405)

Paul Mueller167a458b6b58
diff --git a/bbot/core/config/models.py b/bbot/core/config/models.py
index b6543951a..08c6233d0 100644
--- a/bbot/core/config/models.py
+++ b/bbot/core/config/models.py
@@ -397,6 +397,7 @@ class BBOTConfig(BaseModel):
# URL handling
url_querystring_remove: Optional[bool] = None
url_querystring_collapse: Optional[bool] = None
+ url_max_path_param_repeats: Optional[int] = None
url_extension_blacklist: Optional[list[str]] = None
url_extension_special: Optional[list[str]] = None
url_extension_static: Optional[list[str]] = None
diff --git a/bbot/core/event/base.py b/bbot/core/event/base.py
index f47144de2..efcf12c68 100644
--- a/bbot/core/event/base.py
+++ b/bbot/core/event/base.py
@@ -1641,9 +1641,24 @@ class WEB_PARAMETER(DictHostEvent):
log.verbose(f"Error detecting envelopes for {self}: {e}")
return data
+ def _dedup_url(self, url):
+ """The page the parameter lives on, with the query string reduced the way URL events
+ reduce theirs: parameter names are identity, their values are not unless
+ url_querystring_collapse is False. Ordering never is."""
+ base, sep, query = url.partition("?")
+ if not sep or self.scan is None:
+ return url
+ # keep_blank_values, or "?debug=" silently stops being a parameter
+ query_dict = parse_qs(query, keep_blank_values=True)
+ if self.scan.config.get("url_querystring_collapse", True):
+ kept = "|".join(sorted(query_dict.keys()))
+ else:
+ kept = "&".join(f"{k}={','.join(sorted(v))}" for k, v in sorted(query_dict.items()))
+ return f"{base}?{kept}"
+
def _data_id(self):
# dedupe by url:name:param_type
- url = self.data.get("url", "")
+ url = self._dedup_url(self.data.get("url", ""))
name = self.data.get("name", "")
param_type = self.data.get("type", "")
envelopes = getattr(self, "envelopes", "")
@@ -1655,7 +1670,7 @@ class WEB_PARAMETER(DictHostEvent):
return hash(
(
str(event.host),
- event.data["url"],
+ event._dedup_url(event.data["url"]),
event.data.get("name", ""),
event.data.get("type", ""),
event.data.get("envelopes", ""),
diff --git a/bbot/core/helpers/url.py b/bbot/core/helpers/url.py
index 91c7d8a01..2d7307415 100644
--- a/bbot/core/helpers/url.py
+++ b/bbot/core/helpers/url.py
@@ -1,5 +1,6 @@
import uuid
import logging
+from collections import Counter
from contextlib import suppress
from urllib.parse import urlparse, parse_qs, urlencode, ParseResult
@@ -211,6 +212,46 @@ def hash_url(url):
return hash(tuple(to_hash))
+def max_path_param_repeats(url):
+ """
+ Count how many times the most-repeated path parameter appears in a URL's path.
+
+ Path (matrix) parameters are the ";key=value" pieces a server may append to a path
+ segment; some reissue one on every redirect, so the path grows without bound. Keys are
+ compared case-insensitively. Ordinary path segments are deliberately not counted: a deep
+ path that repeats a directory name is finite, and depth is bounded by web_spider_depth.
+
+ Args:
+ url (Union[str, ParseResult]): The URL to inspect.
+
+ Returns:
+ int: The highest number of times any single path parameter appears.
+
+ Examples:
+ >>> max_path_param_repeats('https://www.evilcorp.com/foo/bar')
+ 0
+
+ >>> max_path_param_repeats('https://www.evilcorp.com/;JSESSIONID=a;JSESSIONID=b')
+ 2
+
+ >>> max_path_param_repeats('https://www.evilcorp.com/app;a=1/b;c=2')
+ 1
+ """
+ parsed = url if hasattr(url, "path") else parse_url(url)
+ # urlparse peels the final segment's matrix parameters off into .params
+ path = parsed.path
+ trailing_params = getattr(parsed, "params", "")
+ if trailing_params:
+ path = f"{path};{trailing_params}"
+ counts = Counter()
+ for segment in path.split("/"):
+ # the first ";"-delimited piece is the segment itself, not a parameter
+ for token in segment.split(";")[1:]:
+ if token:
+ counts[token.split("=", 1)[0].lower()] += 1
+ return max(counts.values(), default=0)
+
+
def url_depth(url):
"""
Calculate the depth of the given URL based on its path components.
diff --git a/bbot/defaults.yml b/bbot/defaults.yml
index cd34653e1..a152c4f1b 100644
--- a/bbot/defaults.yml
+++ b/bbot/defaults.yml
@@ -197,6 +197,8 @@ python: True
url_querystring_remove: True
# When query string is retained, by default collapse parameter values down to a single value per parameter
url_querystring_collapse: True
+# Reject URLs whose path repeats the same path parameter this many times (e.g. a session id appended on every redirect)
+url_max_path_param_repeats: 10
# Completely ignore URLs with these extensions
url_extension_blacklist:
diff --git a/bbot/modules/lightfuzz/lightfuzz.py b/bbot/modules/lightfuzz/lightfuzz.py
index a05e8071a..77796058a 100644
--- a/bbot/modules/lightfuzz/lightfuzz.py
+++ b/bbot/modules/lightfuzz/lightfuzz.py
@@ -50,6 +50,10 @@ class lightfuzz(BaseModule):
True,
description="Emit canonical baseline responses as HTTP_RESPONSE events so excavate can mine them for new params/URLs.",
)
+ max_baseline_generations: int = Field(
+ 10,
+ description="Stop emitting baseline responses once a parameter is this many lightfuzz generations deep, bounding excavate feedback loops.",
+ )
@field_validator("avoid_wafs", mode="before")
@classmethod
@@ -84,6 +88,8 @@ class lightfuzz(BaseModule):
avoid_wafs = "always" if avoid_wafs else "never"
self.avoid_wafs = avoid_wafs.strip().lower()
self.emit_baseline_responses = self.config.get("emit_baseline_responses", True)
+ self.max_baseline_generations = self.config.get("max_baseline_generations", 10)
+ self._baseline_generation_cap_hit = False
self.submodules = {}
# Per-event baseline cache so submodules with identical request signatures share one HttpCompare.
self._baseline_cache = {}
@@ -206,12 +212,42 @@ class lightfuzz(BaseModule):
"""Store an HttpCompare in the per-event baseline cache."""
self._baseline_cache.setdefault(event.id, {})[signature] = http_compare
+ def baseline_generations(self, event):
+ """How many lightfuzz-emitted events are already in this event's ancestry.
+
+ Every baseline response we emit is mined by excavate, which hands the parameters it
+ finds back to us. Pages that vary their form on each load (rotating CSRF tokens,
+ honeypot fields) make each round look new, so the chain is bounded by counting it.
+ """
+ count = 0
+ e = event
+ while 1:
+ parent = e.parent
+ # `is`, not `==`: Event equality is hash-of-id, so two distinct events carrying
+ # equal data would end the walk and undercount everything above them
+ if parent is None or parent is e:
+ break
+ if getattr(parent.module, "name", "") == self.name:
+ count += 1
+ if count >= self.max_baseline_generations:
+ break
+ e = parent
+ return count
+
async def emit_baseline_response(self, response, event, method):
"""Emit a baseline blasthttp Response as an HTTP_RESPONSE event so excavate can mine post-submit pages."""
if not self.emit_baseline_responses:
return
if response is None:
return
+ if self.baseline_generations(event) >= self.max_baseline_generations:
+ if not self._baseline_generation_cap_hit:
+ self._baseline_generation_cap_hit = True
+ self.verbose(
+ f"Reached max_baseline_generations ({self.max_baseline_generations}) on {event.host}; "
+ "no longer emitting baseline responses for parameters nested this deep"
+ )
+ return
try:
parsed = urlparse(str(response.url))
url_input = parsed.netloc or str(response.url)
diff --git a/bbot/scanner/manager.py b/bbot/scanner/manager.py
index b38ed0739..d9c7abccb 100644
--- a/bbot/scanner/manager.py
+++ b/bbot/scanner/manager.py
@@ -2,6 +2,7 @@ import asyncio
from contextlib import suppress
from radixtarget import host_size_key
+from bbot.core.helpers.url import max_path_param_repeats
from bbot.modules.base import BaseInterceptModule
@@ -104,6 +105,17 @@ class ScanIngress(BaseInterceptModule):
)
event.add_tag("blacklisted")
+ # reject degenerate URL paths, which servers generate in unbounded numbers
+ parsed_url = getattr(event, "parsed_url", None)
+ if parsed_url is not None and self.scan.url_max_path_param_repeats > 0:
+ repeats = max_path_param_repeats(parsed_url)
+ if repeats >= self.scan.url_max_path_param_repeats:
+ self.debug(
+ f"Blacklisting {event} because its path repeats a parameter {repeats:,} times "
+ f"(url_max_path_param_repeats={self.scan.url_max_path_param_repeats:,})"
+ )
+ event.add_tag("blacklisted")
+
# main scan blacklist
host_filterable = getattr(event, "host_filterable", None)
event_blacklisted = False
diff --git a/bbot/scanner/scanner.py b/bbot/scanner/scanner.py
index 2379dcd94..324049d98 100644
--- a/bbot/scanner/scanner.py
+++ b/bbot/scanner/scanner.py
@@ -285,6 +285,9 @@ class Scanner:
# url querystring behavior
self.url_querystring_remove = self.config.get("url_querystring_remove", True)
+ # reject URLs whose path repeats the same path parameter this many times
+ self.url_max_path_param_repeats = self.config.get("url_max_path_param_repeats", 10)
+
# blob inclusion
self._file_blobs = self.config.get("file_blobs", False)
self._folder_blobs = self.config.get("folder_blobs", False)
diff --git a/bbot/test/test_step_1/test_events.py b/bbot/test/test_step_1/test_events.py
index ed4010590..b43bc8b2f 100644
--- a/bbot/test/test_step_1/test_events.py
+++ b/bbot/test/test_step_1/test_events.py
@@ -1488,3 +1488,72 @@ async def test_web_parameter_minimize_sentinel():
assert "original_value" in event.data, "original_value stripped during distribution -- sentinel missing"
await scan._cleanup()
+
+
+async def test_web_parameter_querystring_dedup():
+ """A parameter is identified by its name and type on a page, not by the query string of
+ the request that revealed it. url_querystring_collapse=False opts back in to treating
+ sibling parameter values as significant, so those scans fuzz each variant separately."""
+
+ def make_param(scan, url, name="message", param_type="POSTPARAM"):
+ return scan.make_event(
+ {
+ "host": "example.com",
+ "type": param_type,
+ "name": name,
+ "original_value": "",
+ "url": url,
+ "description": f"{param_type} [{name}]",
+ },
+ "WEB_PARAMETER",
+ parent=scan.root_event,
+ )
+
+ base = "https://example.com/contact"
+ rotating_value = f"{base}?csrf=a08157098935259&id=6"
+ rotating_name = f"{base}?csrf=c19ae748d80ed939&id=6&aYBNT794ROfpo=0978126345"
+
+ # collapse=True (the default, and what lightfuzz/lightfuzz-light inherit): a page that
+ # reissues a token on every load is still one work item
+ scan = Scanner("example.com", config={"url_querystring_remove": False, "url_querystring_collapse": True})
+ await scan._prep()
+ a = make_param(scan, f"{base}?csrf=7f01d97aec3100c7&id=6")
+ e = make_param(scan, rotating_value)
+ assert a.data_id == e.data_id, "rotating parameter values must collapse"
+ assert hash(a) == hash(e)
+ assert a._outgoing_dedup_hash(a) == e._outgoing_dedup_hash(e)
+ # ...and ordering is not identity either
+ assert make_param(scan, f"{base}?id=6&csrf=7f01d97aec3100c7").data_id == a.data_id
+
+ # a page that invents a new parameter NAME on every load does not collapse here. dedup
+ # structurally cannot fold those together, so lightfuzz's max_baseline_generations is
+ # what bounds that loop
+ assert make_param(scan, rotating_name).data_id != a.data_id
+
+ # parameter names are part of the page's identity, so a front controller's pages stay
+ # separate work items while their values do not
+ assert make_param(scan, f"{base}?page=admin").data_id != make_param(scan, f"{base}?action=delete").data_id
+ assert make_param(scan, f"{base}?page=admin").data_id == make_param(scan, f"{base}?page=login").data_id
+
+ # a blank value is still a parameter
+ assert make_param(scan, f"{base}?debug=&id=6").data_id != make_param(scan, f"{base}?id=6").data_id
+
+ # a different parameter, page, or parameter type is still its own work item
+ assert make_param(scan, base, name="subject").data_id != a.data_id
+ assert make_param(scan, "https://example.com/other").data_id != a.data_id
+ assert make_param(scan, base, param_type="GETPARAM").data_id != a.data_id
+ await scan._cleanup()
+
+ # collapse=False (lightfuzz-max, lightfuzz-xss): sibling values are significant again
+ scan = Scanner("example.com", config={"url_querystring_remove": False, "url_querystring_collapse": False})
+ await scan._prep()
+ c = make_param(scan, f"{base}?csrf=7f01d97aec3100c7&id=6")
+ assert make_param(scan, rotating_value).data_id != c.data_id
+ assert make_param(scan, rotating_name).data_id != c.data_id
+ assert make_param(scan, base).data_id != c.data_id
+ # ...but the key still does not depend on parameter ordering
+ assert make_param(scan, f"{base}?id=6&csrf=7f01d97aec3100c7").data_id == c.data_id
+ # a blank value is significant in the mode whose whole point is that values are
+ assert make_param(scan, f"{base}?debug=&id=6").data_id != make_param(scan, f"{base}?id=6").data_id
+ await scan._cleanup()
diff --git a/bbot/test/test_step_1/test_helpers.py b/bbot/test/test_step_1/test_helpers.py
index d2a8505ba..a8f7ae8b6 100644
--- a/bbot/test/test_step_1/test_helpers.py
+++ b/bbot/test/test_step_1/test_helpers.py
@@ -45,6 +45,18 @@ async def test_helpers_misc(helpers, scan, bbot_scanner, bbot_httpserver):
with pytest.raises(ValueError):
helpers.validators.clean_url("http://evilcorp,com")
+ # path parameters accumulate inside a path segment, and are keyed by name
+ assert helpers.max_path_param_repeats("http://evilcorp.com/;JSESSIONID=a") == 1
+ assert helpers.max_path_param_repeats("http://evilcorp.com/;JSESSIONID=a;JSESSIONID=b;jsessionid=c") == 3
+ assert helpers.max_path_param_repeats("http://evilcorp.com/app;a=1;b=2") == 1
+ assert helpers.max_path_param_repeats("http://evilcorp.com/app;a=1/b;c=2") == 1
+ # ordinary path segments are not parameters, however deep or repetitive the path
+ assert helpers.max_path_param_repeats("http://evilcorp.com/") == 0
+ assert helpers.max_path_param_repeats("http://evilcorp.com/foo/bar") == 0
+ assert helpers.max_path_param_repeats("http://evilcorp.com/" + "/".join(["a"] * 30)) == 0
+ # the query string is not part of the path
+ assert helpers.max_path_param_repeats("http://evilcorp.com/foo?x=1&x=2&x=3") == 0
+
assert helpers.url_depth("http://evilcorp.com/asdf/user/") == 2
assert helpers.url_depth("http://evilcorp.com/asdf/user") == 2
assert helpers.url_depth("http://evilcorp.com/asdf/") == 1
diff --git a/bbot/test/test_step_1/test_scan.py b/bbot/test/test_step_1/test_scan.py
index 2fc2d60a1..67167afb3 100644
--- a/bbot/test/test_step_1/test_scan.py
+++ b/bbot/test/test_step_1/test_scan.py
@@ -520,3 +520,47 @@ async def test_memory_backpressure_drain_mode_bypass(bbot_scanner, monkeypatch):
assert m.num_incoming_events == 0
scan.modules_status(_log=False)
assert scan._ingress_delay == 0.0, "throttle must clear in drain mode (no producers, ingress is the drain)"
+
+
+async def test_url_max_path_param_repeats():
+ """Servers that append a session id on every redirect, and spider traps, generate an
+ unbounded supply of URLs whose path repeats one key. Ingress drops them."""
+ from bbot.scanner import Scanner
+
+ def jsessionid_url(n):
+ return "http://evilcorp.com/" + "".join(f";JSESSIONID={i:08x}-2ab9-49eb" for i in range(n))
+
+ scan = Scanner("evilcorp.com", config={"url_max_path_param_repeats": 10})
+ await scan._prep()
+ ingress = scan.ingress_module
+
+ # handle_event returns None when it accepts, and (False, reason) when it rejects
+
+ # below the limit the URL is scanned normally
+ shallow = scan.make_event(jsessionid_url(9), "URL_UNVERIFIED", parent=scan.root_event)
+ assert await ingress.handle_event(shallow) is None
+ assert "blacklisted" not in shallow.tags
+
+ # at the limit it is rejected before reaching any module's queue
+ degenerate = scan.make_event(jsessionid_url(10), "URL_UNVERIFIED", parent=scan.root_event)
+ assert await ingress.handle_event(degenerate) == (False, "event is blacklisted")
+ assert "blacklisted" in degenerate.tags
+
+ # ordinary URLs are untouched, however deep or repetitive the path
+ for url in (
+ "http://evilcorp.com/api/v1/users/1",
+ "http://evilcorp.com/" + "/".join(["blacklanternsecurity"] * 20) + ".txt",
+ ):
+ normal = scan.make_event(url, "URL_UNVERIFIED", parent=scan.root_event)
+ assert await ingress.handle_event(normal) is None
+ assert "blacklisted" not in normal.tags
+ await scan._cleanup()
+
+ # the guard can be disabled outright
+ scan = Scanner("evilcorp.com", config={"url_max_path_param_repeats": 0})
+ await scan._prep()
+ off = scan.make_event(jsessionid_url(50), "URL_UNVERIFIED", parent=scan.root_event)
+ await scan.ingress_module.handle_event(off)
+ assert "blacklisted" not in off.tags
+ await scan._cleanup()
diff --git a/bbot/test/test_step_2/module_tests/test_module_lightfuzz.py b/bbot/test/test_step_2/module_tests/test_module_lightfuzz.py
index 39715393a..30c5dd5f3 100644
--- a/bbot/test/test_step_2/module_tests/test_module_lightfuzz.py
+++ b/bbot/test/test_step_2/module_tests/test_module_lightfuzz.py
@@ -11,7 +11,9 @@ from urllib.parse import unquote, quote
import xml.etree.ElementTree as ET
+from bbot.scanner import Scanner
from bbot.core.helpers.url import add_get_params
+from bbot.modules.lightfuzz.lightfuzz import lightfuzz
from bbot.modules.base import BaseModule
from bbot.core.helpers.nowafpls import BypassResult
from bbot.modules.lightfuzz.submodules.base import BaseLightfuzz
@@ -78,6 +80,100 @@ def test_lightfuzz_build_query_string_preserves_fragment():
assert result.endswith("#frag")
+def _generation_chain(scan, depth, host="example.com", duplicate_at=None):
+ """An event whose ancestry contains `depth` lightfuzz-emitted events.
+
+ Built from real events, so the walk meets real parent links and real equality, which is
+ hash-of-id and therefore data equality. `duplicate_at` gives one generation's excavate and
+ lightfuzz events the same URL, making a parent and child equal without being the same
+ object, which is the shape that truncates a walk keyed on `==`.
+ """
+ modules = {name: scan._make_dummy_module(name) for name in ("http", "excavate", "lightfuzz")}
+ node = scan.make_event(f"https://{host}/", "URL_UNVERIFIED", parent=scan.root_event, module=modules["http"])
+ for i in range(depth):
+ excavate_url = f"https://{host}/g{i}"
+ lightfuzz_url = excavate_url if i == duplicate_at else f"{excavate_url}/probe"
+ node = scan.make_event(excavate_url, "URL_UNVERIFIED", parent=node, module=modules["excavate"])
+ node = scan.make_event(lightfuzz_url, "URL_UNVERIFIED", parent=node, module=modules["lightfuzz"])
+ return scan.make_event(f"https://{host}/leaf", "URL_UNVERIFIED", parent=node, module=modules["excavate"])
+
+
+def _fake_baseline_response(url):
+ return SimpleNamespace(
+ url=url,
+ status=200,
+ raw_headers="Content-Type: text/html",
+ headers={"Content-Type": "text/html", "Content-Length": "5"},
+ body_bytes=b"hello",
+ body="hello",
+ decode_error=None,
+ hash=SimpleNamespace(
+ body_md5="m", body_mmh3="m", body_sha256="s", header_md5="m", header_mmh3="m", header_sha256="s"
+ ),
+ cert_info=None,
+ )
+
+
+async def test_lightfuzz_baseline_generations_counts_ancestry():
+ fake = SimpleNamespace(name="lightfuzz", max_baseline_generations=10)
+ count = lightfuzz.baseline_generations
+ scan = Scanner("example.com")
+ await scan._prep()
+ assert count(fake, _generation_chain(scan, 0)) == 0
+ assert count(fake, _generation_chain(scan, 1)) == 1
+ assert count(fake, _generation_chain(scan, 7)) == 7
+ # counting stops at the cap instead of walking the rest of the chain
+ assert count(fake, _generation_chain(scan, 60)) == 10
+ # an ancestor that merely carries the same data as its parent must not end the walk,
+ # or every generation above it stops being counted and the cap never fires
+ assert count(fake, _generation_chain(scan, 7, duplicate_at=5)) == 7
+ await scan._cleanup()
+
+
+async def test_lightfuzz_baseline_generation_cap_stops_emitting():
+ """Baseline responses are what excavate mines to produce the next generation of
+ parameters, so past the cap they stop being emitted and the loop is starved."""
+ emitted = []
+
+ async def _emit_event(*args, **kwargs):
+ emitted.append(args)
+
+ def _fake_module(cap=3):
+ module = SimpleNamespace(
+ name="lightfuzz",
+ max_baseline_generations=cap,
+ emit_baseline_responses=True,
+ _baseline_generation_cap_hit=False,
+ emit_event=_emit_event,
+ verbose=lambda *a, **kw: None,
+ debug=lambda *a, **kw: None,
+ )
+ module.baseline_generations = lambda event: lightfuzz.baseline_generations(module, event)
+ return module
+
+ response = _fake_baseline_response("https://example.com/contact?csrf=abc")
+ scan = Scanner("example.com")
+ await scan._prep()
+
+ # below the cap, the feedback edge stays open
+ module = _fake_module()
+ await lightfuzz.emit_baseline_response(module, response, _generation_chain(scan, 2), "GET")
+ assert len(emitted) == 1
+ assert module._baseline_generation_cap_hit is False
+
+ # at the cap, excavate gets nothing new to mine
+ emitted.clear()
+ module = _fake_module()
+ await lightfuzz.emit_baseline_response(module, response, _generation_chain(scan, 3), "GET")
+ assert emitted == []
+ assert module._baseline_generation_cap_hit is True
+
+ # deeper still stays capped
+ await lightfuzz.emit_baseline_response(module, response, _generation_chain(scan, 9), "GET")
+ assert emitted == []
+ await scan._cleanup()
+
+
# Path Traversal single dot tolerance
class Test_Lightfuzz_path_singledot(ModuleTestBase):
targets = [HTTPSERVER_URL]