The recursive internet scanner for hackers. 🧡
Python asmattack-surface-managementautomationbugbountyclieasmhackingneo4josintosint-frameworkpentestingpythonreconrecursionscannersubdomain-enumerationsubdomain-scannersubdomainsthreat-intelligencethreatintel
Tighten lightfuzz serial Error Resolution (#3427)
Paul Muellerb2dd81af6110
diff --git a/bbot/modules/lightfuzz/lightfuzz.py b/bbot/modules/lightfuzz/lightfuzz.pyindex 77796058a..edaac38a6 100644--- a/bbot/modules/lightfuzz/lightfuzz.py+++ b/bbot/modules/lightfuzz/lightfuzz.py@@ -94,6 +94,9 @@ class lightfuzz(BaseModule):# Per-event baseline cache so submodules with identical request signatures share one HttpCompare.self._baseline_cache = {}+ # Scratch space for submodules needing state that outlives a single WEB_PARAMETER, keyed by submodule name.+ self.submodule_state = {}+# Cross-event baseline_probe response cache: sibling fields of the same form produce identical requests.self._baseline_probe_response_cache = {}self._baseline_probe_response_cache_max = 200diff --git a/bbot/modules/lightfuzz/submodules/serial.py b/bbot/modules/lightfuzz/submodules/serial.pyindex 54b600d6c..2048c80c1 100644--- a/bbot/modules/lightfuzz/submodules/serial.py+++ b/bbot/modules/lightfuzz/submodules/serial.py@@ -166,7 +166,6 @@ class serial(BaseLightfuzz):}SERIALIZATION_ERRORS = [- "invalid user","cannot cast java.lang.string","dump format error","java.io.optionaldataexception",@@ -178,6 +177,16 @@ class serial(BaseLightfuzz):"Internal Server Error",]+ # Baseline statuses that can represent an application-level failure to interpret the+ # payload, the only kind a deserializer could resolve. 3xx is not an error, 404 is+ # routing, 401/403/429 are policy, and 5xx above 500 is upstream infrastructure.+ ERROR_RESOLUTION_BASELINE_STATUSES = (500,)+ # Rounds of the interleaved trial a candidate must survive.+ ERROR_RESOLUTION_TRIAL_ROUNDS = 2+ # Distinct parameters per host allowed to produce Error Resolution findings. Beyond+ # this the signal is systemic to the host rather than specific to any parameter.+ ERROR_RESOLUTION_HOST_PARAM_CAP = 5+@propertydef general_error_yara_rules(self):return self.lightfuzz.serial_general_error_yara_rules@@ -233,12 +242,34 @@ class serial(BaseLightfuzz):return corrupted.hex().upper() if payload.isupper() else corrupted.hex()return base64.b64encode(corrupted).decode()- async def confirm_baseline(self, control_payload, cookies):- """Re-send the control payload to confirm the baseline error state is stable (not transient)."""- confirmation = await self.standard_probe(self.event.data["type"], cookies, control_payload)- if confirmation is None:- return None- return getattr(confirmation, "status_code", None)+ async def error_resolution_trial(self, payload, control_payload, encoding, cookies, resolved_status):+ """Sample payload/twin/control together for several rounds, requiring the payload to+ resolve the error and both negatives to preserve it every time.++ The twin parses like the payload but deserializes under nothing, so a twin that also+ resolves the error proves the outcome is independent of the payload's content.+ Interleaving the arms keeps the comparison within one window of server state.+ """+ twin = self.corrupt_payload(payload, encoding)+ if twin is None:+ return False+ for round_number in range(self.ERROR_RESOLUTION_TRIAL_ROUNDS):+ if round_number:+ await self.lightfuzz.helpers.sleep(0.5)+ for probe, arm, should_resolve in (+ (payload, "payload", True),+ (twin, "scrambled-header twin", False),+ (control_payload, "control", False),+ ):+ response = await self.standard_probe(self.event.data["type"], cookies, probe)+ status = getattr(response, "status_code", None)+ if status is None:+ self.debug(f"trial round {round_number}: no response for {arm}, inconclusive")+ return False+ if (status == resolved_status) is not should_resolve:+ self.debug(f"trial round {round_number}: {arm} returned {status}, discarding")+ return False+ return Trueasync def fuzz(self):cookies = self.event.data.get("assigned_cookies", {})@@ -307,57 +338,20 @@ class serial(BaseLightfuzz):self.debug(f"Status code {status_code} not in (200, 500), skipping")continue- baseline_status = payload_baseline.baseline.status_code- # Skip Error Resolution if baseline uses a non-standard HTTP status code (>511).- # Non-standard codes (e.g. 512 from GlobalProtect) are application-specific- # and don't reliably indicate an error state that deserialization could "resolve".- if baseline_status > 511:- self.debug(- f"Baseline status {baseline_status} is non-standard (>511), skipping Error Resolution for {payload_type}"- )- continue-- # Skip inherently unstable baselines: 429 (rate limit) and 403 (often WAF challenge pages)- # flip between error and success unpredictably, producing false positives.- if baseline_status in (403, 429):- self.debug(- f"Baseline status {baseline_status} is transient (WAF/rate-limit), "- f"skipping Error Resolution for {payload_type}"- )- continue-general_error_matches = await self.lightfuzz.helpers.yara.match(self.general_error_yara_rules, response.text)+ baseline_status = payload_baseline.baseline.status_codeif (status_code == 200and "code" in diff_reasons+ and baseline_status in self.ERROR_RESOLUTION_BASELINE_STATUSESand not general_error_matches # ensure the 200 is not actually an error):- # Confirm the baseline error state is stable by re-sending the control payload.- # If the control also returns 200 now, the original error was transient.- confirmation_status = await self.confirm_baseline(control_payload, cookies)- if confirmation_status == 200:- self.debug(- f"Baseline confirmation returned 200 for {payload_type}, original error was transient, skipping"- )+ if not await self.error_resolution_trial(payload, control_payload, encoding, cookies, status_code):+ self.debug(f"{payload_type} failed the Error Resolution trial, skipping")continue- # a same-shape twin with a scrambled header deserializes under nothing, so if it- # resolves the error too, the value is only being parsed (e.g. as a URL/host)- corrupted_payload = self.corrupt_payload(payload, encoding)- if corrupted_payload is not None:- corrupted_response = await self.standard_probe(- self.event.data["type"], cookies, corrupted_payload- )- corrupted_status = getattr(corrupted_response, "status_code", None)- if corrupted_status == status_code:- self.debug(- f"Corrupted twin of {payload_type} also returned {corrupted_status}, "- "outcome is independent of payload content, skipping"- )- continue-def get_title(text):soup = self.lightfuzz.helpers.beautifulsoup(text, "html.parser")if soup and soup.title and soup.title.string:@@ -372,7 +366,7 @@ class serial(BaseLightfuzz):"name": "Possible Unsafe Deserialization","severity": "HIGH","confidence": "LOW",- "description": f"POSSIBLE Unsafe Deserialization. {self.metadata()} Technique: [Error Resolution (Baseline: [{payload_baseline.baseline.status_code}] {baseline_title} -> Probe: [{status_code}] {probe_title})] Serialization Payload: [{payload_type}]",+ "description": f"POSSIBLE Unsafe Deserialization. {self.metadata()} Technique: [Error Resolution (Baseline: [{baseline_status}] {baseline_title} -> Probe: [{status_code}] {probe_title})] Serialization Payload: [{payload_type}]","_technique": "error_resolution","_language": self.payload_language(payload_type),}@@ -397,15 +391,21 @@ class serial(BaseLightfuzz):)break- # Final safety net: if Error Resolution findings span multiple language families, discard them.- # A real deserialization vuln only deserializes one language's format.+ # Final safety net, tracked per host: a sink deserializes one language's format, and a+ # host whose hits span several families (or too many parameters) is producing noise.error_resolution_results = [r for r in self.results if r.get("_technique") == "error_resolution"]if error_resolution_results:- languages = set(r["_language"] for r in error_resolution_results)- if len(languages) > 1:- self.debug(- f"Error Resolution findings span multiple language families ({languages}), discarding as false positives"- )+ state = self.lightfuzz.submodule_state.setdefault("serial", {})+ host_state = state.setdefault(str(self.event.host), {"languages": set(), "parameters": set()})+ host_state["languages"].update(r["_language"] for r in error_resolution_results)+ host_state["parameters"].add(self.parameter_name)+ discard_reason = None+ if len(host_state["languages"]) > 1:+ discard_reason = f"host hit multiple language families ({sorted(host_state['languages'])})"+ elif len(host_state["parameters"]) > self.ERROR_RESOLUTION_HOST_PARAM_CAP:+ discard_reason = f"host exceeded {self.ERROR_RESOLUTION_HOST_PARAM_CAP} Error Resolution parameters"+ if discard_reason:+ self.verbose(f"Discarding Error Resolution findings: {discard_reason}")self.results = [r for r in self.results if r.get("_technique") != "error_resolution"]# Clean up internal metadata keys before results are emitteddiff --git a/bbot/test/test_step_2/module_tests/test_module_lightfuzz.py b/bbot/test/test_step_2/module_tests/test_module_lightfuzz.pyindex 30c5dd5f3..94a2a9327 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@@ -17,6 +17,7 @@ from bbot.modules.lightfuzz.lightfuzz import lightfuzzfrom bbot.modules.base import BaseModulefrom bbot.core.helpers.nowafpls import BypassResultfrom bbot.modules.lightfuzz.submodules.base import BaseLightfuzz+from bbot.modules.lightfuzz.submodules.serial import serial as serial_submodulefrom .test_module_paramminer_headers import helperfrom bbot.test.worker import HTTPSERVER_URL@@ -2067,7 +2068,8 @@ class Test_Lightfuzz_serial_errordifferential_falsepositive(Test_Lightfuzz_seriaelse:dotnet_serial_reflection = (- f"<html><body><p>invalid user</p><p>reflected input: {post_params['TextBox1']}</body></html>"+ "<html><body><p>java.io.OptionalDataException</p>"+ f"<p>reflected input: {post_params['TextBox1']}</body></html>")return Response(dotnet_serial_reflection, status=500)@@ -2080,8 +2082,8 @@ class Test_Lightfuzz_serial_errordifferential_falsepositive(Test_Lightfuzz_seria# Serialization Module (Error Resolution - Transient Baseline)-# Simulates a server that returns 500 on the first request (baseline), then 200 for everything after.-# The confirmation re-send of the control payload should catch this and suppress the finding.+# A server whose error state does not survive the first request has no baseline to resolve,+# so no finding may be reported.class Test_Lightfuzz_serial_errorresolution_transient_baseline(Test_Lightfuzz_serial_errorresolution):request_count = 0@@ -2106,9 +2108,42 @@ class Test_Lightfuzz_serial_errorresolution_transient_baseline(Test_Lightfuzz_seassert no_finding_emitted, "False positive Error Resolution finding was emitted despite transient baseline"+# Magic headers identifying a serialized object of each language family. A handler keyed on+# these accepts every real payload while rejecting the controls and the scrambled-header twins.+JAVA_SERIAL_HEADER = b"\xac\xed\x00\x05"+DOTNET_SERIAL_HEADER = b"\x00\x01\x00\x00"+SERIAL_MAGIC_HEADERS = (JAVA_SERIAL_HEADER, DOTNET_SERIAL_HEADER, b"\x80\x04", b"\x04\x08", b"a:")+++def carries_serialization_header(value):+ """True if ``value`` decodes (raw, base64, or hex) to a recognized serialization header."""+ candidates = [value.encode()]+ for decoder in (base64.b64decode, bytes.fromhex):+ try:+ candidates.append(decoder(value))+ except Exception:+ pass+ return any(c.startswith(SERIAL_MAGIC_HEADERS) for c in candidates)+++def error_resolution_languages(events):+ """Language families named by the Error Resolution findings in ``events``."""+ languages = set()+ for e in events:+ if e.type != "FINDING":+ continue+ description = e.data.get("description", "")+ if "Error Resolution" not in description:+ continue+ match = re.search(r"Serialization Payload: \[([a-z0-9_]+)\]", description)+ if match:+ languages.add(match.group(1).split("_")[0])+ return languages++# Serialization Module (Error Resolution - Multi-Language Family False Positive)-# Simulates a server where ALL serialization payloads resolve the error (500->200),-# spanning multiple language families. The multi-family check should discard them all.+# A host that resolves its error for several language families is not deserializing any one of+# them, so none of its Error Resolution findings may be reported.class Test_Lightfuzz_serial_errorresolution_multi_language(Test_Lightfuzz_serial_errorresolution):def request_handler(self, request):post_params = request.form@@ -2116,21 +2151,13 @@ class Test_Lightfuzz_serial_errorresolution_multi_language(Test_Lightfuzz_serialif "TextBox1" not in post_params.keys():return Response(self.dotnet_serial_html, status=200)- # __VIEWSTATE mismatch triggers the baseline path- if post_params["__VIEWSTATE"] != "/wEPDwULLTE5MTI4MzkxNjVkZNt7ICM+GixNryV6ucx+srzhXlwP":- return Response(self.dotnet_serial_error, status=500)-- # ALL payloads "resolve" the error - this is the false positive scenario- return Response("<html><body>OK</body></html>", status=200)+ if carries_serialization_header(post_params["TextBox1"]):+ return Response("<html><body>OK</body></html>", status=200)+ return Response(self.dotnet_serial_error, status=500)def check(self, module_test, events):- no_finding_emitted = True- for e in events:- if e.type == "FINDING" and "Error Resolution" in e.data.get("description", ""):- no_finding_emitted = False- assert no_finding_emitted, (- "False positive Error Resolution finding was emitted despite multiple language families triggering"- )+ languages = error_resolution_languages(events)+ assert not languages, f"Error Resolution findings emitted for multiple language families: {languages}"class Test_Lightfuzz_serial_errorresolution_nonstandard_status(Test_Lightfuzz_serial_errorresolution):@@ -2165,6 +2192,141 @@ class Test_Lightfuzz_serial_errorresolution_nonstandard_status(Test_Lightfuzz_se)+# Serialization Module (Error Resolution - Non-Error Baseline)+# Error Resolution infers a deserializer from an application-level failure to interpret the+# payload. A baseline that is not such a failure cannot be resolved, whatever the probe returns.+class _SerialNonErrorBaseline(Test_Lightfuzz_serial_errorresolution):+ def request_handler(self, request):+ post_params = request.form+ if "TextBox1" not in post_params.keys():+ return Response(self.dotnet_serial_html, status=200)+ if post_params["TextBox1"] == "AAEAAAD/////AQAAAAAAAAAGAQAAAAdndXN0YXZvCw==":+ return Response("<html><body>Deserialization successful!</body></html>", status=200)+ return Response(self.dotnet_serial_error, status=self.baseline_status)++ def check(self, module_test, events):+ findings = [+ e.data["description"]+ for e in events+ if e.type == "FINDING" and "Error Resolution" in e.data.get("description", "")+ ]+ assert not findings, f"Error Resolution finding emitted for a [{self.baseline_status}] baseline: {findings}"+++class Test_Lightfuzz_serial_errorresolution_gateway_baseline(_SerialNonErrorBaseline):+ baseline_status = 503+++class Test_Lightfuzz_serial_errorresolution_redirect_baseline(_SerialNonErrorBaseline):+ baseline_status = 302+++class Test_Lightfuzz_serial_errorresolution_routing_baseline(_SerialNonErrorBaseline):+ baseline_status = 404+++# Serialization Module (Error Resolution - Unstable Control)+# The error state must hold for the control across the whole trial, not just while the baseline+# is established, so a control that starts succeeding mid-trial withdraws the finding.+class Test_Lightfuzz_serial_errorresolution_unstable_control(Test_Lightfuzz_serial_errorresolution):+ control_request_count = 0++ def request_handler(self, request):+ post_params = request.form+ if "TextBox1" not in post_params.keys():+ return Response(self.dotnet_serial_html, status=200)++ submitted = post_params["TextBox1"]+ if submitted == serial_submodule.CONTROL_PAYLOAD_BASE64:+ self.control_request_count += 1+ # the baseline pair and the first trial round error, later control samples succeed+ if self.control_request_count > 3:+ return Response("<html><body>OK</body></html>", status=200)+ elif submitted == "AAEAAAD/////AQAAAAAAAAAGAQAAAAdndXN0YXZvCw==":+ return Response("<html><body>Deserialization successful!</body></html>", status=200)+ return Response(self.dotnet_serial_error, status=500)++ def check(self, module_test, events):+ findings = [+ e.data["description"]+ for e in events+ if e.type == "FINDING" and "Error Resolution" in e.data.get("description", "")+ ]+ assert not findings, f"Error Resolution finding emitted despite an unstable control: {findings}"+++# Serialization Module (Error Resolution - Multi-Language Family Across Parameters)+# The single-language-family invariant holds for the host, not for one parameter, so families+# split across two parameters must still collapse to one.+class Test_Lightfuzz_serial_errorresolution_multi_language_per_host(Test_Lightfuzz_serial_errorresolution):+ dotnet_serial_html = """+ <!DOCTYPE html>+ <html>+ <head><title>+ Deserialization RCE Example+ </title></head>+ <body>+ <form method="post" action="./deser.aspx" id="form1">+ <div>+ <textarea name="TextBox1" rows="2" cols="20" id="TextBox1"></textarea><br />+ <textarea name="TextBox2" rows="2" cols="20" id="TextBox2"></textarea><br />+ <input type="submit" name="Button1" value="Submit" id="Button1" />+ </div>+ </form>+ </body>+ </html>+ """++ def request_handler(self, request):+ post_params = request.form+ if "TextBox1" not in post_params.keys() and "TextBox2" not in post_params.keys():+ return Response(self.dotnet_serial_html, status=200)++ # TextBox1 accepts only java, TextBox2 only dotnet+ for field, header in (("TextBox1", JAVA_SERIAL_HEADER), ("TextBox2", DOTNET_SERIAL_HEADER)):+ value = post_params.get(field, "")+ if value:+ try:+ decoded = base64.b64decode(value)+ except Exception:+ decoded = b""+ if decoded.startswith(header):+ return Response("<html><body>OK</body></html>", status=200)+ return Response(self.dotnet_serial_error, status=500)++ def check(self, module_test, events):+ languages = error_resolution_languages(events)+ assert languages, "No Error Resolution finding was emitted for either parameter"+ assert len(languages) == 1, f"Error Resolution findings spanned multiple language families: {languages}"+++# Serialization Module (Differential Error Analysis - Non-Error Baseline)+# Differential Error Analysis rests on a framework error string appearing in the probe and not+# the baseline, so it stays available whatever status the baseline carries.+class Test_Lightfuzz_serial_errordifferential_nonstandard_baseline(Test_Lightfuzz_serial_errorresolution):+ java_cast_error = """+ <html>+ <p>java.lang.ClassCastException: Cannot cast java.lang.String to com.example.User</p>+ </html>+ """++ def request_handler(self, request):+ post_params = request.form+ if "TextBox1" not in post_params.keys():+ return Response(self.dotnet_serial_html, status=200)+ if post_params["TextBox1"] == "rO0ABXQABHRlc3Q=":+ return Response(self.java_cast_error, status=500)+ return Response(self.dotnet_serial_error, status=512)++ def check(self, module_test, events):+ assert any(+ e.type == "FINDING"+ and "Technique: [Differential Error Analysis]" in e.data.get("description", "")+ and "Error-String: [cannot cast java.lang.string]" in e.data.get("description", "")+ for e in events+ ), "Differential Error Analysis was not reported for a non-standard baseline status"++# Python pickle Error Resolution — verifies the new python_pickle_base64# payload flips a baseline UnpicklingError 500 into a 200, which is the# canonical detection path for all languages in the serial submodule.