XSS via Angular Template Injection
Published on bergee.it
This time I have a story about several XSS bugs I found across several programs. This type of XSS is called CSTI XSS (Client Side Template Injection) which means that the attacker can inject the javascript code inside the template language used by the client side technology.
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.
Context
This is a story about several XSS bugs found across several programs, all of the same family: Client Side Template Injection (CSTI). In CSTI the attacker injects JavaScript into the template language evaluated by a client-side framework. Modern frameworks such as Vue, React and Angular use templates to print variable values or evaluate expressions, and Angular in particular evaluates expressions written inside mustache tags.
The report opens with a minimal demonstration: a page that loads AngularJS 1.4.6 and contains a single ng-app div with the expression {{1+1}} renders 2, because the expression is evaluated rather than printed literally.
<html>
<head>
<meta charset=”utf-8″>
<script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.js”></script>
</head>
<body>
<div ng-app>{{1+1}}</div>
</body>
</html>
Angular ships a protection called the sandbox, which restricts evaluation of unsafe expressions. As the author notes, clever people found ways to bypass it, and the payload needed varies between Angular versions. The three cases below are three different sites, three different Angular versions and, in two of them, an AKAMAI WAF in front.
Setup
The only tooling mentioned is Wappalyzer, used to fingerprint the Angular version, plus the public payload collections:
- https://gist.github.com/mccabe615/[redacted]
- https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/XSS%20Injection/XSS%20in%20Angular.md
No accounts, roles or other preconditions are described.
Finding it
The author's testing methodology is short and worth repeating verbatim in spirit:
- Try
{{7*7}}as a payload and see if49is rendered somewhere. - If so, check the Angular version with Wappalyzer or by looking at the source code.
- Choose the right payload for that version and try to pop an alert box.
- When a WAF is in place, play with the payload until it gets through.
The first case is a lesson in not making assumptions. The author expected the CSTI payload not to work on the main site, tried {{7*7}} in a search box anyway, and the page came back with:
“Search Results – 49”
The expression had been evaluated: the template was live in the browser. That confirmed CSTI and the next step was to get JavaScript execution.
Exploitation
Case 1: the simple one
Wappalyzer showed Angular 1.5.x (the exact version is not remembered). The payload chosen was one for AngularJS 1.5.9 to 1.5.11 by Jan Horn, taken from PayloadsAllTheThings and modified to show the actual domain name. The final link was:
, saves and nulls $root.$$phase and replaces $root.$digest so the digest cycle can be driven manually, then calls $apply and $evalAsync. Inside $evalAsync it builds an AST node of type UnaryExpression whose operator is (window.X?void0:(window.X=true,alert(document.domain)))+, with an Identifier argument named foo. The window.X guard makes the alert fire once. The remaining lines push the crafted expression through the async queue and restore [].push.apply afterwards. The result was reflected XSS: the alert fired.
Case 2: the AKAMAI WAF in place
A reflected XSS was found on https://www.redacted.com, again through Angular template injection, this time on Angular 1.6. The original payload for Angular 1.6, from the same PayloadsAllTheThings page, was:
{{constructor.constructor(‘alert(document.domain)’)()}}
AKAMAI blocked it. After about an hour of trial and error the author got through with:
{{constructor.constructor(‘a=document;confirm(a.domain)’)()}}
The change is small: the document reference is aliased to a and alert is swapped for confirm. The confirm box popped up. The confirm box popped up.
Case 3: the stronger AKAMAI WAF in place
On another site the author found CSTI on Angular 1.4.3, again behind AKAMAI. This time the simple trick from case 2 did not work. The payload the author wanted to inject into the page context was:
x=1}}};alert(1)//
It was blocked by the WAF as written. The author then used String.fromCodePoint(), which returns a string built from a sequence of code points, here ASCII codes, to hide the characters. Brackets also triggered the WAF, so the payload was reshaped until this version worked:
{{([].toString()).constructor.prototype.charAt=[].join;$eval(([].toString()).constructor.fromCodePoint([120],[61],[49],[125],[125],[125],[59],[97],[108],[101],[114],[116],[40],[49],[41],[47],[47]));}}
The numbers 120,61,49 and so on are the ASCII codes of the characters in the original payload. Decoded, the array spells x=1}}};alert(1)//. The author notes that alert(document.domain) could not be executed because the code crashed, but reported the finding anyway.
Root cause
In all three cases the application placed user-controlled input into a page where Angular compiles templates, so the input was evaluated as an Angular expression rather than treated as text. The Angular sandbox is the only defence inside the framework, and it is bypassable with version-specific payloads, which is why the payload had to match the Angular version each time. The AKAMAI WAFs in cases 2 and 3 were defeated by small syntactic changes: aliasing document, swapping alert for confirm, and encoding the payload characters as code points fed to String.fromCodePoint(). The report does not describe the server-side code, so the exact place where the input reached the template is not stated.
Impact
Each finding is a reflected XSS: an attacker who gets a victim to open a crafted link runs JavaScript in the victim's session on the affected domain. In case 1 the payload was crafted to show the actual domain name, and in case 2 the confirm box displayed document.domain. The report does not describe what data or actions were reachable from the injected script, nor which users were affected. Case 3 is weaker in practice because the author could not get alert(document.domain) to run, as the code crashed.
Fix
The general fix is to stop feeding user input into a context where Angular compiles it: render untrusted values as text, or use Angular's own contextual escaping and avoid evaluating user input as an expression. A WAF is not a substitute, as cases 2 and 3 show.
Variants to test
- Send
{{7*7}}in every reflected parameter, search box and path segment, and look for49in the response. A positive result means the value is being compiled as an Angular expression. - Fingerprint the framework and version with Wappalyzer or the page source, then pick a sandbox-escape payload for that exact version from the public collections above. A positive result is an alert or confirm showing
document.domain. - If a WAF blocks the payload, change the syntax rather than the logic: alias
documentto a short variable, swapalertforconfirmorprompt, and encode characters withString.fromCodePoint()as in case 3. A positive result is the same popup getting through. - Try the same expressions in other client-side template engines (Vue, React and others) where user input reaches the template. A positive result is arithmetic such as
{{7*7}}being evaluated instead of printed.
What happened, in plain words
A security researcher found the same kind of bug on three different websites. The bug is called Client Side Template Injection, or CSTI for short. To understand it, you first need to know what a template is.
Modern websites are often built with frameworks: ready-made JavaScript libraries that do a lot of the work for you. Three popular ones are Vue, React and Angular. One thing these frameworks can do is take a piece of text written in a special syntax, called a template, and work out what it means. A template can print the value of a variable, or calculate an expression. For example, if a page contains the template {{1+1}}, the framework does not show the characters {{1+1}} on screen. It calculates the sum and shows 2.
That is very useful for the developer. It becomes dangerous when the website lets a visitor type something, and then puts that typed text into a template instead of treating it as plain text. If you type {{1+1}} into a search box and the page shows 2, the site has just calculated something you wrote. If it can calculate 1+1, it may also be able to run JavaScript code you wrote. That is the bug: your input is being evaluated rather than displayed.
A useful everyday comparison: imagine a shop assistant who reads out whatever is written on a note you hand over. If the note says "two plus two", the assistant says "four". That is fine when the note is a harmless sum. It is a problem when the note says "open the till and give me the money", and the assistant does it because it was written on a note. A template engine is that assistant: it does what the text says instead of just reading it aloud.
The researcher found this on three sites, each running a different version of Angular, and two of them protected by a WAF (Web Application Firewall, a filter that inspects incoming requests and blocks ones that look malicious). (Web Application Firewall, a filter that inspects incoming requests and blocks ones that look malicious). In each case the researcher had to adjust the payload to get past the version of Angular and the WAF.
Background: how Angular templates work
The report starts with a tiny demonstration page. It loads AngularJS version 1.4.6 from Google's public content network and contains one element with the expression {{1+1}}:
<html>
<head>
<meta charset=”utf-8″>
<script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.js”></script>
</head>
<body>
<div ng-app>{{1+1}}</div>
</body>
</html>
Line by line:
<html>,<head>,<body>: the ordinary skeleton of any web page.<meta charset=”utf-8″>: tells the browser which character encoding the page uses, so letters and symbols display correctly.<script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.js”></script>: loads the AngularJS library, version 1.4.6, from Google's servers. Without this script the page has no framework and the template syntax means nothing.<div ng-app>{{1+1}}</div>:ng-appis an Angular instruction that says "start the framework here, and treat everything inside this element as a template". The{{1+1}}is the template expression. Angular calculates it and the browser shows2.
Angular does not blindly run anything inside {{ }}. It has a built-in protection called the sandbox, which restricts which expressions are allowed. The sandbox is meant to stop exactly this kind of attack. Over the years, researchers found ways around it, and the trick that works depends on the exact Angular version. That is why the version matters so much in the three cases below.
How to test for it
The researcher's method is short and can be repeated on any site:
- Try
{{7*7}}as a payload and see if you see49rendered somewhere. - If so, check the Angular version with Wappalyzer or look at the source code.
- Choose the right payload for the version and try to pop an alert box.
- When there is WAF in place, play with the payload to achieve the goal.
Why each step:
{{7*7}}is harmless. It cannot do anything bad, so it is safe to send. If the page shows49, the site calculated your input, which proves the template is live. If the page shows{{7*7}}literally, the input is being treated as text and there is nothing to exploit.- The escape payload depends on the Angular version, because the sandbox changed between versions. Wappalyzer is a browser extension that looks at a page and guesses which technologies and versions it uses. Reading the page source (right-click, View Page Source) can also reveal the version in a script URL.
- With the version known, you pick a payload written for that version from a public list. The goal is a popup box (an
alertorconfirm) showing something like the site's domain name. A popup is a simple, visible proof that JavaScript ran. - A WAF sits in front of the site and blocks requests that match known attack patterns. If your payload is blocked, you change how it is written without changing what it does, until the filter no longer recognises it.
Payloads can be found here:
https://gist.github.com/mccabe615/[redacted]
The first case: the simple one
Wappalyzer showed the site was running Angular 1.5.x. The exact version is not remembered in the report.
The main site had a search box. The researcher expected the payload not to work there, because it was the main site. That assumption turned out to be wrong. Typing {{7*7}} into the search box produced a results page reading:
“Search Results – 49”
The 49 is the proof: the search term was placed into an Angular template and calculated. The lesson the researcher draws is simple: do not make any assumptions.
Now the goal was to run JavaScript. The payload chosen came from this collection:
It was a payload for AngularJS 1.5.9 to 1.5.11, written by Jan Horn. The researcher modified it so that the popup would show the actual domain name, and the final link looked like this:
This is a long line, so let us break it into pieces. First, the URL itself:
https://redacted.com/search?searchterm=is the normal search URL. Everything aftersearchterm=is what the visitor typed into the search box.- The
%27you see everywhere is the URL encoding of a single quote'. Browsers cannot put spaces or many symbols directly in a URL, so they are written as%followed by two hexadecimal digits.%27means',%22means", and so on. When the server receives the request it decodes these back into normal characters. - The whole payload is wrapped in
{{ }}, the Angular template markers, so Angular will evaluate it.
Inside the template, the payload does the following, in order:
c=''.sub.call;b=''.sub.bind;a=''.sub.apply;stores references to thecall,bindandapplymethods of a function.''.subis a short way of reachingFunction.prototype, the shared set of methods every JavaScript function has. These methods let you call a function with a chosenthisvalue, which is useful for reaching Angular's internals.c.$apply=$apply;c.$eval=b;attaches Angular's own$applyand$evalfunctions to that object, so they can be called later through it.op=$root.$$phase;$root.$$phase=null;od=$root.$digest;$root.$digest=({}).toString;saves Angular's internal state ($root.$$phasetells Angular whether it is currently updating the page), sets it tonull, and replaces$root.$digest(the function that refreshes the page) with the text of an empty object. This is preparation: it lets the payload drive Angular's update cycle by hand instead of letting Angular do it normally.C=c.$apply(c);runs Angular's$applythrough the stored reference.$root.$$phase=op;$root.$digest=od;restores the saved state and the original$digest, so the page does not stay broken.B=C(b,c,b);calls the storedbindmethod.$evalAsync("astNode=pop();astNode.type='UnaryExpression';astNode.operator='(window.X?void0:(window.X=true,alert(document.domain)))+';astNode.argument={type:'Identifier',name:'foo'};");is the heart of the attack.$evalAsyncis an Angular function that queues an expression to be evaluated later. The string passed to it builds an AST node, which is a small data structure describing an expression. The node is of typeUnaryExpression(an expression with one operand, like!xor+x), and its operator is(window.X?void0:(window.X=true,alert(document.domain)))+. When Angular evaluates that operator, it checkswindow.X. The first time,window.Xis undefined, so it runswindow.X=trueand thenalert(document.domain). Thewindow.Xguard makes sure the popup fires only once.m1=B($$asyncQueue.pop().expression,null,$root);m2=B(C,null,m1);[].push.apply=m2;takes the queued expression and pushes it through Angular's internal queue so it actually gets evaluated.a=''.sub;$eval('a(b.c)');[].push.apply=a;calls$evalon the crafted expression and then restores[].push.applyto its original value, cleaning up after itself.
The result was reflected XSS: the payload was sent in a link, the site reflected it back into the page, and the browser ran it. The alert fired.
The second case: the AKAMAI WAF in place
A reflected XSS was found on https://www.redacted.com, again through Angular template injection. This time the site used Angular 1.6. The original payload for Angular 1.6, taken from the same PayloadsAllTheThings page, was:
{{constructor.constructor(‘alert(document.domain)’)()}}
What this does:
constructoron an object gives you the function that built it. In JavaScript,constructor.constructoris a well-known way to reach theFunctionconstructor, which can turn a string into executable code.('alert(document.domain)')is the string that will become code.- The final
()calls the newly created function, soalert(document.domain)runs and shows the site's domain in a popup.
AKAMAI blocked it. After about an hour of trial and error, the researcher got through with:
{{constructor.constructor(‘a=document;confirm(a.domain)’)()}}
The change is small:
a=document;stores the browser'sdocumentobject (the page itself) in a short variable calleda.confirm(a.domain)shows a confirmation box with the domain name, instead of an alert box.
The confirm box popped up. By renaming document to a and swapping alert for confirm, the payload does the same thing but no longer contains the strings the filter was looking for. The confirm box popped up.
The third case: the stronger AKAMAI WAF in place
On another site, the researcher found CSTI on Angular 1.4.3, again behind AKAMAI. This time the simple trick from case 2 did not work. The payload the researcher wanted to inject into the page was:
x=1}}};alert(1)//
What this means:
x=1is a harmless assignment, there to make the payload look like ordinary text at the start.alert(1)is the popup.
As written, the WAF blocked it. The researcher then used String.fromCodePoint(), a JavaScript function that builds a string from a list of numeric character codes. Each character has a number, called its ASCII code (or more generally a code point). For example, the letter a is 97, l is 108, e is 101, and so on. Writing the payload as numbers hides the dangerous words from the filter. Brackets also triggered the WAF, so the payload was reshaped until this version worked:
{{([].toString()).constructor.prototype.charAt=[].join;$eval(([].toString()).constructor.fromCodePoint([120],[61],[49],[125],[125],[125],[59],[97],[108],[101],[114],[116],[40],[49],[41],[47],[47]));}}
Line by line:
([].toString()).constructorreaches theFunctionconstructor through an empty array'stoStringmethod, the same idea asconstructor.constructorin case 2 but written differently so the filter does not recognise it..prototype.charAt=[].join;replaces thecharAtmethod of strings with thejoinmethod of arrays.charAtnormally returns one character;joinglues all elements of an array into one string. This is a trick to turn the array of numbers into a string.$eval(...)is Angular's function for evaluating an expression.([].toString()).constructor.fromCodePoint([120],[61],[49],[125],[125],[125],[59],[97],[108],[101],[114],[116],[40],[49],[41],[47],[47])builds the string from the numbers. Each number is in its own pair of square brackets, which is why there are so many brackets.- The numbers
120,61,49and so on are the ASCII codes of the characters in the original payload. Decoded, the array spellsx=1}}};alert(1)//.
The researcher notes that alert(document.domain) could not be executed because the code crashed, but reported the finding anyway.
Why it works
In all three cases the application put user-controlled input into a page where Angular compiles templates. So the input was evaluated as an Angular expression instead of being treated as text. The Angular sandbox is the only defence inside the framework, and it can be bypassed with payloads written for the specific version, which is why the payload had to match the Angular version each time. The AKAMAI WAFs in cases 2 and 3 were defeated by small changes in how the payload was written: renaming document to a, swapping alert for confirm, and encoding the characters as numbers fed to String.fromCodePoint(). The report does not describe the server-side code, so the exact place where the input reached the template is not stated.
What the impact is
Each finding is a reflected XSS: the payload travels in a link, the site reflects it back into the page, and the browser runs it. An attacker who gets a victim to open such a link runs JavaScript in the victim's session on the affected domain. In case 1 the payload was crafted to show the actual domain name, and in case 2 the confirm box displayed document.domain. The report does not describe what data or actions were reachable from the injected script, nor which users were affected. Case 3 is weaker in practice because the researcher could not get alert(document.domain) to run, as the code crashed.
How to fix it
The general fix is to stop feeding user input into a context where Angular compiles it: render untrusted values as text, or use Angular's own contextual escaping and avoid evaluating user input as an expression. A WAF is not a substitute, as cases 2 and 3 show.
Variants to test
- Send
{{7*7}}in every reflected parameter, search box and path segment, and look for49in the response. A positive result means the value is being compiled as an Angular expression. - Fingerprint the framework and version with Wappalyzer or the page source, then pick a sandbox-escape payload for that exact version from the public collections above. A positive result is an alert or confirm showing
document.domain. - If a WAF blocks the payload, change the syntax rather than the logic: alias
documentto a short variable, swapalertforconfirmorprompt, and encode characters withString.fromCodePoint()as in case 3. A positive result is the same popup getting through. - Try the same expressions in other client-side template engines (Vue, React and others) where user input reaches the template. A positive result is arithmetic such as
{{7*7}}being evaluated instead of printed.
Glossary
- Angular (AngularJS): a JavaScript framework for building web pages. It can evaluate expressions written in templates.
- ASCII code: a number that represents a character. For example,
ais 97 andlis 108. - AST node: a small data structure that describes a piece of code, such as an expression, in a form a program can work with.
- Client side: happening in the visitor's browser, rather than on the server.
- CSTI (Client Side Template Injection): a bug where user input is placed into a template that the browser's framework evaluates, so the input can run as code.
- Framework: a ready-made library that provides structure and common features for building a website or app.
- Function constructor: a JavaScript feature that turns a string into a runnable function. It is often used to run code from a string.
- ng-app: an Angular instruction that marks where the framework starts and which part of the page is a template.
- Payload: the piece of input an attacker sends to trigger a bug.
- Reflected XSS: a cross-site scripting bug where the payload is sent in a request (usually a link) and immediately echoed back into the page.
- Sandbox (Angular): a built-in protection in Angular that restricts which expressions are allowed to run.
- Template: text written in a special syntax that a framework turns into output, such as
{{1+1}}becoming2. - URL encoding: writing special characters in a URL as
%followed by two hexadecimal digits, such as%27for a single quote. - WAF (Web Application Firewall): a filter in front of a website that inspects incoming requests and blocks ones that look like attacks.
- Wappalyzer: a browser extension that detects which technologies and versions a website uses.
- XSS (Cross-Site Scripting): a bug where an attacker gets JavaScript to run in another user's browser on a website.