Parsing Binary AXML, DEX, and ARSC On-Device in Pure Kotlin
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
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:
- Indie developers or small teams without a SAST pipeline who want a fast pre-release sanity check on their own APK.
- AppSec engineers, QA testers, or students who need 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-Minute 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:
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:
core/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)
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):
- Effective exported components: Flags both explicit exported="true" and the pre-API-31 implicit-export rule (an without exported="false").
- Permission checks: Accounts for permission, readPermission, and writePermission on providers.
- Launcher detection: Requires both ACTION_MAIN and CATEGORY_LAUNCHER inside the same .
- meta-data pairs: Extracted and fed into the configuration secret scanner alongside resources and text assets.
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):
- Decodes up to 250,000 strings (max 4,096 chars each) while preserving a 1:1 IntArray back to each raw DEX string_id.
- Collects L...; class descriptors from type_ids for obfuscation analysis.
- 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 greater than 10% non-printable bytes in the first 4 KB)βeliminating the flood of false positives from Unity/IL2CPP data bundles.
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:
- Exact-sized bounded reads (readEntryBytesBounded): When ZipEntry.size is known and below the per-surface cap (64 MB DEX, 32 MB ARSC, 8 MB manifest, 2 MB asset), it allocates one exact ByteArray and reads straight into itβzero buffer doubling and zero trailing copy.
- DEX-by-DEX streaming (scanDexStreaming): Parses one classes*.dex at a time, runs regex rules and bytecode attribution against the same in-memory ByteArray (eliminating double ZIP reads), retains only findings, class descriptors, and counts, and releases the bytes and string pool before reading the next DEX.
// core/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
...
}
}
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.
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:
- Entropy only on config surfaces EntropyScanner runs on resources.arsc, text assets, and β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.
- 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.
- R8 full-mode repackaging (ObfuscationAnalyzer) R8 full mode repackages renamed classes into synthetic packages (a.a, l2.b) and leaves under L/ only what it cannot renameβmanifest components and Room's generated _Impl. Measuring L/ alone reported 0/4 renamed (NONE) on our own release build. Taking the union of L/ and non-library classes restored the real signal (2832/3533 β OBFUSCATED). Native/IL2CPP APKs with zero app DEX classes are marked unassessable (INFO).
- 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.
// core/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
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:
No dynamic analysis: It does not hook runtime execution, inspect live TLS traffic, or test certificate pinning (use Frida, Objection, or mitmproxy).
No full decompilation or taint analysis: Bytecode attribution locates the class and method referencing a matched string, but cannot prove whether a SQL query (CWE-89) concatenates untrusted user input or whether a Google AIza... key is restricted by SHA-1 in GCP Console.
No native binary reversing: ELF .so binaries (C/C++, Rust, Unity IL2CPP) are not disassembled.
Packers and string encryption: Commercial obfuscators that encrypt string literals hide them from static string tables.
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.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.