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/csp.py ADDED
@@ -0,0 +1,674 @@
1
+ """Content-Security-Policy: read the policy the way a browser reads it.
2
+
3
+ Substring matching ("the response mentions Content-Security-Policy") cannot
4
+ answer the only question a scanner has: *would this payload have run if the
5
+ application had not filtered it?* The answer lives in the policy's directives,
6
+ their fallback chains, and the keywords that silently disable other keywords --
7
+ ``'unsafe-inline'`` is ignored as soon as a nonce or hash appears,
8
+ ``'strict-dynamic'`` discards host allowlists and ``'self'``, and ``'none'`` is
9
+ only meaningful on its own.
10
+
11
+ This module parses the header into directives and answers three questions:
12
+
13
+ * is inline script / an event handler / a ``javascript:`` URL permitted?
14
+ * would a ``<script src=...>`` on this URL be permitted?
15
+ * what does the policy leave open even if it does block the payload
16
+ (missing ``base-uri``/``object-src``, wildcard or ``http:`` allowlists,
17
+ report-only delivery)?
18
+
19
+ The answers are *static*: they describe what the policy declares, not what the
20
+ engine did. The browser remains the only source of an execution verdict; a
21
+ policy that forbids a technique explains a negative result, it never creates a
22
+ positive one.
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import re
27
+ import urllib.parse
28
+ from dataclasses import dataclass, field
29
+
30
+ # Fetch directives fall back to default-src; these do not (or fall back to a
31
+ # different chain first). Getting this wrong turns "not assessed" into a false
32
+ # claim, so the chains are explicit.
33
+ _FALLBACKS: dict[str, tuple[str, ...]] = {
34
+ "script-src-elem": ("script-src", "default-src"),
35
+ "script-src-attr": ("script-src", "default-src"),
36
+ "style-src-elem": ("style-src", "default-src"),
37
+ "style-src-attr": ("style-src", "default-src"),
38
+ "worker-src": ("child-src", "script-src", "default-src"),
39
+ "frame-src": ("child-src", "default-src"),
40
+ "connect-src": ("default-src",),
41
+ "img-src": ("default-src",),
42
+ "font-src": ("default-src",),
43
+ "media-src": ("default-src",),
44
+ "object-src": ("default-src",),
45
+ "manifest-src": ("default-src",),
46
+ "prefetch-src": ("default-src",),
47
+ "base-uri": (),
48
+ "form-action": (),
49
+ "frame-ancestors": (),
50
+ "sandbox": (),
51
+ "report-uri": (),
52
+ "report-to": (),
53
+ }
54
+
55
+ _NAME_RE = re.compile(r"^[a-z][a-z0-9-]*\Z")
56
+ _SCHEME_SRC_RE = re.compile(r"^([a-z][a-z0-9+.-]*):\Z", re.I)
57
+ _HOST_SRC_RE = re.compile(
58
+ r"^(?:([a-z][a-z0-9+.-]*)://)?(\*|\*\.[^/:]+|\[[^\]]+\]|[^/:]+)(?::(\d+|\*))?(/.*)?\Z",
59
+ re.I,
60
+ )
61
+ _POLICY_SPLIT_RE = re.compile(r",(?=\s*[a-z][a-z0-9-]*\s)", re.I)
62
+
63
+ _DEFAULT_PORTS = {"http": 80, "https": 443, "ws": 80, "wss": 443}
64
+
65
+ # Payload techniques, most specific first. The order matters: `<script src=...>`
66
+ # also contains `<script`, and an event handler may sit inside a `<script>` body.
67
+ _TECHNIQUE_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (
68
+ ("external_script", re.compile(r"<script\b[^>]*\bsrc\s*=", re.I)),
69
+ ("srcdoc", re.compile(r"\bsrcdoc\b", re.I)),
70
+ ("inline_script", re.compile(r"<script\b", re.I)),
71
+ ("javascript_url", re.compile(r"javascript\s*:", re.I)),
72
+ ("inline_event_handler", re.compile(r"<[a-z][^>]*?\son[a-z]+\s*=", re.I | re.S)),
73
+ )
74
+
75
+ TECHNIQUE_LABELS = {
76
+ "external_script": "an external script element",
77
+ "inline_script": "an inline script element",
78
+ "inline_event_handler": "an inline event handler",
79
+ "javascript_url": "a javascript: URL",
80
+ "srcdoc": "an iframe srcdoc document",
81
+ "markup": "markup only (no script technique)",
82
+ }
83
+
84
+
85
+ def technique_of(markup: str) -> str:
86
+ """Classify what a payload needs the policy to permit."""
87
+ text = markup or ""
88
+ for name, pattern in _TECHNIQUE_PATTERNS:
89
+ if pattern.search(text):
90
+ return name
91
+ return "markup"
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class Feasibility:
96
+ """Static answer to "would the policy let this technique run?"."""
97
+
98
+ technique: str
99
+ allowed: bool | None # None = the policy says nothing about it
100
+ reason: str
101
+
102
+ def line(self) -> str:
103
+ label = TECHNIQUE_LABELS.get(self.technique, self.technique)
104
+ if self.allowed is None:
105
+ return f"{label}: not forbidden by the policy ({self.reason})"
106
+ verdict = "would be permitted" if self.allowed else "would be blocked"
107
+ return f"{label} {verdict}: {self.reason}"
108
+
109
+
110
+ @dataclass(frozen=True)
111
+ class Policy:
112
+ raw: str
113
+ directives: dict[str, tuple[str, ...]] = field(default_factory=dict)
114
+ report_only: bool = False
115
+
116
+ # -- construction ----------------------------------------------------
117
+ @classmethod
118
+ def parse(cls, raw: str, report_only: bool = False) -> Policy:
119
+ directives: dict[str, tuple[str, ...]] = {}
120
+ for part in (raw or "").split(";"):
121
+ tokens = part.split()
122
+ if not tokens:
123
+ continue
124
+ name = tokens[0].lower()
125
+ # Browsers ignore a directive whose name is not a valid token.
126
+ if not _NAME_RE.match(name):
127
+ continue
128
+ # A repeated directive is ignored: the first instance wins.
129
+ if name in directives:
130
+ continue
131
+ values: list[str] = []
132
+ for token in tokens[1:]:
133
+ if token not in values:
134
+ values.append(token)
135
+ directives[name] = tuple(values)
136
+ return cls(raw=(raw or "").strip(), directives=directives,
137
+ report_only=report_only)
138
+
139
+ # -- directive resolution -------------------------------------------
140
+ def effective(self, name: str) -> tuple[str, tuple[str, ...]] | None:
141
+ """Resolve *name* through its fallback chain.
142
+
143
+ Returns ``(directive_name, sources)`` for the directive a browser would
144
+ actually use, or ``None`` when no policy covers it. ``'none'`` on its
145
+ own means the empty set; combined with other sources it is ignored.
146
+ """
147
+ chain = (name,) + _FALLBACKS.get(name, ("default-src",))
148
+ for candidate in chain:
149
+ if candidate not in self.directives:
150
+ continue
151
+ sources = tuple(s for s in self.directives[candidate]
152
+ if s.lower() != "'none'")
153
+ return candidate, sources
154
+ return None
155
+
156
+ def present(self) -> bool:
157
+ return bool(self.directives)
158
+
159
+ def policy_for_scripts(self, kind: str = "elem") -> tuple[str, tuple[str, ...]] | None:
160
+ name = "script-src-attr" if kind == "attr" else "script-src-elem"
161
+ return self.effective(name)
162
+
163
+ # -- keyword analysis ------------------------------------------------
164
+ @staticmethod
165
+ def _keywords(sources: tuple[str, ...]) -> dict[str, bool]:
166
+ low = [s.lower() for s in sources]
167
+ return {
168
+ "unsafe_inline": "'unsafe-inline'" in low,
169
+ "unsafe_eval": "'unsafe-eval'" in low or "'wasm-unsafe-eval'" in low,
170
+ "strict_dynamic": "'strict-dynamic'" in low,
171
+ "nonce": any(s.startswith("'nonce-") for s in low),
172
+ "hash": any(s.startswith(("'sha256-", "'sha384-", "'sha512-")) for s in low),
173
+ "self": "'self'" in low,
174
+ "wildcard": "*" in low,
175
+ }
176
+
177
+ def inline_allowed(self, kind: str = "elem") -> Feasibility:
178
+ """May inline script (``elem``) or an event handler (``attr``) run?"""
179
+ technique = "inline_event_handler" if kind == "attr" else "inline_script"
180
+ resolved = self.policy_for_scripts(kind)
181
+ if resolved is None:
182
+ return Feasibility(technique, None,
183
+ "no script-src/script-src-elem/default-src directive applies")
184
+ name, sources = resolved
185
+ kw = self._keywords(sources)
186
+ disablers = []
187
+ if kw["nonce"]:
188
+ disablers.append("a nonce-source")
189
+ if kw["hash"]:
190
+ disablers.append("a hash-source")
191
+ if kw["strict_dynamic"]:
192
+ disablers.append("'strict-dynamic'")
193
+ if kw["unsafe_inline"] and not disablers:
194
+ return Feasibility(technique, True, f"{name} lists 'unsafe-inline'")
195
+ if kw["unsafe_inline"]:
196
+ return Feasibility(
197
+ technique, False,
198
+ f"{name} lists 'unsafe-inline' but the browser ignores it when the "
199
+ f"policy also contains {', '.join(disablers)}")
200
+ listed = " ".join(sources) or "(empty)"
201
+ return Feasibility(technique, False,
202
+ f"{name} is {listed} and does not include 'unsafe-inline'")
203
+
204
+ def allows_eval(self) -> bool | None:
205
+ resolved = self.policy_for_scripts("elem")
206
+ if resolved is None:
207
+ return None
208
+ return self._keywords(resolved[1])["unsafe_eval"]
209
+
210
+ def strict_dynamic(self) -> bool:
211
+ """Does this policy trust a script tree instead of a script allowlist?"""
212
+ resolved = self.policy_for_scripts("elem")
213
+ if resolved is None:
214
+ return False
215
+ return self._keywords(resolved[1])["strict_dynamic"]
216
+
217
+ # -- URL matching ----------------------------------------------------
218
+ def allows_url(self, url: str, kind: str = "elem",
219
+ self_origin: str = "") -> Feasibility:
220
+ """Would a script loaded from *url* be permitted?"""
221
+ technique = "external_script"
222
+ resolved = self.policy_for_scripts(kind)
223
+ if resolved is None:
224
+ return Feasibility(technique, None,
225
+ "no script-src/script-src-elem/default-src directive applies")
226
+ name, sources = resolved
227
+ kw = self._keywords(sources)
228
+ if kw["strict_dynamic"] and not kw["nonce"] and not kw["hash"]:
229
+ # Without a nonce/hash in the document, strict-dynamic permits only
230
+ # scripts created by already-trusted script: a markup injection
231
+ # cannot bootstrap itself.
232
+ return Feasibility(
233
+ technique, False,
234
+ f"{name} uses 'strict-dynamic' without a nonce or hash, so a "
235
+ f"markup-injected external script cannot load")
236
+ target = _absolute(url, self_origin)
237
+ if not target:
238
+ return Feasibility(technique, None, "payload has no resolvable script URL")
239
+ for source in sources:
240
+ if source_matches(source, target, self_origin):
241
+ return Feasibility(technique, True,
242
+ f"{name} allows {source} for {_host_of(target)}")
243
+ listed = " ".join(sources) or "(empty)"
244
+ return Feasibility(technique, False,
245
+ f"{name} is {listed} and none matches {_host_of(target)}")
246
+
247
+ # -- assessment ------------------------------------------------------
248
+ def feasibility(self, markup: str, page_url: str = "") -> Feasibility:
249
+ """Static feasibility of *markup* under this policy."""
250
+ technique = technique_of(markup)
251
+ if technique == "inline_event_handler":
252
+ return self.inline_allowed("attr")
253
+ if technique == "inline_script":
254
+ return self.inline_allowed("elem")
255
+ if technique == "javascript_url":
256
+ inline = self.inline_allowed("elem")
257
+ if inline.allowed is None:
258
+ return Feasibility("javascript_url", None, inline.reason)
259
+ return Feasibility(
260
+ "javascript_url", inline.allowed,
261
+ ("'unsafe-inline' is required for javascript: URLs; " + inline.reason))
262
+ if technique == "external_script":
263
+ match = re.search(r"<script\b[^>]*\bsrc\s*=\s*(['\"]?)([^'\"\s>]+)", markup, re.I)
264
+ if not match:
265
+ return Feasibility(technique, None, "could not parse the script src")
266
+ return self.allows_url(match.group(2), "elem", page_url)
267
+ if technique == "srcdoc":
268
+ # A srcdoc document inherits the embedding page's policy, so script
269
+ # inside it is judged by the same script-src.
270
+ inner = self.inline_allowed("elem")
271
+ return Feasibility(
272
+ "srcdoc", inner.allowed,
273
+ "a srcdoc frame inherits this policy; " + inner.reason)
274
+ return Feasibility("markup", None, "no script technique in the payload")
275
+
276
+ def deficiencies(self) -> list[str]:
277
+ """What the policy leaves open, independent of any payload."""
278
+ out: list[str] = []
279
+ script = self.policy_for_scripts("elem")
280
+ if script is None:
281
+ out.append("no script-src or default-src directive: script is unrestricted")
282
+ else:
283
+ name, sources = script
284
+ kw = self._keywords(sources)
285
+ if kw["unsafe_inline"] and not (kw["nonce"] or kw["hash"] or kw["strict_dynamic"]):
286
+ out.append(f"{name} allows 'unsafe-inline': the policy does not "
287
+ f"mitigate reflected XSS")
288
+ if kw["unsafe_eval"]:
289
+ out.append(f"{name} allows 'unsafe-eval'")
290
+ if kw["wildcard"]:
291
+ out.append(f"{name} allows '*' (any host)")
292
+ if self._keywords(sources)["hash"] and kw["unsafe_inline"]:
293
+ out.append(f"{name} mixes hashes with 'unsafe-inline'; only the hashes apply")
294
+ lowered = [s.lower() for s in sources]
295
+ if any(s == "http:" or s.startswith("http://") for s in lowered):
296
+ out.append(f"{name} allows plaintext http: sources")
297
+ if "data:" in lowered:
298
+ out.append(f"{name} allows data: URLs")
299
+ if kw["strict_dynamic"] and not (kw["nonce"] or kw["hash"]):
300
+ out.append(f"{name} uses 'strict-dynamic' without a nonce or hash; "
301
+ f"browsers that support it ignore the host allowlist")
302
+ hosts = [s for s in sources
303
+ if s and not s.startswith("'") and s not in ("*",)]
304
+ hosts = [s for s in hosts if not _SCHEME_SRC_RE.match(s)]
305
+ if hosts and not kw["strict_dynamic"]:
306
+ listed = ", ".join(hosts[:4]) + (" ..." if len(hosts) > 4 else "")
307
+ out.append(f"{name} trusts {listed}: a host that serves JSONP or a "
308
+ f"script gadget can be used to bypass the policy")
309
+ if "base-uri" not in self.directives:
310
+ out.append("no base-uri directive: an injected <base href> can retarget "
311
+ "relative script URLs")
312
+ if "object-src" not in self.directives and "default-src" not in self.directives:
313
+ out.append("no object-src or default-src: plugin content is unrestricted")
314
+ if "form-action" not in self.directives:
315
+ out.append("no form-action directive: injected forms can post off-origin")
316
+ if self.report_only:
317
+ out.append("delivered as Content-Security-Policy-Report-Only: it reports "
318
+ "violations but blocks nothing")
319
+ return out
320
+
321
+ def summary(self) -> str:
322
+ parts = []
323
+ for name in ("default-src", "script-src", "script-src-elem", "script-src-attr",
324
+ "object-src", "base-uri"):
325
+ if name in self.directives:
326
+ values = " ".join(self.directives[name]) or "(empty)"
327
+ parts.append(f"{name} {values}")
328
+ if not parts:
329
+ return "empty policy"
330
+ prefix = "report-only" if self.report_only else "enforced"
331
+ return f"{prefix}: " + "; ".join(parts)
332
+
333
+
334
+ # ---------------------------------------------------------------------------
335
+ # Header collection
336
+ # ---------------------------------------------------------------------------
337
+
338
+ @dataclass
339
+ class Assessment:
340
+ """Every policy a response declares, split by enforcement mode."""
341
+
342
+ enforced: list[Policy] = field(default_factory=list)
343
+ report_only: list[Policy] = field(default_factory=list)
344
+
345
+ @classmethod
346
+ def from_headers(cls, headers: list[tuple[str, str]] | None) -> Assessment:
347
+ assessment = cls()
348
+ for name, value in headers or []:
349
+ lowered = name.lower().strip()
350
+ if lowered not in ("content-security-policy",
351
+ "content-security-policy-report-only"):
352
+ continue
353
+ report_only = lowered.endswith("report-only")
354
+ for chunk in _split_policies(value):
355
+ policy = Policy.parse(chunk, report_only=report_only)
356
+ if not policy.present():
357
+ continue
358
+ (assessment.report_only if report_only
359
+ else assessment.enforced).append(policy)
360
+ return assessment
361
+
362
+ @property
363
+ def present(self) -> bool:
364
+ return bool(self.enforced or self.report_only)
365
+
366
+ def feasibility(self, markup: str, page_url: str = "") -> Feasibility:
367
+ """Combine every enforced policy: all of them must permit the technique."""
368
+ technique = technique_of(markup)
369
+ if not self.enforced:
370
+ return Feasibility(technique, None,
371
+ "report-only headers do not block; no enforced policy")
372
+ allowed = True
373
+ reasons: list[str] = []
374
+ assessed = False
375
+ for policy in self.enforced:
376
+ verdict = policy.feasibility(markup, page_url)
377
+ if verdict.allowed is None:
378
+ reasons.append(verdict.reason)
379
+ continue
380
+ assessed = True
381
+ if not verdict.allowed:
382
+ return Feasibility(technique, False, verdict.reason)
383
+ reasons.append(verdict.reason)
384
+ if not assessed:
385
+ return Feasibility(technique, None, "; ".join(reasons) or "not restricted")
386
+ return Feasibility(technique, allowed, "; ".join(reasons))
387
+
388
+ def deficiencies(self) -> list[str]:
389
+ out: list[str] = []
390
+ for policy in self.enforced:
391
+ out.extend(policy.deficiencies())
392
+ for _ in self.report_only:
393
+ out.append("a report-only policy has no effect on execution")
394
+ seen: set[str] = set()
395
+ unique = []
396
+ for item in out:
397
+ if item not in seen:
398
+ seen.add(item)
399
+ unique.append(item)
400
+ return unique
401
+
402
+ def summary(self) -> str:
403
+ if not self.present:
404
+ return "no Content-Security-Policy header"
405
+ parts = [p.summary() for p in self.enforced]
406
+ parts += [p.summary() for p in self.report_only]
407
+ return " | ".join(parts)
408
+
409
+ def describe(self, markup: str, page_url: str = "", limit: int = 3) -> str:
410
+ """Compact multi-line description for a finding's notes."""
411
+ if not self.present:
412
+ return ""
413
+ lines = [self.summary(), self.feasibility(markup, page_url).line()]
414
+ for item in self.deficiencies()[:limit]:
415
+ lines.append(f"policy gap: {item}")
416
+ return "\n".join(lines)
417
+
418
+ def strict_dynamic(self) -> bool:
419
+ """True when an enforced policy switches the host allowlist off.
420
+
421
+ Any policy that carries 'strict-dynamic' blocks a markup-inserted
422
+ script, so one is enough to make the gadget question relevant.
423
+ """
424
+ return any(p.strict_dynamic() for p in self.enforced)
425
+
426
+
427
+ def describe_with_gadgets(assessment: Assessment, markup: str, page_url: str = "",
428
+ page_html: str = "", limit: int = 3) -> str:
429
+ """``describe()`` plus what ``'strict-dynamic'`` leaves open on this page.
430
+
431
+ ``'strict-dynamic'`` is not a blanket XSS fix: it trusts any script created
432
+ by script that is already trusted. A page that ships a gadget consuming
433
+ attacker-controlled data into ``createElement('script')``/``innerHTML``
434
+ therefore still executes, and no header can tell us whether such a gadget
435
+ exists. The note states what was found and leaves the verdict to a human.
436
+ """
437
+ text = assessment.describe(markup, page_url, limit=limit)
438
+ if not assessment.strict_dynamic():
439
+ return text
440
+ gadgets = strict_dynamic_gadgets(page_html)
441
+ lines = [text] if text else []
442
+ if gadgets:
443
+ found = ", ".join(f"{label} x{count}" for label, count, _ in gadgets)
444
+ lines.append(
445
+ f"strict-dynamic: HTML injection alone cannot load a script, but this "
446
+ f"page's own code contains {len(gadgets)} script-creating gadget(s) "
447
+ f"({found}); if one consumes attacker-controlled data the policy does "
448
+ f"not stop the resulting execution - needs a manual gadget check")
449
+ first = gadgets[0][2]
450
+ if first:
451
+ lines.append(f"strict-dynamic gadget excerpt: {first}")
452
+ else:
453
+ lines.append(
454
+ "strict-dynamic: only nonce/hash scripts can run and no script-creating "
455
+ "gadget was found in this page's code, so a DOM-only execution path "
456
+ "is not established by this page alone")
457
+ jsonp = allowlisted_jsonp(assessment, page_html, page_url)
458
+ if jsonp:
459
+ lines.append("allowlisted JSONP endpoint(s) - the callback must be checked by "
460
+ "hand, an unescaped one executes from an allowed origin: "
461
+ + ", ".join(jsonp[:5]))
462
+ return "\n".join(lines)
463
+
464
+
465
+ # Script-creating patterns that turn data into code *inside* an already trusted
466
+ # script. Ordered by how often they appear in real bypasses.
467
+ _GADGET_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (
468
+ ("createElement('script')", re.compile(r"createElement\s*\(\s*['\"]script['\"]", re.I)),
469
+ ("innerHTML with <script>", re.compile(r"innerHTML\s*=\s*[^;\n]{0,200}?<script", re.I)),
470
+ ("jQuery/HTML sink with <script>", re.compile(r"\$\(\s*[^)\n]{0,160}?<script", re.I)),
471
+ ("document.write with <script>", re.compile(r"document\.write(?:ln)?\s*\(\s*[^)\n]{0,200}?<script", re.I)),
472
+ ("insertAdjacentHTML with <script>",
473
+ re.compile(r"insertAdjacentHTML\s*\([^)\n]{0,200}?<script", re.I)),
474
+ )
475
+
476
+ _SCRIPT_BLOCK_RE = re.compile(r"<script\b([^>]*)>(.*?)</script\s*>", re.I | re.S)
477
+ _CALLBACK_PARAM_RE = re.compile(
478
+ r"[?&](?:callback|cb|jsonp|jsonpCallback|json_callback|_callback)=([^&#\s'\"<>]+)", re.I)
479
+
480
+ # Bounds: a hostile or enormous page must not turn a note into a CPU sink.
481
+ _MAX_HTML = 2_000_000
482
+ _MAX_SCRIPTS = 200
483
+ _MAX_EXCERPT = 120
484
+
485
+
486
+ def inline_scripts(page_html: str) -> list[str]:
487
+ """Bodies of inline ``<script>`` blocks, bounded in count and length."""
488
+ if not page_html:
489
+ return []
490
+ out: list[str] = []
491
+ for match in _SCRIPT_BLOCK_RE.finditer(page_html[:_MAX_HTML]):
492
+ attrs, body = match.group(1), match.group(2)
493
+ if re.search(r"\bsrc\s*=", attrs, re.I):
494
+ continue
495
+ if re.search(r"\btype\s*=\s*['\"]?(?:application/(?:ld\+)?json|text/template)", attrs, re.I):
496
+ continue
497
+ if body.strip():
498
+ out.append(body)
499
+ if len(out) >= _MAX_SCRIPTS:
500
+ break
501
+ return out
502
+
503
+
504
+ def strict_dynamic_gadgets(page_html: str) -> list[tuple[str, int, str]]:
505
+ """Count script-creating gadgets in the page's inline code.
506
+
507
+ Returns ``(label, occurrences, excerpt)``; the excerpt is whitespace-
508
+ collapsed and truncated so it can sit in a finding note. A match is a
509
+ lead -- the gadget still has to receive attacker-controlled data.
510
+ """
511
+ found: list[tuple[str, int, str]] = []
512
+ scripts = inline_scripts(page_html)
513
+ for label, pattern in _GADGET_PATTERNS:
514
+ count = 0
515
+ excerpt = ""
516
+ for script in scripts:
517
+ for match in pattern.finditer(script):
518
+ count += 1
519
+ if not excerpt:
520
+ snippet = " ".join(match.group(0).split())
521
+ excerpt = snippet[:_MAX_EXCERPT]
522
+ break
523
+ if count:
524
+ found.append((label, count, excerpt))
525
+ return found
526
+
527
+
528
+ def allowlisted_jsonp(assessment: Assessment, page_html: str, page_url: str = "") -> list[str]:
529
+ """Script URLs on a host the policy trusts that take a callback parameter.
530
+
531
+ The classic JSONP bypass: ``<script src=allowed-host/jsonp?callback=...>``
532
+ passes a host allowlist without any nonce. Under ``'strict-dynamic'`` the
533
+ allowlist is ignored for markup-inserted scripts, so this returns nothing:
534
+ claiming a bypass there would be wrong.
535
+ """
536
+ if not assessment.enforced or not page_html or assessment.strict_dynamic():
537
+ return []
538
+ limit = 0
539
+ for policy in assessment.enforced:
540
+ resolved = policy.policy_for_scripts("elem")
541
+ if resolved is not None:
542
+ limit = max(limit, len(resolved[1]))
543
+ if not limit:
544
+ return []
545
+ out: list[str] = []
546
+ seen: set[str] = set()
547
+ for match in re.finditer(r"<script\b[^>]*\bsrc\s*=\s*(['\"]?)([^'\"\s>]+)",
548
+ page_html[:_MAX_HTML], re.I):
549
+ url = match.group(2)
550
+ if not _CALLBACK_PARAM_RE.search(url):
551
+ continue
552
+ absolute = _absolute(url, page_url) or url
553
+ if absolute in seen:
554
+ continue
555
+ verdict = assessment.feasibility(f'<script src="{absolute}"></script>', page_url)
556
+ if verdict.allowed:
557
+ seen.add(absolute)
558
+ out.append(absolute)
559
+ if len(out) >= 20:
560
+ break
561
+ return out
562
+
563
+
564
+ def _split_policies(value: str) -> list[str]:
565
+ """Split one header value into policies.
566
+
567
+ A comma between policies is only a separator when what follows looks like a
568
+ directive name; commas inside a source expression or report URI are not.
569
+ """
570
+ return [chunk.strip() for chunk in _POLICY_SPLIT_RE.split(value or "") if chunk.strip()]
571
+
572
+
573
+ # ---------------------------------------------------------------------------
574
+ # Source expression matching
575
+ # ---------------------------------------------------------------------------
576
+
577
+ def _host_of(url: str) -> str:
578
+ try:
579
+ parts = urllib.parse.urlsplit(url)
580
+ except ValueError:
581
+ return url
582
+ host = parts.hostname or ""
583
+ return f"{parts.scheme}://{host}:{parts.port}" if parts.port else f"{parts.scheme}://{host}"
584
+
585
+
586
+ def _absolute(url: str, base: str) -> str:
587
+ if url.startswith("//"):
588
+ scheme = urllib.parse.urlsplit(base).scheme or "https"
589
+ return f"{scheme}:{url}"
590
+ if re.match(r"^[a-z][a-z0-9+.-]*:", url, re.I):
591
+ return url
592
+ if base:
593
+ return urllib.parse.urljoin(base, url)
594
+ return ""
595
+
596
+
597
+ def source_matches(source: str, url: str, self_origin: str = "") -> bool:
598
+ """Does one CSP source expression allow *url*?
599
+
600
+ Implements the parts that decide a script load: ``'self'``, ``*``, scheme
601
+ sources, host sources with optional wildcard/port/path. It deliberately
602
+ ignores nonces and hashes (they cannot be satisfied by injected markup).
603
+ """
604
+ src = (source or "").strip()
605
+ low = src.lower()
606
+ if not src or low in ("'none'", "'unsafe-inline'", "'unsafe-eval'", "'wasm-unsafe-eval'",
607
+ "'strict-dynamic'", "'report-sample'", "'unsafe-hashes'"):
608
+ return False
609
+ try:
610
+ parts = urllib.parse.urlsplit(url)
611
+ except ValueError:
612
+ return False
613
+ if not parts.scheme:
614
+ return False
615
+ scheme = parts.scheme.lower()
616
+ host = (parts.hostname or "").lower()
617
+ port = parts.port or _DEFAULT_PORTS.get(scheme, 0)
618
+
619
+ if low == "'self'":
620
+ if not self_origin:
621
+ return False
622
+ try:
623
+ base = urllib.parse.urlsplit(self_origin)
624
+ except ValueError:
625
+ return False
626
+ base_port = base.port or _DEFAULT_PORTS.get(base.scheme.lower(), 0)
627
+ return (base.scheme.lower() == scheme and (base.hostname or "").lower() == host
628
+ and base_port == port)
629
+
630
+ if low == "*":
631
+ return scheme in ("http", "https", "ws", "wss", "ftp")
632
+
633
+ scheme_match = _SCHEME_SRC_RE.match(src)
634
+ if scheme_match:
635
+ return scheme_match.group(1).lower() == scheme
636
+
637
+ match = _HOST_SRC_RE.match(src)
638
+ if not match:
639
+ return False
640
+ src_scheme, src_host, src_port, src_path = match.groups()
641
+ if src_scheme:
642
+ if src_scheme.lower() != scheme:
643
+ return False
644
+ elif scheme not in ("http", "https", "ws", "wss"):
645
+ # A scheme-less host source matches only network schemes, and permits
646
+ # the http -> https upgrade.
647
+ return False
648
+ if not _host_matches(src_host, host):
649
+ return False
650
+ if src_port and src_port != "*":
651
+ if int(src_port) != port:
652
+ return False
653
+ elif not src_port and port != _DEFAULT_PORTS.get(scheme, 0):
654
+ # No port in the source means the scheme's default port only.
655
+ return False
656
+ if src_path:
657
+ path = parts.path or "/"
658
+ if src_path.endswith("/"):
659
+ if not path.startswith(src_path):
660
+ return False
661
+ elif path != src_path and not path.startswith(src_path + "/"):
662
+ return False
663
+ return True
664
+
665
+
666
+ def _host_matches(pattern: str, host: str) -> bool:
667
+ pattern = (pattern or "").lower()
668
+ if pattern == "*":
669
+ return True
670
+ if pattern.startswith("*."):
671
+ suffix = pattern[1:] # ".example.com"
672
+ # Per CSP, *.example.com matches subdomains but not example.com itself.
673
+ return host.endswith(suffix) and host != suffix.lstrip(".")
674
+ return pattern == host