Skip to content
XSS Write-up Advanced

XSS in Gmail's Amp4Email

A cross-site scripting vulnerability existed in Gmail's AMP4Email implementation because Gmail's filter decoded CSS escape sequences inside selectors, allowing an attacker to inject a closing style tag and execute arbitrary JavaScript. An attacker could send a specially crafted email that runs script in the recipient's Gmail session.

Adi "Adico" Cohen Follow

Published on adico.me

Bounty$5,000 View original

AMP is most commonly used as a framework to develop fast-loading content on the web.

Adi "Adico" Cohen (@wir3less2), on adico.me

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 4 min read.

Context

AMP is a framework for building fast-loading web content. AMP4Email is an AMP project that lets email senders include a subset of HTML with AMP components for layouts, templates and forms, producing dynamic emails. Gmail supports AMP4Email and provides a Playground where you can write and validate AMP emails and send them to your own mailbox to see how they render.

Setup

The researcher used Gmail's AMP Playground to write and validate AMP emails, and sent test emails to a Gmail mailbox to observe how they render. No special accounts or tools beyond the Playground and a Gmail inbox are described. The issue was reported to Google on 27 March 2021.

Finding it

After a few days in the Playground, the researcher had about five vectors that produced either broken HTML or complete XSS in the Playground. When the initial vector was sent to Gmail, the entire document failed to load, suggesting a second filter or a different AMP version with extra security validations.

The approach was to create a mismatch between the rendering context used by the filter and the context the browser actually uses. A payload must contain more than one rendering context. Plain HTML is the first; additional contexts can come from templates, SVG, MathML or CSS. In AMP4Email most of these are forbidden, leaving stylesheets as the main option, so the research focused on CSS.

The initial vector relied on AMP leaving the CSS context as soon as it sees the string </style, even without a closing > or whitespace. The browser, by contrast, ignores </styleX> and stays in CSS. The payload was:

<style amp-custom>body{color:red}</styleX>
<meta name="</style><img src='x'onerror=alert(1)">

The filter sees the </styleX> as ending the style and treats the name attribute of the <meta> tag as safe HTML. The browser stays in CSS, treats the <meta> tag as malformed CSS, terminates the stylesheet at the real </style> and renders the <img> with its onerror, triggering the XSS. Sending this to Gmail made the whole document fail to load, which is what happens on a significant validation error.

Exploitation

Step 1: Probe Gmail's restrictions with harmless payloads

The researcher sent payloads that use a string-comment hybrid in CSS to see what Gmail allows:

<style>div{font-family:'aa/*f<br> ff*/'}</style>
<style>div{font-family:'aa/*f</xxx> ff*/'}</style>
<style>div{font-family:'aa/*f</style> ff*/'}</style>

AMP allows any value inside this hybrid. Gmail does not. The first two arrived with a change: they were escaped. For example:

<style>div{font-family:'aa/*f</xxx> ff*/'}</style>

became:

<style>div{font-family:'aa/*f\00003c/xxx\00003e ff*/'}</style>

Because < and > were encoded as CSS escapes, the tag could not be terminated. Gmail does not allow any value inside this hybrid, unlike AMP.

Step 2: Find a context that is not escaped

After trying HTML entities in different locations of the CSS statement, the researcher found that a selector was returned unescaped. Sending:

<style amp-custom>[id='a<br>aa'],body{font-family:'aaaa'}</style>

to Gmail returned exactly the same thing, with no escaping or other mutation.

Step 3: Try to close the style tag inside a selector

Copying the </styleX><meta…> idea into a selector failed in the AMP Playground with an error, because AMP detects it as malformed CSS. The cutoff is after encountering </style. Deleting the e and sending </styl> also failed: Gmail deletes the payload as soon as anything resembling a closing </style> tag is encountered.

Step 4: Use a CSS escape inside the selector

The researcher sent an encoded selector to see whether Gmail would decode it:

<style amp-custom>[id='a<b\000072> aa'],body{font-family:'aaaa'}</style>

Gmail decoded \000072 into the letter r.

Step 5: Encode the closing style tag

With decoding confirmed, the next payload encoded the y in </style>:

<style amp-custom>[id='a</st\000079le> aa'],body{font-family:'aaaa'}</style>

Gmail decoded it into a usable closing style tag, and the payload only mutates into a usable form after Gmail's extra filter runs.

