APK AppSec · Engineering Notes #1

Parsing Binary AXML, DEX, and ARSC On-Device in Pure Kotlin

How to run a fast, offline static security audit directly on an Android phone—without apktool, jadx, or a backend server—while staying inside mobile heap limits and keeping false positives under control.

Pure Kotlin/JVM Engine · Offline-First SAST · ~7 min read

Most Android static analysis workflows assume a desktop or server stack: upload an APK to MobSF, unpack it with apktool, decompile it with jadx, and inspect the output. That is the right toolset for a deep audit, but it adds friction in two common situations: when an indie developer or small team without a SAST pipeline wants a fast pre-release sanity check on their own APK, or when an AppSec engineer, QA tester, or student needs a quick defensive go/no-go triage pass before moving to a full desktop lab.

I built APK AppSec to run that first-pass static security audit directly on an Android phone. The entire analysis engine lives in a pure Kotlin/JVM module (core/) using only java.util.zip and java.io, with zero Android SDK dependencies so the parsers, secret rules, and scoring logic run under plain JUnit on the JVM.

Privacy & network boundary: The core/ analysis engine makes zero network calls—no APK, string, or finding ever leaves the device. The INTERNET permission in the Android shell exists solely for AdMob, UMP consent, and Google Play Billing on the free tier (removable via an optional one-time in-app purchase).
2-min on-device demo: auditing OVAA (5.3 MB, 9 DEX, 80,984 strings in 13.08 s) offline and exporting structured JSON directly to Gemini for live vulnerability vs. false-positive triage. Watch on YouTube →

1. Pipeline Overview

The Android shell handles Storage Access Framework imports (ACTION_OPEN_DOCUMENT), launchable installed-app selection via ACTION_MAIN/CATEGORY_LAUNCHER queries (deliberately avoiding QUERY_ALL_PACKAGES), local Room history snapshots for version-to-version diffs, and report export. All parsing and security logic executes off the UI thread in ApkScanner:

Execution Pipelinecore/ApkScanner.kt
[.apk on device (SAF URI or exported installed APK)]
                        |
                        v
               +-----------------+
               |  ApkScanner     |  (pure JVM, Dispatchers.Default)
               +--------+--------+
                        |
     +------------------+------------------+
     |                  |                  |
     v                  v                  v
