xssmap 2.8.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
xssmap/domscan.py ADDED
@@ -0,0 +1,1098 @@
1
+ """DOM-based XSS: static taint flow plus runtime proof.
2
+
3
+ Server-side reflection scanning cannot see DOM XSS. The dangerous flow lives
4
+ entirely in JavaScript: a *source* (``location.search``, ``location.hash``,
5
+ ``document.referrer``, ``window.name``, storage) reaches a *sink*
6
+ (``innerHTML``, ``document.write``, ``eval``, ``location.href`` ...).
7
+
8
+ What this module does:
9
+
10
+ 1. Parses every JS resource the crawler found (inline blocks and bundles).
11
+ 2. Builds a light taint graph: variables assigned from a source, then variables
12
+ assigned from those variables (fixpoint, so ``a = location.hash; b = a`` counts).
13
+ 3. Records each sink that consumes a tainted value, including the parameter name
14
+ when the code reads one (``URLSearchParams(location.search).get('q')``).
15
+ 4. Notices hardening in the flow (DOMPurify, ``createPolicy``, an escape call)
16
+ so a sanitised flow is reported as a lead rather than as a vulnerability.
17
+ 5. Verifies the surviving flows in a real browser by driving the page with a
18
+ payload that creates a DOM artifact, and only claims DOM XSS if the artifact
19
+ appears.
20
+
21
+ Static flow is labelled *inferred* in the report; only the browser step proves it.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import os
27
+ import re
28
+ import time
29
+ import urllib.parse
30
+ import uuid
31
+ from dataclasses import dataclass, field
32
+
33
+ from . import domstate
34
+
35
+ # -- sources ---------------------------------------------------------------
36
+ SOURCES = {
37
+ "location.search": "query",
38
+ "document.location.search": "query",
39
+ "location.hash": "hash",
40
+ "document.location.hash": "hash",
41
+ "location.href": "url",
42
+ "document.location.href": "url",
43
+ "document.URL": "url",
44
+ "document.documentURI": "url",
45
+ "document.referrer": "referrer",
46
+ "window.name": "window.name",
47
+ "document.cookie": "cookie",
48
+ "localStorage": "storage",
49
+ "sessionStorage": "storage",
50
+ "document.baseURI": "url",
51
+ # Framework router hooks: they expose the same URL state under a name the
52
+ # plain location.* patterns cannot see.
53
+ "useSearchParams": "query",
54
+ "useLocation": "url",
55
+ "useParams": "url",
56
+ "useRoute": "query",
57
+ "$route.query": "query",
58
+ "route.query": "query",
59
+ "URLSearchParams": "query",
60
+ "location.pathname": "url",
61
+ }
62
+ # Server-rendered state the client re-reads after hydration. The payload does not
63
+ # have to be reflected into markup: it only has to land in the blob, and the
64
+ # bundle hands it to a sink on the client.
65
+ SOURCES.update({name: "query" for name in domstate.HYDRATION_SOURCES})
66
+
67
+ SOURCE_RX = re.compile(
68
+ r"(?P<src>"
69
+ + "|".join(re.escape(s) for s in sorted(SOURCES, key=len, reverse=True))
70
+ + r")(?![\w$])"
71
+ )
72
+
73
+ # Sources that are a *shape*, not a name: server-rendered JSON handed to the page
74
+ # through a data- attribute (`el.dataset.state`, `getAttribute('data-boot')`).
75
+ STRUCTURAL_SOURCE_RX = re.compile(
76
+ r"(?P<src>\.dataset(?:\.(?P<one>[A-Za-z_$][\w$]{0,40})"
77
+ r"|\[\s*['\"](?P<two>[^'\"]{1,40})['\"]\s*\])"
78
+ r"|getAttribute\s*\(\s*['\"](?P<attr>data-[^'\"]{1,60})['\"]\s*\))"
79
+ )
80
+ STRUCTURAL_DELIVERY = "query"
81
+
82
+ # -- sinks -----------------------------------------------------------------
83
+ SINKS = [
84
+ ("innerHTML", re.compile(r"\.innerHTML\s*\+?=")),
85
+ ("outerHTML", re.compile(r"\.outerHTML\s*\+?=")),
86
+ ("insertAdjacentHTML", re.compile(r"\.insertAdjacentHTML\s*\(")),
87
+ ("document.write", re.compile(r"document\.write(?:ln)?\s*\(")),
88
+ ("eval", re.compile(r"(?<![\w$.])eval\s*\(")),
89
+ ("Function", re.compile(r"new\s+Function\s*\(")),
90
+ ("setTimeout-string", re.compile(r"setTimeout\s*\(\s*[^,)]*[a-zA-Z_$][\w$]*\s*[,)]")),
91
+ ("location.assign", re.compile(r"location\.assign\s*\(")),
92
+ ("location.href=", re.compile(r"location\.href\s*=")),
93
+ ("window.open", re.compile(r"window\.open\s*\(")),
94
+ ("jquery-html", re.compile(r"\.html\s*\(")),
95
+ ("jquery-append", re.compile(r"\.(?:append|prepend|after|before|replaceWith|wrap)\s*\(")),
96
+ ("srcdoc", re.compile(r"\.srcdoc\s*=")),
97
+ ("script-src", re.compile(r"createElement\s*\(\s*['\"]script['\"]")),
98
+ # Framework template escape hatches: React, Vue and Angular each have an
99
+ # explicit "this string is HTML" API, and bundles keep their names.
100
+ ("dangerouslySetInnerHTML", re.compile(r"dangerouslySetInnerHTML\s*[:=]")),
101
+ ("v-html", re.compile(r"v-html\s*=")),
102
+ ("bypassSecurityTrustHtml", re.compile(r"\.bypassSecurityTrustHtml\s*\(")),
103
+ ("createContextualFragment", re.compile(r"createContextualFragment\s*\(")),
104
+ ("jquery-parseHTML", re.compile(r"\.parseHTML\s*\(")),
105
+ ]
106
+
107
+ HARDENING_RX = re.compile(
108
+ r"(?P<kind>DOMPurify|createPolicy|TrustedTypes|trustedTypes|encodeURIComponent|"
109
+ r"escapeHtml|sanitize\w*|textContent|innerText|createTextNode)",
110
+ re.I,
111
+ )
112
+
113
+ GET_PARAM_RX = re.compile(r"""\.get\s*\(\s*['"]([^'"]{1,60})['"]\s*\)""")
114
+ PARAM_RX = re.compile(r"""(?:getParameterByName|getParam|param|query)\s*\(\s*['"]([^'"]{1,60})['"]""")
115
+ ASSIGN_RX = re.compile(
116
+ r"(?:^|[;{}\n,(])\s*(?:var|let|const)?\s*([A-Za-z_$][\w$]{0,40})\s*=\s*([^;\n]{0,400})"
117
+ )
118
+ # $route.query.q / route.query['q'] (Vue Router) and other property reads.
119
+ QUERY_PROP_RX = re.compile(r"query\.([A-Za-z_$][\w$]{0,60})")
120
+ QUERY_INDEX_RX = re.compile(r"query\[\s*['\"]([^'\"]{1,60})['\"]\s*\]")
121
+ # Destructuring router hooks: const [sp] = useSearchParams(), {search} = useLocation()
122
+ HOOK_BIND_RX = re.compile(
123
+ r"(?:const|let|var)\s*[\[{]\s*([A-Za-z_$][\w$]{0,40})[^\]}]*[\]}]\s*=\s*"
124
+ r"(useSearchParams|useLocation|useParams|useRoute)\s*\("
125
+ )
126
+ # Shapes the `var x = expr` pass cannot see: a value parked on an object
127
+ # property, appended to an array that is rendered later, or pushed into a React
128
+ # hook's state setter. All three are the same flow with a different carrier.
129
+ PROP_ASSIGN_RX = re.compile(
130
+ r"([A-Za-z_$][\w$]{0,40})\.([A-Za-z_$][\w$]{0,40})\s*=(?!=)\s*([^;\n]{0,300})"
131
+ )
132
+ PUSH_RX = re.compile(r"([A-Za-z_$][\w$]{0,40})\.(?:push|unshift)\s*\(\s*([^;\n]{0,200})")
133
+ HOOK_STATE_RX = re.compile(
134
+ r"(?:const|let|var)\s*\[\s*([A-Za-z_$][\w$]{0,40})\s*,\s*"
135
+ r"([A-Za-z_$][\w$]{0,40})\s*\]\s*=\s*useState"
136
+ )
137
+ SETTER_CALL_RX = re.compile(r"([A-Za-z_$][\w$]{0,40})\s*\(\s*([^;\n]{0,240})")
138
+ # Carriers that are themselves globals or sinks: treating them as taint stores
139
+ # only adds noise, and the sink match already sees the source in the statement.
140
+ NON_STORE_OBJECTS = {"window", "document", "location", "console", "JSON", "Math",
141
+ "Object", "Array", "Number", "String", "Date", "this", "self"}
142
+ SINK_PROPERTIES = {"innerHTML", "outerHTML", "srcdoc", "href", "src", "action"}
143
+ STATEMENT_SPLIT = re.compile(r"[;\n]")
144
+
145
+
146
+ @dataclass
147
+ class DomCandidate:
148
+ resource: str
149
+ sink: str
150
+ source: str
151
+ parameter: str
152
+ delivery: str # query | hash | url | referrer | window.name | cookie | storage
153
+ taint_chain: list[str] = field(default_factory=list)
154
+ sink_snippet: str = ""
155
+ flow_snippet: str = ""
156
+ hardening: str = ""
157
+ line: int = 0
158
+ page: str = "" # page that loads the code (verification host)
159
+ confidence: str = "medium" # medium until the browser proves it
160
+ # Cross-resource flows: the value was parked in a store and read later.
161
+ store: str = "" # localStorage | sessionStorage | state | dispatch
162
+ store_key: str = ""
163
+ write_page: str = "" # page that performs the store write
164
+ write_line: int = 0
165
+ two_step: bool = False # verification must drive the write step first
166
+ param_guesses: list[str] = field(default_factory=list)
167
+
168
+ def key(self) -> str:
169
+ return f"{self.resource}|{self.sink}|{self.parameter}|{self.delivery}"
170
+
171
+ def summary(self) -> str:
172
+ chain = " -> ".join(self.taint_chain) if self.taint_chain else self.source
173
+ if self.store:
174
+ hop = f"{self.store}.{self.store_key}"
175
+ if not chain.endswith(hop):
176
+ chain = f"{chain} -> {hop}"
177
+ return f"{chain} reaches {self.sink}()"
178
+
179
+
180
+ def _line_of(body: str, offset: int) -> int:
181
+ return body.count("\n", 0, offset) + 1
182
+
183
+
184
+ def _statement_at(body: str, offset: int, radius: int = 260) -> str:
185
+ """Grab a readable statement window around an offset (works on minified code).
186
+
187
+ Some callers hand over the start of a match whose pattern begins with a
188
+ delimiter (``ASSIGN_RX`` matches ``{var x =``), so an offset sitting *on* a
189
+ ``;``/newline would otherwise return the previous statement -- which silently
190
+ attached the wrong origin (``location.hash`` became ``query``) to a flow.
191
+ """
192
+ while offset < len(body) and body[offset] in ";\n":
193
+ offset += 1
194
+ starts = [m.end() for m in STATEMENT_SPLIT.finditer(body, 0, offset)]
195
+ start = starts[-1] if starts else max(0, offset - radius)
196
+ end_match = STATEMENT_SPLIT.search(body, offset)
197
+ end = end_match.start() if end_match else min(len(body), offset + radius)
198
+ snippet = body[start:end].strip()
199
+ return snippet[:400]
200
+
201
+
202
+ # Wrappers expose URL state but hide which part of the URL it came from.
203
+ WRAPPER_SOURCES = {"URLSearchParams", "useSearchParams", "useRoute",
204
+ "useLocation", "useParams"}
205
+
206
+
207
+ def _struct_name(match: re.Match[str]) -> str:
208
+ groups = match.groupdict()
209
+ name = groups.get("src") or ""
210
+ if "dataset" in name:
211
+ return "dataset"
212
+ if groups.get("attr") or name.startswith("getAttribute"):
213
+ return "data-attribute"
214
+ return name
215
+
216
+
217
+ def find_source(text: str) -> str:
218
+ """Name of the request-derived source in *text*, or ''.
219
+
220
+ The literal table covers named APIs; ``STRUCTURAL_SOURCE_RX`` covers the
221
+ shape-only cases (``.dataset.state``), where the element name is the store.
222
+ Among several hits the concrete origin wins over the wrapper around it:
223
+ ``new URLSearchParams(location.search)`` reports ``location.search``, which is
224
+ what telling query from fragment delivery depends on.
225
+ """
226
+ hits = [(m.start(), m.group("src")) for m in SOURCE_RX.finditer(text)]
227
+ struct = STRUCTURAL_SOURCE_RX.search(text)
228
+ if struct:
229
+ hits.append((struct.start(), _struct_name(struct)))
230
+ if not hits:
231
+ return ""
232
+ direct = [hit for hit in hits if hit[1] not in WRAPPER_SOURCES]
233
+ hits = direct or hits
234
+ hits.sort(key=lambda hit: hit[0])
235
+ return hits[0][1]
236
+
237
+
238
+ def _rhs_source(rhs: str, taint: dict) -> tuple[str, str] | None:
239
+ """(source, delivery) for a right-hand side, following already-tainted names."""
240
+ source = find_source(rhs)
241
+ if source:
242
+ return source, _delivery_for(source, rhs)
243
+ for other, (other_source, delivery, _line) in taint.items():
244
+ if re.search(r"(?<![\w$.])" + re.escape(other) + r"(?![\w$])", rhs):
245
+ return other_source, delivery
246
+ return None
247
+
248
+
249
+ def _build_taint(body: str) -> dict[str, tuple[str, str, int]]:
250
+ """variable -> (source, delivery, line), propagated through assignments."""
251
+ taint: dict[str, tuple[str, str, int]] = {}
252
+
253
+ # 0. destructured router hooks do not use the `x = expr` shape, so bind
254
+ # them before the generic assignment pass.
255
+ for m in HOOK_BIND_RX.finditer(body):
256
+ var, hook = m.group(1), m.group(2)
257
+ source = "$route.query" if hook == "useRoute" else hook
258
+ taint.setdefault(var, (source, SOURCES.get(source, "query"),
259
+ _line_of(body, m.start())))
260
+
261
+ # 0b. carriers other than a plain variable: `holder.value = <src>`,
262
+ # `items.push(<src>)`, and a React hook's `setDraft(<src>)` (the value
263
+ # is read back as `draft`, so the state variable is what gets tainted).
264
+ hooks = {setter: state for state, setter in HOOK_STATE_RX.findall(body)}
265
+
266
+ # 1. propagate taint through assignments (three passes handle short chains)
267
+ for _ in range(3):
268
+ for m in PROP_ASSIGN_RX.finditer(body):
269
+ obj, prop, rhs = m.group(1), m.group(2), m.group(3)
270
+ carrier = f"{obj}.{prop}"
271
+ if obj in NON_STORE_OBJECTS or prop in SINK_PROPERTIES or carrier in taint:
272
+ continue
273
+ found = _rhs_source(rhs, taint)
274
+ if found:
275
+ taint[carrier] = (found[0], found[1], _line_of(body, m.start()))
276
+ for m in PUSH_RX.finditer(body):
277
+ array, rhs = m.group(1), m.group(2)
278
+ if array in taint:
279
+ continue
280
+ found = _rhs_source(rhs, taint)
281
+ if found:
282
+ taint[array] = (found[0], found[1], _line_of(body, m.start()))
283
+ for m in SETTER_CALL_RX.finditer(body):
284
+ setter, rhs = m.group(1), m.group(2)
285
+ state = hooks.get(setter)
286
+ if not state or state in taint:
287
+ continue
288
+ found = _rhs_source(rhs, taint)
289
+ if found:
290
+ taint[state] = (found[0], found[1], _line_of(body, m.start()))
291
+ for m in ASSIGN_RX.finditer(body):
292
+ var, rhs = m.group(1), m.group(2)
293
+ if var in taint:
294
+ continue
295
+ source = find_source(rhs)
296
+ if source:
297
+ # Delivery is decided at the assignment, where the real origin is
298
+ # visible: `new URLSearchParams(location.hash.slice(1))` reads the
299
+ # fragment even though the wrapper alone says "query".
300
+ origin = _statement_at(body, m.start(1)) or rhs
301
+ taint[var] = (source, _delivery_for(source, origin),
302
+ _line_of(body, m.start()))
303
+ continue
304
+ for other, (other_source, delivery, _line) in list(taint.items()):
305
+ if re.search(r"(?<![\w$.])" + re.escape(other) + r"(?![\w$])", rhs):
306
+ taint[var] = (other_source, delivery, _line_of(body, m.start()))
307
+ break
308
+ return taint
309
+
310
+
311
+ def analyze_js(resource: str, body: str, max_candidates: int = 40,
312
+ taint: dict | None = None) -> list[DomCandidate]:
313
+ """Return source→sink flows found in one JavaScript resource."""
314
+ if not body:
315
+ return []
316
+ if taint is None:
317
+ taint = _build_taint(body)
318
+ candidates: list[DomCandidate] = []
319
+ seen: set[str] = set()
320
+
321
+ # 2. find sinks whose statement consumes tainted data or a source directly
322
+ for sink_name, sink_rx in SINKS:
323
+ for m in sink_rx.finditer(body):
324
+ if len(candidates) >= max_candidates:
325
+ break
326
+ stmt = _statement_at(body, m.start())
327
+ if not stmt:
328
+ continue
329
+ direct = find_source(stmt)
330
+ tainted_vars = [v for v in taint
331
+ if re.search(r"(?<![\w$.])" + re.escape(v) + r"(?![\w$])", stmt)]
332
+ if not direct and not tainted_vars:
333
+ continue
334
+ if direct:
335
+ source = direct
336
+ delivery = _delivery_for(source, stmt)
337
+ chain = [source]
338
+ else:
339
+ # prefer the variable closest to the sink call
340
+ tainted_vars.sort(key=lambda v: stmt.rfind(v), reverse=True)
341
+ var = tainted_vars[0]
342
+ source, delivery, _line = taint[var]
343
+ delivery = _delivery_for(source, stmt, delivery)
344
+ chain = [source, var] + [v for v in tainted_vars[1:3]]
345
+ param = _param_for(body, m.start(), stmt)
346
+ if source in domstate.HYDRATION_SOURCES or source in ("dataset", "data-attribute"):
347
+ # Server-rendered state: the parameter is the server's choice, not
348
+ # something the bundle names, so verification has to guess it.
349
+ param = ""
350
+ hardening = ""
351
+ hm = HARDENING_RX.search(stmt)
352
+ if hm:
353
+ hardening = hm.group("kind")
354
+ harden_par = _hardening_before(body, m.start(), source)
355
+ key = f"{sink_name}|{param}|{delivery}|{source}"
356
+ if key in seen:
357
+ continue
358
+ seen.add(key)
359
+ candidates.append(DomCandidate(
360
+ resource=resource,
361
+ sink=sink_name,
362
+ source=source,
363
+ parameter=param,
364
+ delivery=delivery,
365
+ taint_chain=chain,
366
+ sink_snippet=stmt,
367
+ flow_snippet=_flow_snippet(body, source, taint, sink_name),
368
+ hardening=hardening or harden_par,
369
+ line=_line_of(body, m.start()),
370
+ ))
371
+ return candidates
372
+
373
+
374
+ def _delivery_for(source: str, stmt: str, default: str | None = None) -> str:
375
+ """Which part of the URL the flow actually reads.
376
+
377
+ A wrapper hides the real origin: ``new URLSearchParams(location.hash.slice(1))``
378
+ reads the fragment, not the query string, and ``URLSearchParams`` alone is
379
+ mapped to ``query``. Left that way the browser is driven with ``?q=payload``
380
+ on a page that only ever reads ``#q=payload``, the payload never reaches the
381
+ sink, and a real DOM XSS is reported as an unproven lead. An explicit
382
+ ``location.<member>`` in the same statement therefore outranks the table.
383
+ """
384
+ base = default or SOURCES.get(source, "url")
385
+ if "location" in stmt:
386
+ if re.search(r"location(?:\.|\[['\"])hash", stmt):
387
+ return "hash"
388
+ if re.search(r"location(?:\.|\[['\"])search", stmt):
389
+ return "query"
390
+ return base
391
+
392
+
393
+ def _param_for(body: str, sink_offset: int, stmt: str) -> str:
394
+ for rx in (GET_PARAM_RX, PARAM_RX, QUERY_INDEX_RX, QUERY_PROP_RX):
395
+ m = rx.search(stmt)
396
+ if m:
397
+ return m.group(1)
398
+ # the parameter is often read a few statements earlier
399
+ window_start = max(0, sink_offset - 900)
400
+ for m in GET_PARAM_RX.finditer(body, window_start, sink_offset):
401
+ return m.group(1)
402
+ return "q"
403
+
404
+
405
+ def _hardening_before(body: str, sink_offset: int, source: str) -> str:
406
+ window_start = max(0, sink_offset - 1200)
407
+ window = body[window_start:sink_offset]
408
+ if re.search(r"createPolicy\s*\(", window) or "trustedTypes" in window:
409
+ return "Trusted Types policy"
410
+ if re.search(r"DOMPurify\.sanitize|\.sanitize\s*\(", window):
411
+ return "sanitizer"
412
+ if re.search(r"[.\s]textContent\s*=", window) and "innerHTML" not in window[-200:]:
413
+ return "textContent (safe sink)"
414
+ return ""
415
+
416
+
417
+ def _flow_snippet(body: str, source: str, taint: dict, sink: str) -> str:
418
+ """Show the assignment that introduced the source, for the report."""
419
+ m = SOURCE_RX.search(body)
420
+ if not m:
421
+ return ""
422
+ line = _line_of(body, m.start())
423
+ stmt = _statement_at(body, m.start(), radius=200)
424
+ return f"line {line}: {stmt[:300]}"
425
+
426
+
427
+ def is_hardened(candidate: DomCandidate) -> bool:
428
+ """A flow through an escaping/sanitising API is not automatically exploitable."""
429
+ if not candidate.hardening:
430
+ return False
431
+ if candidate.hardening in ("textContent", "innerText", "createTextNode"):
432
+ return True
433
+ # encodeURIComponent on a URL sink is still exploitable in some cases, so it
434
+ # only hardens when the sink is not markup-based
435
+ return candidate.hardening.lower() in (
436
+ "dompurify", "sanitizer", "trusted types policy", "escapehtml",
437
+ )
438
+
439
+
440
+ # ---------------------------------------------------------------------------
441
+ # Delivery
442
+ # ---------------------------------------------------------------------------
443
+
444
+ def build_test_url(base: str, candidate: DomCandidate, payload: str,
445
+ param: str | None = None) -> str | None:
446
+ """Place the payload where the candidate's source actually reads from."""
447
+ parts = urllib.parse.urlsplit(base)
448
+ encoded = urllib.parse.quote(payload, safe="")
449
+ param = param or candidate.parameter or "q"
450
+ if candidate.delivery in ("query", "url"):
451
+ pairs = urllib.parse.parse_qsl(parts.query, keep_blank_values=True)
452
+ pairs = [(k, v) for k, v in pairs if k != param]
453
+ pairs.append((param, payload))
454
+ query = urllib.parse.urlencode(pairs, quote_via=urllib.parse.quote)
455
+ return urllib.parse.urlunsplit((parts.scheme, parts.netloc, parts.path, query, ""))
456
+ if candidate.delivery == "hash":
457
+ fragment = f"{param}={encoded}"
458
+ return urllib.parse.urlunsplit((parts.scheme, parts.netloc, parts.path, parts.query, fragment))
459
+ if candidate.delivery == "window.name":
460
+ return None # needs a scripted setter; handled by the browser driver
461
+ if candidate.delivery in ("referrer", "cookie", "storage"):
462
+ return None # requires request-level injection, handled elsewhere
463
+ return urllib.parse.urlunsplit((parts.scheme, parts.netloc, parts.path,
464
+ parts.query, f"{param}={encoded}"))
465
+
466
+
467
+ def build_window_name_payload(payload: str) -> str:
468
+ return payload
469
+
470
+
471
+ DOM_JS_TEMPLATE = (
472
+ "document.body.appendChild(document.createElement('b')).id='{}'"
473
+ )
474
+
475
+
476
+ def dom_payloads(marker: str) -> list[tuple[str, str]]:
477
+ """Markup vectors that execute the moment the node is inserted.
478
+
479
+ Ordering is empirical, not cosmetic. Chromium (Edge 13x) does **not** fire
480
+ ``onload`` for an inline ``<svg>`` created through ``innerHTML``, so the
481
+ classic ``<svg/onload=...>`` vector silently produces a dead node: the
482
+ markup is in the DOM but nothing runs. ``<img onerror>`` does fire, and it
483
+ fires even for a one-pixel ``src=x`` request that 404s, which is why it is
484
+ first. The bare (unquoted) variant survives filters that strip quotes, and
485
+ ``<details ontoggle>`` covers pages where images are blocked outright.
486
+ """
487
+ js = dom_js_artifact(marker)
488
+ return [
489
+ ("img-onerror", f'<img src=x onerror="{js}">'),
490
+ ("img-onerror-bare", f"<img src=x onerror={js}>"),
491
+ ("details-ontoggle", f'<details open ontoggle="{js}">'),
492
+ ("svg-onload", f'<svg onload="{js}">'),
493
+ ]
494
+
495
+
496
+ def dom_payload(marker: str) -> str:
497
+ """Primary markup vector (kept for callers that need a single string)."""
498
+ return dom_payloads(marker)[0][1]
499
+
500
+
501
+ def dom_js_artifact(marker: str) -> str:
502
+ """Space-free JS that leaves an element only execution can create."""
503
+ return f"document.body.appendChild(document.createElement('b')).id='{dom_target_id(marker)}'"
504
+
505
+
506
+ def dom_target_id(marker: str) -> str:
507
+ return f"xdm{marker}x"
508
+
509
+
510
+ MARKUP_SINKS = {
511
+ "innerhtml", "outerhtml", "insertadjacenthtml", "document.write",
512
+ "jquery-html", "jquery-append", "srcdoc", "dangerouslysetinnerhtml",
513
+ "v-html", "bypasssecuritytrusthtml", "createcontextualfragment",
514
+ "jquery-parshtml", "jquery-parsehtml",
515
+ }
516
+
517
+ JS_SINKS = {
518
+ "eval", "function", "settimeout-string",
519
+ }
520
+
521
+ URL_SINKS = {
522
+ "location.assign", "location.href=", "window.open",
523
+ }
524
+
525
+ # sinks a markup or javascript: payload cannot exercise (they need a served script)
526
+ UNVERIFIABLE_SINKS = {"script-src"}
527
+
528
+
529
+ def sink_kind(sink: str) -> str:
530
+ s = (sink or "").lower()
531
+ if s in MARKUP_SINKS:
532
+ return "markup"
533
+ if s in JS_SINKS:
534
+ return "js"
535
+ if s in URL_SINKS:
536
+ return "url"
537
+ return "markup"
538
+
539
+
540
+ def payloads_for(kind: str, marker: str) -> list[tuple[str, str]]:
541
+ """Ranked (vector, payload) pairs for one sink class."""
542
+ js = dom_js_artifact(marker)
543
+ if kind == "js":
544
+ return [("js-direct", js), ("js-string-break", f"';{js};//")]
545
+ if kind == "url":
546
+ return [("javascript-url", "javascript:" + js),
547
+ ("javascript-url-mixed", "JaVaScRiPt:" + js)]
548
+ return dom_payloads(marker)
549
+
550
+
551
+ def payload_for(kind: str, marker: str) -> str:
552
+ return payloads_for(kind, marker)[0][1]
553
+
554
+
555
+ # NOTE: keep %s, never str.format -- the IIFE braces would be read as fields
556
+ # and .format() raises ValueError *before* the script is ever evaluated.
557
+ DOM_ARTIFACT_JS = (
558
+ "(function(){var e=document.getElementById(%s);"
559
+ "return e?(e.tagName+':'+e.id):''})()"
560
+ )
561
+
562
+
563
+ # ---------------------------------------------------------------------------
564
+ # Runtime verification
565
+ # ---------------------------------------------------------------------------
566
+
567
+ class DomScanner:
568
+ """Turn static flows into proven findings, or into explicitly-labelled leads."""
569
+
570
+ def __init__(self, browser=None, log=None, max_flows: int = 25,
571
+ screenshot_dir: str | None = None, deadline: float | None = None,
572
+ max_store_flows: int = 12):
573
+ self.browser = browser
574
+ self.log = log
575
+ self.max_flows = max_flows
576
+ self.max_store_flows = max_store_flows
577
+ self.screenshot_dir = screenshot_dir
578
+ # Wall-clock deadline shared with the other phases. The DOM phase drives a
579
+ # real browser per flow, so it is the easiest place to blow a budget.
580
+ self.deadline = deadline
581
+ self.budget_exhausted = False
582
+ self.flows: list[DomCandidate] = []
583
+ self.findings: list = []
584
+ self.leads: list = []
585
+ self.runtime: list[dict] = []
586
+
587
+ def _out_of_budget(self) -> bool:
588
+ if self.deadline is None:
589
+ return False
590
+ if time.time() < self.deadline:
591
+ return False
592
+ if not self.budget_exhausted:
593
+ self.budget_exhausted = True
594
+ self._log("time budget reached during DOM analysis; reporting flows "
595
+ "proven so far")
596
+ return True
597
+
598
+ # -- collection ----------------------------------------------------
599
+ def collect(self, resources) -> list[DomCandidate]:
600
+ """*resources* is a list of (url, body, pages_that_load_it)."""
601
+ seen: set[str] = set()
602
+ out: list[DomCandidate] = []
603
+ hosts: dict[str, str] = {}
604
+ writes: list[domstate.StoreWrite] = []
605
+ reads: list[domstate.StoreRead] = []
606
+ reducers: dict[str, str] = {}
607
+ by_resource_reads: dict[str, list[domstate.StoreRead]] = {}
608
+
609
+ for resource, body, pages in resources:
610
+ if not body:
611
+ continue
612
+ host = ""
613
+ for p in pages or []:
614
+ if p and not p.endswith("#inline") and p != resource:
615
+ host = p
616
+ break
617
+ if not host and "#inline" in resource:
618
+ host = resource.split("#inline", 1)[0]
619
+ hosts[resource] = host
620
+ taint = _build_taint(body)
621
+
622
+ # 1. flows that live inside this resource
623
+ for cand in analyze_js(resource, body, taint=taint):
624
+ if cand.key() in seen:
625
+ continue
626
+ seen.add(cand.key())
627
+ cand.page = host
628
+ out.append(cand)
629
+
630
+ # 2. store traffic: writes and reads are joined across resources
631
+ body_writes, body_reads = domstate.scan_state(resource, body, taint, SINKS)
632
+ writes.extend(body_writes)
633
+ reads.extend(body_reads)
634
+ reducers.update(domstate.reducer_map(body))
635
+ if body_reads:
636
+ by_resource_reads[resource] = body_reads
637
+
638
+ # A dispatch carries an action type; the reducer maps it to a field. Only
639
+ # after every resource has been read can the two halves be joined.
640
+ writes = domstate.expand_dispatch(writes, reducers)
641
+
642
+ # A storage read is only a *lead* today because the value looks like it
643
+ # arrives out of band. When the same key is written from a URL source,
644
+ # the browser can be driven through both steps -- so recover the key and
645
+ # promote the flow to verifiable instead of leaving it unexplained.
646
+ for cand in out:
647
+ if cand.delivery != "storage" or cand.store:
648
+ continue
649
+ for var in cand.taint_chain[1:]:
650
+ read = domstate.read_for_var(reads, var, cand.resource)
651
+ if read is None:
652
+ continue
653
+ write = domstate.write_for(read.kind, read.key, writes)
654
+ if write is None:
655
+ continue
656
+ self._attach_store(cand, write, read, hosts)
657
+ seen.add(cand.key())
658
+ break
659
+
660
+ for flow in domstate.join_state(writes, reads, limit=self.max_store_flows):
661
+ flow_cand = self._store_candidate(flow, hosts)
662
+ if flow_cand is None or flow_cand.key() in seen:
663
+ continue
664
+ seen.add(flow_cand.key())
665
+ out.append(flow_cand)
666
+
667
+ self.flows = out
668
+ return out
669
+
670
+ @staticmethod
671
+ def _same_origin(a: str, b: str) -> bool:
672
+ """Storage is origin-scoped: a cross-origin join can never be exercised."""
673
+ if not a or not b:
674
+ return True
675
+ try:
676
+ return urllib.parse.urlsplit(a).netloc == urllib.parse.urlsplit(b).netloc
677
+ except ValueError:
678
+ return False
679
+
680
+ def _attach_store(self, cand: DomCandidate, write: domstate.StoreWrite,
681
+ read: domstate.StoreRead, hosts: dict[str, str]) -> None:
682
+ cand.store = read.kind
683
+ cand.store_key = read.key
684
+ cand.write_page = hosts.get(write.resource, "") or cand.page
685
+ cand.write_line = write.line
686
+ cand.source = write.source
687
+ cand.delivery = write.delivery
688
+ cand.parameter = read.parameter or write.parameter or cand.parameter
689
+ cand.taint_chain = [write.source, f"{write.kind}.{write.key}"]
690
+ cand.two_step = (write.kind in ("localStorage", "sessionStorage")
691
+ or cand.write_page != cand.page)
692
+ if not self._same_origin(cand.write_page, cand.page):
693
+ cand.store = ""
694
+ cand.two_step = False
695
+
696
+ def _store_candidate(self, flow: domstate.StoreFlow,
697
+ hosts: dict[str, str]) -> DomCandidate | None:
698
+ read, write = flow.read, flow.write
699
+ page = hosts.get(read.resource, "")
700
+ write_page = hosts.get(write.resource, "") or page
701
+ if not write.delivery:
702
+ return None
703
+ cand = DomCandidate(
704
+ resource=read.resource,
705
+ sink=read.sink,
706
+ source=write.source,
707
+ parameter=read.parameter or write.parameter or "",
708
+ delivery=write.delivery,
709
+ taint_chain=[write.source, f"{write.kind}.{write.key}"],
710
+ sink_snippet=read.statement,
711
+ flow_snippet=f"line {write.line}: {write.snippet}",
712
+ line=read.line,
713
+ page=page,
714
+ store=read.kind,
715
+ store_key=read.key,
716
+ write_page=write_page,
717
+ write_line=write.line,
718
+ )
719
+ # A second document is involved whenever the two halves live on different
720
+ # pages, not only for web storage: the replay has to walk both steps.
721
+ cand.two_step = (write.kind in ("localStorage", "sessionStorage")
722
+ or write_page != page)
723
+ if not self._same_origin(write_page, page):
724
+ return None
725
+ return cand
726
+
727
+ # -- verification --------------------------------------------------
728
+ def scan(self, base_url: str, resources) -> dict:
729
+ cands = self.collect(resources)
730
+ if not cands:
731
+ return {"flows": [], "findings": [], "leads": [], "runtime": []}
732
+ self._log(f"DOM analysis: {len(cands)} source-to-sink flow(s) in "
733
+ f"{len(resources)} script resource(s)")
734
+ checkable = [c for c in cands if self._can_verify(c)]
735
+ rest = [c for c in cands if not self._can_verify(c)]
736
+ for cand in rest[: self.max_flows]:
737
+ if cand.store and not cand.two_step:
738
+ reason = (f"{cand.store}.{cand.store_key} is written from another origin, "
739
+ "so the browser cannot be driven through both steps")
740
+ elif cand.store:
741
+ reason = (f"{cand.store}.{cand.store_key} lives in page memory, so a "
742
+ "second navigation cannot carry it; review the write and "
743
+ "the read together")
744
+ elif cand.delivery == "storage":
745
+ reason = ("value is read from storage but no URL-fed write was found, "
746
+ "so the flow cannot be replayed from the request")
747
+ else:
748
+ reason = "requires request-level injection or a served script"
749
+ self.leads.append(self._lead(cand, base_url, reason))
750
+ for cand in checkable[: self.max_flows]:
751
+ if is_hardened(cand):
752
+ self.leads.append(self._lead(cand, base_url,
753
+ f"flow passes through {cand.hardening}"))
754
+ continue
755
+ if self._out_of_budget():
756
+ break
757
+ finding = self._verify(base_url, cand)
758
+ if finding is None:
759
+ continue
760
+ if finding.verified_browser:
761
+ self.findings.append(finding)
762
+ self._log(f"DOM XSS confirmed: {cand.parameter} -> {cand.sink}() on "
763
+ f"{cand.page or base_url}")
764
+ else:
765
+ self.leads.append(finding)
766
+ return {"flows": self.flows, "findings": self.findings,
767
+ "leads": self.leads, "runtime": self.runtime}
768
+
769
+ def _can_verify(self, cand: DomCandidate) -> bool:
770
+ if not self.browser or not getattr(self.browser, "available", False):
771
+ return False
772
+ if cand.sink.lower() in UNVERIFIABLE_SINKS:
773
+ return False
774
+ if cand.two_step:
775
+ # Browser storage survives a second navigation, so a joined write can
776
+ # be replayed even though the value never travels in one request. An
777
+ # in-memory store (setState, reducer, event bus) is reset by the new
778
+ # document, so only a single-page flow can actually be driven.
779
+ if cand.store and cand.store not in ("localStorage", "sessionStorage"):
780
+ return False
781
+ return cand.delivery in ("query", "url", "hash") and bool(cand.write_page)
782
+ return cand.delivery in ("query", "url", "hash", "window.name")
783
+
784
+ def _param_candidates(self, page_url: str, cand: DomCandidate) -> list[str]:
785
+ """Parameters worth trying when the flow does not name one.
786
+
787
+ A hydration blob or a data- attribute is populated by *some* parameter the
788
+ server chose; the page's own query names are the best evidence we have,
789
+ and the list is capped because every guess costs a navigation.
790
+ """
791
+ if cand.parameter:
792
+ return [cand.parameter]
793
+ names: list[str] = []
794
+ try:
795
+ names.extend(k for k, _ in urllib.parse.parse_qsl(
796
+ urllib.parse.urlsplit(page_url).query, keep_blank_values=True) if k)
797
+ except ValueError:
798
+ pass
799
+ for guess in ("q", "search", "query", "id", "page", "s", "term", "name", "state"):
800
+ if guess not in names:
801
+ names.append(guess)
802
+ return names[:3] or ["q"]
803
+
804
+ def _verify(self, base_url: str, cand: DomCandidate):
805
+ marker = uuid.uuid4().hex[:10]
806
+ kind = sink_kind(cand.sink)
807
+ page_url = cand.page or base_url
808
+ target = dom_target_id(marker)
809
+ observation: dict = {"flow": cand.summary(), "resource": cand.resource,
810
+ "page": page_url, "payload": "", "kind": kind,
811
+ "delivery": cand.delivery, "marker": marker,
812
+ "attempts": []}
813
+
814
+ confirmed = False
815
+ detail: dict = {"loaded": False}
816
+ params = self._param_candidates(page_url, cand)
817
+ vectors = payloads_for(kind, marker)
818
+ if len(params) > 1:
819
+ # the parameter has to be guessed, and every guess costs a navigation:
820
+ # spend them on names rather than on extra vectors
821
+ vectors = vectors[:1]
822
+ for label, payload in vectors:
823
+ for param in params:
824
+ if self._out_of_budget():
825
+ break
826
+ if cand.delivery == "window.name":
827
+ ok, detail = self._drive_window_name(page_url, payload, target)
828
+ elif cand.delivery == "hash":
829
+ ok, detail = self._drive_hash(page_url, cand, payload, target, param=param)
830
+ elif cand.two_step:
831
+ ok, detail = self._drive_store(cand, payload, param, target)
832
+ else:
833
+ url = build_test_url(page_url, cand, payload, param=param) or page_url
834
+ ok, detail = self._drive_url(url, target)
835
+ observation.setdefault("url", url)
836
+ observation["attempts"].append({"vector": label, "parameter": param,
837
+ "confirmed": ok,
838
+ "artifact": detail.get("artifact", "")})
839
+ if not detail.get("loaded"):
840
+ return None # the page never loaded; nothing to say about this flow
841
+ if ok:
842
+ confirmed = True
843
+ observation["vector"] = label
844
+ observation["parameter"] = param
845
+ observation["payload"] = payload
846
+ observation["url"] = (detail.get("url") or observation.get("url")
847
+ or page_url)
848
+ break
849
+ if confirmed:
850
+ break
851
+ if not observation["payload"]:
852
+ observation["payload"] = payloads_for(kind, marker)[0][1]
853
+ payload = observation["payload"]
854
+
855
+ observation.update(detail)
856
+ if confirmed and self.screenshot_dir:
857
+ shot = os.path.join(self.screenshot_dir, f"dom-xss-{marker}.png")
858
+ try:
859
+ if self.browser.screenshot(shot):
860
+ observation["screenshot"] = shot
861
+ except Exception:
862
+ pass
863
+ self.runtime.append(observation)
864
+ if not detail.get("loaded"):
865
+ return None
866
+
867
+ evidence = self._evidence(cand, observation)
868
+ notes = [f"DOM flow: {cand.summary()}",
869
+ "static taint flow is inferred; runtime check is the proof"]
870
+ if confirmed:
871
+ notes.append("injected node observed in the live DOM after execution")
872
+ elif detail.get("marker_in_dom"):
873
+ notes.append("payload reached the DOM but its handler did not run "
874
+ "(Content-Security-Policy or a sanitizer)")
875
+ else:
876
+ notes.append("payload did not reach the DOM through the analysed flow")
877
+
878
+ from .scanner import Finding
879
+ return Finding(
880
+ url=observation.get("url") or page_url,
881
+ method="GET", param=observation.get("parameter") or cand.parameter or "q",
882
+ location="DOM", payload=payload, context="dom_xss", status=0,
883
+ confidence="high" if confirmed else "low",
884
+ verified_browser=confirmed, browser_checked=True,
885
+ verify_state="confirmed" if confirmed else "not_observed",
886
+ verify_reason=("injected node observed in the live DOM after execution" if confirmed
887
+ else ("payload reached the DOM but the handler did not run"
888
+ if detail.get("marker_in_dom")
889
+ else "the analysed flow did not place the payload in the DOM")),
890
+ evidence=evidence, notes=notes, title="DOM-based XSS",
891
+ )
892
+
893
+ def _drive_url(self, url: str, target: str) -> tuple[bool, dict]:
894
+ info = self.browser.navigate(url)
895
+ detail = {"loaded": bool(info.get("loaded")), "error": info.get("error", ""),
896
+ "url": info.get("url") or url}
897
+ if not detail["loaded"]:
898
+ return False, detail
899
+ self._settle()
900
+ artifact = self._artifact(target)
901
+ detail["artifact"] = artifact
902
+ detail["marker_in_dom"] = self._marker_seen(target)
903
+ return bool(artifact), detail
904
+
905
+ def _drive_hash(self, page_url: str, cand: DomCandidate,
906
+ payload: str, target: str,
907
+ param: str | None = None) -> tuple[bool, dict]:
908
+ """Set the fragment from script so no character is re-encoded, then reload.
909
+
910
+ Both ``#param=payload`` and ``#payload`` are attempted because the two
911
+ common readers (URLSearchParams vs. slice(1)) expect different shapes.
912
+ """
913
+ param = param or cand.parameter or "q"
914
+ # ``#q=payload`` first: modern routers read the fragment with
915
+ # URLSearchParams. The bare shape covers slice(1)-style routers.
916
+ variants = [f"{param}={payload}", payload]
917
+ detail: dict = {"loaded": False}
918
+ for fragment in variants:
919
+ info = self.browser.navigate(page_url)
920
+ if not info.get("loaded"):
921
+ return False, {"loaded": False, "error": info.get("error", "")}
922
+ try:
923
+ token = self.browser.evaluate("String(performance.timeOrigin)")
924
+ self.browser.evaluate("location.hash = " + json.dumps("#" + fragment))
925
+ self.browser.evaluate("location.reload()")
926
+ self._wait_new_document(token)
927
+ except Exception as exc: # browser went away mid-flow
928
+ return False, {"loaded": True, "error": str(exc)[:160]}
929
+ self._settle()
930
+ artifact = self._artifact(target)
931
+ if artifact:
932
+ return True, {"loaded": True, "url": page_url, "artifact": artifact,
933
+ "marker_in_dom": True, "fragment_shape": fragment[:40]}
934
+ detail = {"loaded": True, "url": page_url,
935
+ "artifact": "", "marker_in_dom": self._marker_seen(target),
936
+ "fragment_shape": fragment[:40]}
937
+ return False, detail
938
+
939
+ def _drive_store(self, cand: DomCandidate, payload: str, param: str,
940
+ target: str) -> tuple[bool, dict]:
941
+ """Walk the flow the way the application does: write the value, then read it.
942
+
943
+ A store flow has two steps on purpose -- the page that *stores* the request
944
+ data and the page that *renders* it can be different documents. The write
945
+ step is verified before the read step so a payload that was never stored
946
+ is reported as "not exercised" rather than as "not vulnerable".
947
+ """
948
+ write_page = cand.write_page or cand.page
949
+ read_page = cand.page or write_page
950
+ if not write_page or not read_page:
951
+ return False, {"loaded": False, "error": "store flow without page URLs"}
952
+ url = build_test_url(write_page, cand, payload, param=param) or write_page
953
+ info = self.browser.navigate(url)
954
+ if not info.get("loaded"):
955
+ return False, {"loaded": False, "error": info.get("error", ""), "url": url}
956
+ self._settle()
957
+ stored = self._store_value(cand.store, cand.store_key, target)
958
+ if read_page.rstrip("/") != write_page.rstrip("/"):
959
+ info = self.browser.navigate(read_page)
960
+ if not info.get("loaded"):
961
+ return False, {"loaded": False, "error": info.get("error", ""),
962
+ "url": read_page, "store_value_seen": stored}
963
+ self._settle()
964
+ artifact = self._artifact(target)
965
+ return bool(artifact), {"loaded": True, "url": read_page, "artifact": artifact,
966
+ "marker_in_dom": self._marker_seen(target),
967
+ "write_url": url, "store_value_seen": stored}
968
+
969
+ def _store_value(self, store: str, key: str, target: str) -> bool | None:
970
+ """Did the write step actually park the payload? ``None`` = cannot tell.
971
+
972
+ Web storage is readable from the driver, so a false here means the flow was
973
+ never exercised and the runtime result must not be read as a negative.
974
+ A framework store (``state``/``dispatch``) is in-memory and opaque: there
975
+ is no honest way to inspect it from outside, so it reports ``None``.
976
+ """
977
+ if store not in ("localStorage", "sessionStorage"):
978
+ return None
979
+ script = (
980
+ f"(function(){{try{{var v=window[{json.dumps(store)}].getItem("
981
+ f"{json.dumps(key)});return v?v.indexOf({json.dumps(target)})>=0:false}}"
982
+ f"catch(e){{return false}}}})()"
983
+ )
984
+ try:
985
+ value = self.browser.evaluate(script)
986
+ except Exception:
987
+ return None
988
+ return bool(value) if isinstance(value, bool) else None
989
+
990
+ def _drive_window_name(self, page_url: str, payload: str,
991
+ target: str) -> tuple[bool, dict]:
992
+ info = self.browser.navigate("about:blank")
993
+ if not info.get("loaded"):
994
+ return False, {"loaded": False, "error": "could not open about:blank"}
995
+ self.browser.evaluate("window.name = " + json.dumps(payload))
996
+ info = self.browser.navigate(page_url)
997
+ if not info.get("loaded"):
998
+ return False, {"loaded": False, "error": info.get("error", "")}
999
+ self._settle()
1000
+ artifact = self._artifact(target)
1001
+ return bool(artifact), {"loaded": True, "url": page_url, "artifact": artifact,
1002
+ "marker_in_dom": self._marker_seen(target)}
1003
+
1004
+ def _wait_new_document(self, old_token: str, timeout: float = 6.0) -> None:
1005
+ """Block until a *new* document exists (timeOrigin changes on reload)."""
1006
+ deadline = time.time() + timeout
1007
+ while time.time() < deadline:
1008
+ try:
1009
+ token = self.browser.evaluate("String(performance.timeOrigin)")
1010
+ ready = self.browser.evaluate("document.readyState")
1011
+ except Exception:
1012
+ return
1013
+ if token and token != old_token and ready in ("interactive", "complete"):
1014
+ return
1015
+ time.sleep(0.1)
1016
+
1017
+ def _settle(self, timeout: float = 3.0) -> None:
1018
+ deadline = time.time() + timeout
1019
+ while time.time() < deadline:
1020
+ try:
1021
+ if self.browser.evaluate("document.readyState") in ("interactive", "complete"):
1022
+ return
1023
+ except Exception:
1024
+ return
1025
+ time.sleep(0.1)
1026
+
1027
+ def _artifact(self, target: str, timeout: float = 2.5) -> str:
1028
+ """Poll briefly: error/load handlers run after the insertion returns."""
1029
+ deadline = time.time() + timeout
1030
+ while True:
1031
+ try:
1032
+ found = self.browser.evaluate(DOM_ARTIFACT_JS % json.dumps(target)) or ""
1033
+ except Exception:
1034
+ return ""
1035
+ if found or time.time() >= deadline:
1036
+ return found
1037
+ time.sleep(0.1)
1038
+
1039
+ def _marker_seen(self, target: str) -> bool:
1040
+ try:
1041
+ value = self.browser.evaluate(
1042
+ "document.documentElement.outerHTML.indexOf(" + json.dumps(target) + ")>=0")
1043
+ if isinstance(value, bool):
1044
+ return value
1045
+ return str(value).strip().lower() in ("true", "1")
1046
+ except Exception:
1047
+ return False
1048
+
1049
+ # -- reporting -----------------------------------------------------
1050
+ def _evidence(self, cand: DomCandidate, obs: dict) -> str:
1051
+ lines = [
1052
+ f"DOM flow (static, inferred): {cand.summary()}",
1053
+ f" script: {cand.resource}",
1054
+ f" source line {cand.line}: {cand.sink_snippet}",
1055
+ f" delivery: {cand.delivery}, parameter: "
1056
+ f"{obs.get('parameter') or cand.parameter or 'guessed at verification'}",
1057
+ ]
1058
+ if cand.store:
1059
+ lines.append(f" store: {cand.store}.{cand.store_key} written at "
1060
+ f"{cand.write_page or 'the same page'} line {cand.write_line}")
1061
+ if cand.flow_snippet:
1062
+ lines.append(f" origin: {cand.flow_snippet}")
1063
+ if obs.get("artifact"):
1064
+ steps = (f"wrote the payload at {obs.get('write_url')} then loaded "
1065
+ if obs.get("write_url") else "navigated to ")
1066
+ lines.append(f"Runtime proof: {steps}{obs.get('url')} and observed "
1067
+ f"the injected node <{obs['artifact']}> in the live DOM")
1068
+ if obs.get("screenshot"):
1069
+ lines.append(f" screenshot: {obs['screenshot']}")
1070
+ elif obs.get("marker_in_dom"):
1071
+ lines.append(f"Runtime check: payload reached the DOM at {obs.get('url')} "
1072
+ "but no injected node appeared (blocked)")
1073
+ elif obs.get("store_value_seen") is False:
1074
+ lines.append(f"Runtime check: the write step at {obs.get('write_url')} did not "
1075
+ "store the payload, so the read step was never exercised")
1076
+ else:
1077
+ lines.append(f"Runtime check: the analysed flow did not place the payload "
1078
+ f"in the DOM at {obs.get('url')}")
1079
+ return "\n".join(lines)
1080
+
1081
+ def _lead(self, cand: DomCandidate, base_url: str, reason: str):
1082
+ from .scanner import Finding
1083
+ return Finding(
1084
+ url=cand.page or base_url, method="GET", param=cand.parameter or "q",
1085
+ location="DOM", payload="", context="dom_xss", status=0,
1086
+ confidence="low", verified_browser=False, browser_checked=False,
1087
+ verify_state="not_tested", verify_reason=reason,
1088
+ evidence=self._evidence(cand, {}),
1089
+ notes=[f"DOM flow: {cand.summary()}", f"not verified: {reason}"],
1090
+ title="DOM-based XSS (candidate)",
1091
+ )
1092
+
1093
+ def _log(self, message: str) -> None:
1094
+ if self.log is not None:
1095
+ try:
1096
+ self.log.info(message)
1097
+ except Exception:
1098
+ pass