Step 6: Final payload

The <meta> tag was no longer needed. The final payload injects an <img> tag, though any HTML could be used:

  <style amp-custom>[id='</st\000079le></head><body>
  <img src=https://bla.com/xx.jpg onerror=a=1>']{color:blue}</style>

Opening the email showed a broken image, and the browser's developer tools confirmed the XSS had executed.

Root cause

The root cause is a rendering-context mismatch between Gmail's filter and the browser, combined with inconsistent handling of CSS escapes. AMP leaves the CSS context at the string </style even without a closing >, while the browser does not. Gmail's filter escapes < and > in most CSS contexts but not inside selectors, and it decodes CSS escapes such as \000072 and \000079 in selectors. That lets an attacker write a closing </style> in encoded form that the filter does not recognise as a tag terminator but that the browser decodes and acts on. The existing defences (AMP validation and Gmail's extra filter) each handled part of the problem but not the combination.

Impact

The researcher demonstrated JavaScript execution in a received email via an onerror handler on an injected image. The researcher demonstrated execution with an onerror handler on an injected image. The report does not describe what data or actions the script could reach beyond that demonstration.

Fix

The report does not describe the fix. The timeline notes the fix was noticed on 7 July 2022, though it was actually fixed much earlier and there was an issue with the notice. The timeline notes that the fix was noticed on 7 July 2022, though it was actually fixed much earlier and there was an issue with the notice.

Variants to test

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 15 min read.

What happened, in plain words

A security researcher found a way to make a Gmail email run JavaScript code when the recipient opened it. This kind of bug is called cross-site scripting, or XSS for short. The researcher demonstrated JavaScript execution in a received email via an onerror handler on an injected image.

The trick was not a single clever line of code. It was a disagreement between two programs about what a piece of text means. Gmail runs a filter that reads the email before showing it, and the browser that finally displays the email reads the same text too. If the filter and the browser disagree about where a piece of CSS (the language used to style web pages) ends and where ordinary HTML begins, an attacker can hide something dangerous in the gap.

The researcher reported it to Google on 27 March 2021, Google replied "Nice Catch" on 1 April 2021, and a bounty of 5000 USD was awarded on 13 April 2021. The fix was noticed on 7 July 2022, though it had actually been fixed much earlier and there was an issue with the notice. The blog post was published on 9 July 2022.

Background: what AMP and AMP4Email are

AMP is a framework for building web pages that load quickly. Think of it as a set of building blocks and rules that a website can use so that pages appear fast on a phone with a weak connection.

One of AMP's projects is called AMP4Email. Email used to be plain text, then it became HTML (the language web pages are written in), and AMP4Email goes one step further: it lets a sender put a small, restricted subset of HTML into an email, plus a few ready-made AMP components for layouts, templates and forms. The result is called a dynamic email: an email that can do things, not just show text and pictures.

Many of the leading mail services adopted AMP4Email. Gmail is one of them.

When the researcher first heard about this feature a few years earlier, the first reaction was the same as many people's: "This can't be secured! How did they prevent XSS?"

Gmail provides a Playground website where you can write an AMP email, have it validated, and send it to your own mailbox to see how it renders in Gmail. That is perfect for security research: you can try things safely and watch the result arrive in your own inbox.

After a few days in that sandbox, the researcher had about five different vectors. A vector here means a particular way of writing a payload (the malicious snippet) that might get past the defences. Some of those vectors produced broken HTML that might be exploited with extra work, and some produced complete XSS in the Playground.

It sounded easy. It was not. When any of those vectors was sent to Gmail, the entire document failed to load. That is what happens when the filter encounters a significant validation error. So there was either a second filter in play, or a completely different version of AMP with additional security validations.

Methodology: making two readers disagree

Over the years the researcher had learned that the easiest way to get around an XSS filter is to trick it into a different rendering context than the one the browser will actually use to render a given piece of code.

A rendering context is simply "which language am I reading right now?". The same characters can mean completely different things depending on the context. A useful everyday comparison: the letters "ROT" mean a direction on a road sign, but inside the word "ROTATE" they are just part of a longer word. If one reader thinks it is looking at a sign and another thinks it is looking at a word, they will interpret the same letters differently.

For this trick to work, the payload has to contain more than one rendering context. Plain HTML is the first context. Additional contexts can be reached through many means: templates, SVG (a format for drawing with markup), MathML (a format for mathematical notation), CSS, and so on.

In the scope of AMP4Email, however, most of those are forbidden. One of the only real options left is stylesheets, so the research focused on CSS.

Initial vector: the greedy </style

For the attack to work, the researcher needed to find a discrepancy between how the filter renders a stylesheet and how the browser does. A discrepancy means the two disagree. There are two directions this can go:

  1. Trick the filter into believing a fake style tag (either an opening or a closing one) is real and should be treated as such, when in reality the browser will ignore it.
  2. The exact opposite: make the filter treat a real tag as fake and ignore it.

The researcher already had a vector that triggered XSS in the AMP Playground but could not get past Gmail's filter. Here it is:

HTML
<style amp-custom>body{color:red}</styleX>
<meta name="</style><img src='x'onerror=alert(1)">

Line by line, in plain words:

  • <style amp-custom> opens a style block. The amp-custom attribute is AMP's way of saying "this is the custom CSS for this email". Everything until the closing style tag is meant to be CSS.
  • body{color:red} is ordinary CSS: make the page body red.
  • </styleX> looks like a closing style tag with an extra X on the end. It is not a real closing tag.
  • <meta name="..."> is an HTML tag that normally carries metadata about the page. Its name attribute is a string, and strings are supposed to be harmless.
  • Inside that name attribute there is </style><img src='x'onerror=alert(1)>. The </style> is a real closing style tag, and the <img> is an image tag whose src points to x (which does not exist). The onerror attribute is JavaScript that the browser runs when the image fails to load. alert(1) pops up a dialog box, which is the classic harmless proof that JavaScript ran.

Why does this work? AMP is being slightly too greedy: it leaves the CSS context as soon as it encounters the string </style, even if there is no closing bracket > or at least a whitespace after it. The researcher assumes this was in place to mitigate other attacks. But it can be used to trick the filter into believing we are back in HTML context, while the browser obviously ignores </styleX> entirely and stays well within the realm of CSS.

Next, the rendering context mismatch is used to position the XSS in a way that looks safe to the filter. The name attribute of a <meta> tag was chosen, but any safe attribute would work here.

When the browser (which is still rendering CSS at this point) encounters the <meta> tag, it counts it as malformed CSS, terminates the stylesheet at the real </style> tag, and renders the <img> tag with its onerror attribute. That triggers the XSS.

If you try sending this payload to Gmail, however, the entire document fails to load.

Some (more) research: probing Gmail's rules

At this point the researcher still thought the payload could be sneaked past Gmail. To start off, a few "harmless" payloads were sent to get a sense of what restrictions are in place before trying anything too malicious. This is a standard technique: send something that cannot hurt anyone, and watch what the filter does to it.

The tests included:

HTML
<style>div{font-family:'aa/*f<br> ff*/'}</style>
<style>div{font-family:'aa/*f</xxx> ff*/'}</style>
<style>div{font-family:'aa/*f</style> ff*/'}</style>

What is going on in these lines? Each one sets the font family of div elements to a strange string. The string mixes a CSS comment (/* ... */) with a piece of HTML-looking text (<br>, </xxx>, </style>). This is called a string-comment hybrid: a value that is partly a quoted string and partly a comment, which is a good place to hide characters that a filter might otherwise treat as markup.

  • The first line hides <br> (an HTML line break tag) inside the string.
  • The second line hides </xxx> (a made-up closing tag) inside the string.
  • The third line hides a real </style> inside the string.

AMP allows any value to be present inside this string-comment hybrid. Gmail does not.

The first two payloads worked well: they arrived at the inbox with only a minor change. They were escaped. For example:

HTML
<style>div{font-family:'aa/*f</xxx> ff*/'}</style>

Transformed into:

HTML
<style>div{font-family:'aa/*f\00003c/xxx\00003e ff*/'}</style>

What does escaping mean here? The filter replaced the < character with the CSS escape \00003c and the > character with \00003e. A CSS escape is a way of writing a character by its numeric code, so the browser will still understand it as < and >, but a filter that is looking for the literal characters < and > will not see them. It is like writing a word in a code so that a scanner does not recognise it, while the reader who knows the code still reads it normally.

Since a tag cannot be terminated without the HTML entities < and >, what looked like a promising vector in AMP seemed much less interesting after Gmail ran its magic on it.

More time was spent trying to put HTML entities in different locations of the CSS statement, until the researcher reached the holy grail: the CSS selector.

A CSS selector is the part of a CSS rule that says which elements the rule applies to. In [id='a']{color:blue}, the [id='a'] is a selector that matches elements whose id attribute is a. Selectors are a different sub-context inside CSS, and that turned out to matter.

If we send the following payload to Gmail:

HTML
<style amp-custom>[id='a<br>aa'],body{font-family:'aaaa'}</style>

we get back the exact same thing, with no escaping or other mutations taking place.

Line by line:

  • <style amp-custom> opens the custom style block.
  • [id='a<br>aa'] is a selector matching an element whose id is the literal string a<br>aa. Notice that <br> is sitting inside the selector, unescaped.
  • ,body adds the body element to the same rule.
  • {font-family:'aaaa'} sets the font family to aaaa.
  • </style> closes the style block.

So all that was needed now, the researcher thought, was to copy in the </styleX><meta…> payload and be done. It was written into the AMP Playground editor, only to immediately receive an error.

So a fake closing tag cannot be placed in the middle of a selector, because AMP detects it as malformed CSS.

At this point the researcher still thought the payload could be jiggled a little to make it work, so the cutoff point where AMP errors out was investigated. As expected, it happens after encountering </style.

The e was deleted and </styl> was sent to see how Gmail handles this case. Gmail did not appreciate the attempt.

So now we know that Gmail has an even stricter filter and just deletes the payload as soon as anything resembling a closing </style> tag is encountered.

The payload: encoding the closing tag

Before giving up on this direction completely, there was one last idea left to try.

Every other CSS context encoded the HTML entities, except selectors. So what would happen if an encoded selector were sent to Gmail? Would it get decoded?

To decode means to turn the escape back into the real character. If the filter decodes it, the browser will see a real < or >, and the filter may not notice it was ever there.

The safest payload possible was sent first, just to ensure that if it does get filtered, it will be because of the encoding and nothing else:

HTML
<style amp-custom>[id='a<b\000072> aa'],body{font-family:'aaaa'}</style>

Line by line:

  • [id='a<b\000072> aa'] is a selector. Inside it, \000072 is the CSS escape for the letter r. So the selector is really asking for an element whose id is a<br> aa.
  • ,body adds the body element.
  • {font-family:'aaaa'} sets the font family.
  • </style> closes the style block.

And yes, it worked. Gmail actually decoded the \000072 into the letter r.

Now for the real test: can this be used to inject a closing style tag?

HTML
<style amp-custom>[id='a</st\000079le> aa'],body{font-family:'aaaa'}</style>

Line by line:

  • [id='a</st\000079le> aa'] is a selector. Inside it, \000079 is the CSS escape for the letter y. So the selector really contains </style>.
  • ,body adds the body element.
  • {font-family:'aaaa'} sets the font family.
  • </style> closes the style block.

It comes out as:

Yes, it can.

At this point the <meta> tag could be completely ditched. It is not needed, because AMP rightfully does not treat </st\000079le> as anything it should worry about. And this only mutates into a usable payload after Gmail's extra filter is executed. In other words: the filter sees a harmless escape, decodes it into a real closing tag, and hands the browser something the filter itself never checked.

To tie everything together, the following final payload injects an <img> tag, though at this point any HTML could be used:

HTML
  <style amp-custom>[id='</st\000079le></head><body>
  <img src=https://bla.com/xx.jpg onerror=a=1>']{color:blue}</style>

Line by line:

  • [id=' starts a selector whose id value is a quoted string.
  • </st\000079le> is the encoded closing style tag. After Gmail decodes it, it becomes </style>.
  • </head><body> closes the head section of the page and opens the body. This is ordinary HTML that only makes sense once the style block has been closed.
  • <img src=https://bla.com/xx.jpg onerror=a=1> is an image tag pointing at a picture that does not exist. When the image fails to load, the browser runs onerror=a=1, which is JavaScript. Here it just assigns 1 to a variable, which is enough to prove the code ran.
  • ']{color:blue} closes the selector string and the rule, setting the colour to blue.
  • </style> closes the style block.

The researcher could immediately see this worked when the email was opened and a broken image appeared.

Looking closer at the browser's developer tools confirmed it.

A new XSS was born, only to then quickly die because it was reported to Google.

Timeline

  • Mar 27th 2021: reported the issue to Google
  • Apr 1st 2021: "Nice Catch" response from Google
  • Apr 13th 2021: awarded a bounty of 5000 USD
  • Jul 7th 2022: noticed the issue was fixed (in reality this was fixed much quicker, there was just an issue with the notice)
  • Jul 9th 2022: blog post published

Root cause

The root cause is a rendering-context mismatch between Gmail's filter and the browser, combined with inconsistent handling of CSS escapes. AMP leaves the CSS context at the string </style even without a closing >, while the browser does not. Gmail's filter escapes < and > in most CSS contexts but not inside selectors, and it decodes CSS escapes such as \000072 and \000079 in selectors. That lets an attacker write a closing </style> in encoded form that the filter does not recognise as a tag terminator but that the browser decodes and acts on. The existing defences (AMP validation and Gmail's extra filter) each handled part of the problem but not the combination.

Impact

An attacker who can send an AMP email to a Gmail user could execute JavaScript in the context of the email when the recipient opens it. The researcher demonstrated execution with an onerror handler on an injected image. The report does not describe what data or actions the script could reach beyond that demonstration.

Fix

The report does not describe the fix. The timeline notes the fix was noticed on 7 July 2022, though it was actually fixed much earlier and there was an issue with the notice. The timeline notes that the fix was noticed on 7 July 2022, though it was actually fixed much earlier and there was an issue with the notice.

Variants to test

Glossary

  • AMP: a framework for building web pages that load quickly, made of rules and ready-made components.
  • AMP4Email: an AMP project that lets email senders include a restricted subset of HTML and AMP components in an email, producing a dynamic email.
  • Attribute: a piece of information attached to an HTML tag, such as name or src.
  • Bounty: a payment made by a company to a researcher who reports a security bug.
  • Browser: the program that displays web pages and emails, such as Chrome or Firefox.
  • Context (rendering context): which language a piece of text is being read as at a given moment, for example HTML, CSS or a string inside an attribute.
  • CSS: the language used to describe how a web page looks, including colours, fonts and layout.
  • CSS escape: a way of writing a character by its numeric code, such as \00003c for <, so the browser still understands it.
  • CSS selector: the part of a CSS rule that says which elements the rule applies to, such as [id='a'].
  • Developer tools: the built-in panel in a browser that lets you inspect the page, its HTML and its scripts.
  • Discrepancy: a disagreement between two programs about what something means.
  • Dynamic email: an email that can do things, not just show text and pictures, thanks to AMP4Email.
  • Escaping: replacing a special character with a coded form so that a filter does not treat it as special, while the browser still understands it.
  • Filter: a program that reads content before it is shown and removes or blocks anything dangerous.
  • Framework: a set of rules and building blocks that developers use to build something, in this case web pages.
  • HTML: the language web pages and emails are written in, made of tags such as <img> and <style>.
  • HTML entity: a coded way of writing a character in HTML, such as &lt; for <.
  • JavaScript: the programming language that runs in the browser and can make a page do things.
  • Malformed: written in a way that does not follow the rules of the language.
  • MathML: a markup format for writing mathematical notation.
  • Mutation: a change made to a payload by a filter, such as escaping or deleting part of it.
  • onerror: an HTML attribute that holds JavaScript to run when an image fails to load.
  • Payload: the malicious snippet an attacker sends, designed to get past defences.
  • Playground: Gmail's website where you can write, validate and send AMP emails to your own mailbox.
  • Pseudo-class: a CSS selector that matches elements based on their state, such as :hover.
  • Sandbox: a safe place to try things without affecting real users.
  • String-comment hybrid: a CSS value that is partly a quoted string and partly a comment, useful for hiding characters from a filter.
  • SVG: a markup format for drawing shapes and images.
  • Tag: a piece of HTML markup such as <img> or </style> that tells the browser what to do.
  • Template: a reusable piece of markup that can be filled in later.
  • Validation: checking that a document follows the rules of a language, and rejecting it if it does not.
  • Vector: a particular way of writing a payload that might get past the defences.
  • XSS (cross-site scripting): a bug where an attacker gets their own JavaScript to run inside a page or email that the victim trusts.

More from Google

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Cross-site scripting (XSS)

The lesson behind this report.

Script an attacker supplies runs in another user's browser, on the target's origin, with that user's session.