XSS Filter Bypass Methodology
Overview
This skill provides a systematic approach for bypassing HTML/JavaScript sanitization filters in authorized security testing contexts (CTF challenges, penetration testing, security research). The methodology emphasizes understanding filter mechanisms before attempting bypasses, avoiding trial-and-error approaches in favor of systematic analysis.
Phase 1: Filter Analysis
Before attempting any bypasses, thoroughly analyze the filter implementation:
Identify the Sanitization Library
- Determine which library performs sanitization (BeautifulSoup, DOMPurify, html-sanitizer, etc.)
- Identify the parser being used (html.parser, lxml, html5lib for BeautifulSoup)
- Research known quirks and bypass techniques for that specific library/parser combination
Map Filter Behavior
Create a systematic map of what the filter blocks vs. preserves:
Blocked Elements: Test which HTML tags are removed
- Script-related:
<script>, <noscript>
- Frame-related:
<iframe>, <frame>, <object>, <embed>
- Other dangerous:
<base>, <link>, <meta>
Blocked Attributes: Test which attributes are stripped
- Event handlers:
onclick, onload, onerror, onmouseover, etc.
- URL attributes with javascript:
href="javascript:...", src="javascript:..."
Preserved Elements: Identify what passes through unchanged
- Standard HTML elements:
<div>, <span>, <p>, <img>, <a>, <style>
- SVG elements:
<svg>, <animate>, <set>
- Math elements:
<math>
Examine Filter Implementation
- Read the filter source code if available
- Look for regex-based filtering (often bypassable)
- Check if filtering is case-sensitive
- Determine if the filter runs once or recursively
Phase 2: Systematic Bypass Categories
Organize bypass attempts by category rather than random trial-and-error:
Category 1: Parser Differential Exploits
Different parsers interpret malformed HTML differently. The server-side sanitizer may parse HTML differently than the browser:
- Nested tag confusion:
<noscript><style></noscript><img src=x>
- Comment injection:
<!--<script>-->alert(1)<!--</script>-->
- Encoding mismatches: UTF-7, charset switching
Category 2: Alternative JavaScript Execution Vectors
If <script> is blocked, identify other execution paths:
- SVG with script:
<svg><script>alert(1)</script></svg>
- SVG event handlers:
<svg>
- SVG animate:
<svg><animate>
- Math elements:
<math><maction actiontype="statusline#http://evil">
Category 3: Event Handler Variations
If standard event handlers are blocked:
- Less common events:
onfocus, onblur, onanimationend, ontransitionend
- Attribute injection: Breaking out of attribute context
- Data attributes with event delegation
Category 4: URL-Based Execution
- javascript: protocol in href:
<a href="javascript:alert(1)">
- data: URLs:
<a href="data:text/html,<script>alert(1)</script>">
- Encoded payloads: URL encoding, HTML entities, mixed encoding
Category 5: CSS-Based Attacks
- CSS expressions (legacy IE):
<div style="background:expression(alert(1))">
- CSS injection for data exfiltration
- @import with data URLs
Phase 3: Testing Methodology
Build a Testing Harness First
Before testing individual payloads, create infrastructure for efficient testing:
# Example: Test multiple payloads at once
payloads = [
'<script>alert(1)</script>',
'<img src=x
'<svg
# ... more payloads
]
for payload in payloads:
filtered = apply_filter(payload)
print(f"Input: {payload}")
print(f"Output: {filtered}")
print(f"Preserved: {payload == filtered}")
print("---")
Two-Stage Verification
- Stage 1 - Filter preservation: Does the payload survive the filter?
- Stage 2 - Browser execution: Does the filtered payload execute in the browser?
Run Stage 1 tests first to eliminate non-viable candidates before slower browser testing.
Document All Attempts
Maintain a log of:
- What was tried
- Why it failed (filtered out vs. didn't execute)
- Insights gained for next attempt
Phase 4: Verification and Validation
Multiple Verification Steps
- Run the verification test multiple times
- Check all success criteria, not just the primary indicator
- Examine the filtered output for anomalies (duplicate tags, malformed HTML)
Cross-Browser Considerations
- A bypass working in Chrome may not work in Firefox or Safari
- Identify which browser the test environment uses
- Document browser-specific behavior
Handle Verification Discrepancies
If initial tests pass but final verification fails:
- Re-read the task requirements
- Check for additional validation steps
- Examine timing issues or race conditions
- Verify the test environment matches expectations
Common Pitfalls to Avoid
Premature Success Declaration
- Do not celebrate after a single test pass
- Run additional verification rounds
- Check the overall task status, not just test output
Workarounds vs. Understanding
- Avoid hacky workarounds that mask underlying issues
- If the test expects files in unexpected locations, understand why before copying files
- Workarounds may introduce inconsistencies
Inefficient Trial-and-Error
- Do not try random XSS vectors without a systematic framework
- Research before attempting; look up known bypass techniques first
- Understand why previous attempts failed before trying similar approaches
Ignoring Malformed Output
- Pay attention to duplicate or malformed tags in filtered output
- Malformed output may indicate an unstable bypass
- Question whether the solution is reliable
Missing Root Cause Analysis
When a bypass works, understand WHY:
- How does the sanitizer parse the payload?
- What browser behavior enables execution?
- Is this a stable, reliable technique or a fragile edge case?
Reference Resources
For authorized security testing contexts, these resources provide bypass techniques:
- OWASP XSS Filter Evasion Cheat Sheet
- PortSwigger Web Security Academy
- HTML5 Security Cheatsheet
- BeautifulSoup documentation on parser differences
- Browser-specific parsing quirks documentation
1---2name: filter-js-from-html3description: This skill provides guidance for XSS filter bypass tasks where the goal is to craft HTML payloads that execute JavaScript despite sanitization filters. Use this skill when tasks involve bypassing HTML sanitizers (like BeautifulSoup), exploiting parser differentials between server-side sanitizers and browsers, or security testing/CTF challenges involving XSS filter evasion.4---56# XSS Filter Bypass Methodology78## Overview910This skill provides a systematic approach for bypassing HTML/JavaScript sanitization filters in authorized security testing contexts (CTF challenges, penetration testing, security research). The methodology emphasizes understanding filter mechanisms before attempting bypasses, avoiding trial-and-error approaches in favor of systematic analysis.1112## Phase 1: Filter Analysis1314Before attempting any bypasses, thoroughly analyze the filter implementation:1516### Identify the Sanitization Library17- Determine which library performs sanitization (BeautifulSoup, DOMPurify, html-sanitizer, etc.)18- Identify the parser being used (html.parser, lxml, html5lib for BeautifulSoup)19- Research known quirks and bypass techniques for that specific library/parser combination2021### Map Filter Behavior22Create a systematic map of what the filter blocks vs. preserves:23241. **Blocked Elements**: Test which HTML tags are removed25 - Script-related: `<script>`, `<noscript>`26 - Frame-related: `<iframe>`, `<frame>`, `<object>`, `<embed>`27 - Other dangerous: `<base>`, `<link>`, `<meta>`28292. **Blocked Attributes**: Test which attributes are stripped30 - Event handlers: `onclick`, `onload`, `onerror`, `onmouseover`, etc.31 - URL attributes with javascript: `href="javascript:..."`, `src="javascript:..."`32333. **Preserved Elements**: Identify what passes through unchanged34 - Standard HTML elements: `<div>`, `<span>`, `<p>`, `<img>`, `<a>`, `<style>`35 - SVG elements: `<svg>`, `<animate>`, `<set>`36 - Math elements: `<math>`3738### Examine Filter Implementation39- Read the filter source code if available40- Look for regex-based filtering (often bypassable)41- Check if filtering is case-sensitive42- Determine if the filter runs once or recursively4344## Phase 2: Systematic Bypass Categories4546Organize bypass attempts by category rather than random trial-and-error:4748### Category 1: Parser Differential Exploits49Different parsers interpret malformed HTML differently. The server-side sanitizer may parse HTML differently than the browser:5051- **Nested tag confusion**: `<noscript><style></noscript><img src=x onerror=alert(1)></style>`52- **Comment injection**: `<!--<script>-->alert(1)<!--</script>-->`53- **Encoding mismatches**: UTF-7, charset switching5455### Category 2: Alternative JavaScript Execution Vectors56If `<script>` is blocked, identify other execution paths:5758- **SVG with script**: `<svg><script>alert(1)</script></svg>`59- **SVG event handlers**: `<svg onload=alert(1)>`60- **SVG animate**: `<svg><animate onbegin=alert(1)>`61- **Math elements**: `<math><maction actiontype="statusline#http://evil">`6263### Category 3: Event Handler Variations64If standard event handlers are blocked:6566- **Less common events**: `onfocus`, `onblur`, `onanimationend`, `ontransitionend`67- **Attribute injection**: Breaking out of attribute context68- **Data attributes with event delegation**6970### Category 4: URL-Based Execution71- **javascript: protocol in href**: `<a href="javascript:alert(1)">`72- **data: URLs**: `<a href="data:text/html,<script>alert(1)</script>">`73- **Encoded payloads**: URL encoding, HTML entities, mixed encoding7475### Category 5: CSS-Based Attacks76- **CSS expressions** (legacy IE): `<div style="background:expression(alert(1))">`77- **CSS injection for data exfiltration**78- **@import with data URLs**7980## Phase 3: Testing Methodology8182### Build a Testing Harness First83Before testing individual payloads, create infrastructure for efficient testing:8485```python86# Example: Test multiple payloads at once87payloads = [88 '<script>alert(1)</script>',89 '<img src=x onerror=alert(1)>',90 '<svg onload=alert(1)>',91 # ... more payloads92]9394for payload in payloads:95 filtered = apply_filter(payload)96 print(f"Input: {payload}")97 print(f"Output: {filtered}")98 print(f"Preserved: {payload == filtered}")99 print("---")100```101102### Two-Stage Verification1031. **Stage 1 - Filter preservation**: Does the payload survive the filter?1042. **Stage 2 - Browser execution**: Does the filtered payload execute in the browser?105106Run Stage 1 tests first to eliminate non-viable candidates before slower browser testing.107108### Document All Attempts109Maintain a log of:110- What was tried111- Why it failed (filtered out vs. didn't execute)112- Insights gained for next attempt113114## Phase 4: Verification and Validation115116### Multiple Verification Steps117- Run the verification test multiple times118- Check all success criteria, not just the primary indicator119- Examine the filtered output for anomalies (duplicate tags, malformed HTML)120121### Cross-Browser Considerations122- A bypass working in Chrome may not work in Firefox or Safari123- Identify which browser the test environment uses124- Document browser-specific behavior125126### Handle Verification Discrepancies127If initial tests pass but final verification fails:128- Re-read the task requirements129- Check for additional validation steps130- Examine timing issues or race conditions131- Verify the test environment matches expectations132133## Common Pitfalls to Avoid134135### Premature Success Declaration136- Do not celebrate after a single test pass137- Run additional verification rounds138- Check the overall task status, not just test output139140### Workarounds vs. Understanding141- Avoid hacky workarounds that mask underlying issues142- If the test expects files in unexpected locations, understand why before copying files143- Workarounds may introduce inconsistencies144145### Inefficient Trial-and-Error146- Do not try random XSS vectors without a systematic framework147- Research before attempting; look up known bypass techniques first148- Understand why previous attempts failed before trying similar approaches149150### Ignoring Malformed Output151- Pay attention to duplicate or malformed tags in filtered output152- Malformed output may indicate an unstable bypass153- Question whether the solution is reliable154155### Missing Root Cause Analysis156When a bypass works, understand WHY:157- How does the sanitizer parse the payload?158- What browser behavior enables execution?159- Is this a stable, reliable technique or a fragile edge case?160161## Reference Resources162163For authorized security testing contexts, these resources provide bypass techniques:164165- OWASP XSS Filter Evasion Cheat Sheet166- PortSwigger Web Security Academy167- HTML5 Security Cheatsheet168- BeautifulSoup documentation on parser differences169- Browser-specific parsing quirks documentation