Double Encoding and Context Confusion Attacks
What you'll learn: How attackers exploit multiple layers of encoding or context transitions to sneak malicious payloads past security filters.
The Core Problem
Even when you apply output encoding correctly, attackers can sometimes bypass your defenses by exploiting double encoding (encoding the same data twice) or context confusion (causing data to be interpreted in different security contexts).
Think of it like security checkpoints at an airport. If you encode dangerous characters once (say, converting < to <), a basic filter checks and says "safe!" But if an attacker double-encodes (< becomes &lt;), your filter might pass it through. When the browser or application decodes it twice, the original < reappears—bypassing your protection.
How Double Encoding Works
An attacker encodes their payload multiple times:
Original: <script>
First pass: <script> (HTML entity encoded)
Second: &lt;script&gt; (encoded again!)
If your validation sees the doubly-encoded version, it looks harmless. But if the application or browser decodes twice, the malicious <script> emerges.
Context Confusion
This happens when data transitions between contexts (HTML → JavaScript → URL) and security checks only apply to one layer. For example, data might be safely HTML-encoded but then inserted into JavaScript, where different encoding rules apply—creating an exploitable gap.
<!-- Encoded for HTML, but vulnerable in JS context -->
<div data-name="<script>">
<script>
var name = element.getAttribute('data-name'); // Gets decoded!
document.write(name); // XSS executes here
</script>
Key Takeaway: Always decode input to canonical form before validation, apply context-appropriate encoding at every output boundary, and never assume one layer of encoding provides complete protection—attackers exploit encoding confusion to bypass filters.