AndroidManifest.xml  classes*.dex     resources.arsc + assets/*
(AXML chunks)        (streaming 1x)   (ResTable + text filter)
     |                  |                  |
     |           +------+------+           |
     |           |             |           |
     |     string_ids     class_defs       +---> SecretRules (regex)
     |     type_ids       bytecode refs    +---> EntropyScanner (config only)
     |           |             |           |
     v           v             v           v
 Manifest    Obfuscation   APP_CODE vs   Prioritized + Deduplicated
 Findings    Analyzer      3RD_PARTY     Findings (cap: 50 total)
     |           |             |           |
     +-----------+------+------+-----------+
                        |
                        v
        HardeningScore.evaluate(allFindings)
        -> Hardening Score (0-100, A-F)
        -> Hygiene Score   (0-100, A-F)

2. Parsing Android Binaries Without apktool or jadx

Binary AndroidManifest.xml (AXML)

aapt2 compiles AndroidManifest.xml into a binary chunk stream (0x0003 root header) starting with a ResStringPool (0x0001) followed by element chunks (0x0102/0x0103). ManifestParser walks those chunks directly and decodes typed Res_value attributes (TYPE_STRING=0x03, TYPE_INT_DEC=0x10, TYPE_INT_HEX=0x11, TYPE_INT_BOOLEAN=0x12).

DEX String Tables and On-Demand Bytecode Attribution

Full Java decompilation on mobile is slow and memory-intensive. DexParser instead reads the DEX header directly (dex\n magic, string_ids, type_ids, class_defs):

  1. Decodes up to 250,000 strings (max 4,096 chars each) while preserving a 1:1 IntArray back to each raw DEX string_id.
  2. Collects L...; class descriptors from type_ids for obfuscation analysis.
  3. Only when regex rules hit (or when checking app-owned classes for direct credential field assignments), resolveBytecodeAnalysis builds a BooleanArray mask over matched string_ids and walks class_defs (static_values, fields, methods, and code_item instructions) to attribute each finding to its originating class and method (APP_CODE vs THIRD_PARTY_LIB).

resources.arsc and Binary Asset Filtering

ResourcesParser parses the compiled resource table (ResTable package and type chunks, supporting standard, sparse, and 16-bit offset entry tables) with a shared StringPools decoder for both UTF-16 and MUTF-8 pools. Mapping compiled string values back to resource keys like @string/google_api_key lets the engine distinguish standard Firebase/Maps client identifiers from unknown secrets.

For assets/, the scanner inspects text-like extensions (.properties, .json, .xml, .conf, .yml, .plist, or extensionless files) and skips binary blobs via isProbablyBinary (NUL byte or >10% non-printable bytes in the first 4 KB)—eliminating the flood of false positives from Unity/IL2CPP data bundles.

3. Staying Inside Android's Heap Budget on Multi-DEX APKs

Calling InputStream.readBytes() on large ZIP entries is deceptively expensive on Android's bounded heap: ByteArrayOutputStream doubles its backing array as it grows and then calls toByteArray() (Arrays.copyOf), peaking at 2x–3x the uncompressed entry size. Holding decoded string tables for 10–20 classes*.dex files simultaneously compounds the problem.

To keep memory flat, ApkScanner combines two mechanisms:

Kotlincore/ApkScanner.kt
internal fun readEntryBytesBounded(zip: ZipFile, entry: ZipEntry, maxBytes: Int): ByteArray? {
    val maxLong = maxBytes.toLong()
    val declaredSize = entry.size
    if (declaredSize > maxLong) return null

    return zip.getInputStream(entry).use { input ->
        if (declaredSize > 0L) {
            val expected = declaredSize.toInt()
            val buffer = ByteArray(expected)
            var offset = 0
            while (offset < expected) {
                val read = input.read(buffer, offset, expected - offset)
                if (read <= 0) break
                offset += read
            }
            if (offset < expected) return@use buffer.copyOf(offset)
            if (input.read() == -1) return@use buffer
            // Bounded fallback if stream exceeds declared size
            ...
        }
        // Bounded streaming read when entry.size == -1
        ...
    }
}

4. Real-World On-Device Scan Latency

Over 99% of strings inside a DEX never trigger a security rule. Because DexParser avoids full AST/Java decompilation and uses a BooleanArray mask over matched string_ids—walking class_defs and code_item bytecode only when a rule actually hits—it skips most of the CPU work a traditional decompiler pays for. End-to-end scans complete in seconds directly on a mid-range phone:

Target Profile APK Size DEX / Classes Strings Total Time
OVAA benchmark (open source) 5.3 MB 9 DEX · 9,306 classes 80,984 13.08 s
Hybrid Cordova app 10.5 MB 1 DEX · 8,346 classes 56,958 5.63 s
Hardened 2FA authenticator 15.5 MB 3 DEX · 12,946 classes 87,567 7.88 s
Large Kotlin/Compose editor 62.9 MB 6 DEX · 51,719 classes 286,419 35.73 s

Most of the wall-clock time on 60+ MB multi-DEX APKs is spent inflating DEFLATED ZIP entries and decoding MUTF-8/UTF-16 string pools; binary manifest parsing and scoring take a few milliseconds.

5. Four False-Positive Traps

Naive static scanners flag every http:// literal, run entropy checks over DEX bytecode, and subtract flat points per match—driving almost every real production app to 0/100. Four design choices keep findings actionable:

5.1 Entropy only on config surfaces

EntropyScanner runs on resources.arsc, text assets, and <meta-data>—never raw DEX bytecode. Candidates must mix letters and digits, pass a Shannon entropy threshold (>= 3.5 bits/char, or >= 3.0 next to credential keywords/resource keys), and survive filters for paths, camelCase/snake_case/CONSTANT_CASE identifiers, RFC 4122 UUIDs, and 32/40/64-char hex digests.

5.2 Cleartext URL triage (CleartextUrlTriage)

XML namespaces and spec URLs (schemas.android.com, w3.org, dashif.org, crbug.com) are dropped completely. Known SDK/CDN domains are downgraded to INFO (LIBRARY), while the manifest package is reversed into domain candidates (br.com.acme.app → acme.com.br) so the app's own domain always overrides the allowlist.

5.3 R8 full-mode repackaging (ObfuscationAnalyzer)

R8 full mode repackages renamed classes into synthetic packages (a.a, l2.b) and leaves under L<appPackage>/ only what it cannot rename—manifest components and Room's generated _Impl. Measuring L<appPackage>/ alone reported 0/4 renamed (NONE) on our own release build. Taking the union of L<appPackage>/ and non-library classes restored the real signal (2832/3533 → OBFUSCATED). Native/IL2CPP APKs with zero app DEX classes are marked unassessable (INFO).

5.4 Dual scoring with geometric decay (HardeningScore)

Repeated hits of the same rule decay as 0.5^n (capping any single rule at 2x its weight). High findings are capped at 35 points and Medium at 15, while Critical (20 points each) stays uncapped. INFO, LIBRARY, THIRD_PARTY_LIB, and possibleFalsePositive findings cost 0 in the confirmed Hardening Score, while remaining visible at reduced weight in a parallel Hygiene Score.

Kotlincore/HardeningScore.kt
val seen = occurrences.getOrDefault(finding.id, 0)
val penalty = rawWeight.toDouble() * halfPow(seen) // 1.0, 0.5, 0.25, ...
occurrences[finding.id] = seen + 1
Live execution log scanning a 15-DEX APK on-device
Live scan log walking binary manifest, 15 classes*.dex files, and resources.arsc directly on-device.
Hardening Score, Hygiene Score, R8 obfuscation verdict, and App Info
Dual Hardening and Hygiene scores, R8 obfuscation verdict, manifest summary, and scan statistics.
Expanded finding with POSSIBLE FP badge, triage context, OWASP MASVS, and CWE
Expanded finding with POSSIBLE FP triage context, class attribution, MASVS-PLATFORM-2, and CWE-749.

6. Honest Limitations

On-device static analysis is a fast pre-release sanity check and defensive go/no-go triage tool, not a replacement for a full desktop security lab:

Want to run a quick pre-release check on your own Android builds? APK AppSec runs offline on Android 8.0+ with no root required.

View on Google Play →

More in the APK AppSec Engineering Series