Skip to content

Static Analysis

Sam MG Harish edited this page Oct 30, 2026 · 4 revisions

Static analysis (phase 1)

Phase 1 turns an APK into findings, each tied to a file and line range in a decompiled or extracted artifact.

Five frameworks have an analyzer: Java/Kotlin (JADX), Flutter (Blutter for release builds, kernel-source recovery for debug builds, plus JADX for the platform layer), React Native (a built-in Metro splitter for plain bundles, hermes-decomp for Hermes bytecode, plus JADX for the platform layer), Cordova (asset extraction), Xamarin/.NET MAUI (assembly recovery + optional ILSpy). All share the same scanners, agent engine and enrichment; only the route from APK to readable tree differs. Native .so libraries in any of them can be decompiled to C with headless Ghidra when it is configured (Native libraries). Kony, LibGDX, Unity and Unreal stay detection-only.

Pipeline order

detect → dispatch → preflight → decompile/extract
      → deterministic scanners (SAST)          ← Java/Kotlin only: runs BEFORE the agent
      → leads worklist from SAST findings      ← Java/Kotlin only
      → code graph: ownership → class map → call graph
      → partition call graph into regions
      → one agent per region, in parallel, budgeted
      → file review: every flagged app file once, one request per part
      → deterministic scanners (SAST)          ← every other framework: runs AFTER the review
      → merge + dedupe → (Flutter: pool citations moved to code) → code-context enrichment

Two layers produce findings:

Layer Reads Property
Deterministic scanners Manifest, WebView setup, network config, shipped strings, Semgrep rules Always runs, always complete, ~15 s
Agents The code, navigated with read tools Selective; bounded by steps and wall clock
File review Every flagged app-owned file, shown whole Exhaustive over the agent's assignment; bounded by max_review_parts

On Java/Kotlin the scanners run first so their hits become a worklist the agents verify, rather than the agents searching open-endedly. Flutter, React Native, Cordova and Xamarin run them after the agents and the file review, so those agents get no leads; the review's checklist covers the same ground there. Either way the outputs are merged and the agent version wins on a duplicate (richer description).

1. Detection and dispatch

MobileSecurityDetector.detect() (detection/detector.py) returns a DetectionResult from two things:

  • HybridFrameworkDetector.detect_all_frameworks(): twelve detectors (Java, Kotlin, Flutter, React Native, Native, Cordova, Xamarin, Unity, Unreal, LibGDX, Kony, plus a zip-entry detector driven by TECH_DETECTION_MAP in config/constants.py). Each returns framework, confidence 0–1, matched indicators. Highest confidence wins. On failure, the five core detectors run individually and results at confidence ≥ 0.3 are kept.
  • BasicInfoExtractor.extract_basic_info(): package name, app name, version name/code, min/target SDK, file size, component lists (androguard).

Indicators are mostly APK path signatures: libflutter.so + assets/flutter_assets/; libreactnativejni.so + assets/index.android.bundle + libhermes.so.

Registry

analyzers/registry.py maps a lowercased framework name to an analyzer class:

Names Analyzer
java, kotlin, generic, unknown, native (c/c++) JavaKotlinAnalyzer
flutter FlutterAnalyzer
react native, expo ReactNativeAnalyzer
cordova CordovaAnalyzer
xamarin, maui, .net maui XamarinAnalyzer

Anything else is in AnalysisService.UNSUPPORTED_FRAMEWORKS (kony, kony visualizer, libgdx, unity, unreal) and gets a detection-only result.

BaseAnalyzer.preflight() then checks the framework's external tool. False degrades to the same detection-only shape, with the missing setting named in analysis.error. analysis.decompilation_status is Unsupported Framework or Tool Not Configured. Framework detection, app info, components and a report are still produced.

2. Source profiles

A SourceProfile (analyzers/agent/profiles.py) tells the shared machinery what app code looks like in a given artifact tree.

Profile Source extensions Noise filtered Orientation file
JAVA_KOTLIN .java, .kt androidx/, android/, kotlin/, com/google/, resource-qualifier and support-library paths AndroidManifest.xml
FLUTTER .asm, .s, .S, .dis, .dart, .java, .kt dart/, flutter/, package:flutter/, sdk/, plus the Java/Kotlin framework paths of the platform layer flutter_scan_overview.txt (written by the analyzer), else pp.txt
REACT_NATIVE .js, .jsx, .ts, .tsx, .java, .kt framework_modules/, node_modules/, metro-, regenerator, com/facebook/, plus the Java/Kotlin framework paths of the platform layer rn_scan_overview.txt (written by the analyzer), else package-metadata.json
CORDOVA .js, .html, .htm cordova.js, cordova_plugins.js, cordova-js-src/, jQuery/Angular/Bootstrap config.xml
XAMARIN .cs, .txt System., Microsoft., Mono., Xamarin.Forms, netstandard, mscorlib assemblies.txt (written by the analyzer)

AgentTools(root, profile=…) (analyzers/agent/tools.py) reads extensions, noise fragments and orientation candidates from the profile. read_file never filters by extension, so a graph node always resolves.

BaseAnalyzer (analyzers/base.py) provides preflight(), analyze(), run_agent() and enrich_vulnerabilities(). resolve_source_path tries the path as given, then each source_prefixes() entry (JADX's sources/resources split), then a basename search.

3. Deterministic scanners (SAST)

analyzers/sast/ (runner.py) runs pure-Python extractors plus Semgrep over the artifact tree. Each scanner is wrapped separately, so one raising costs only its own findings.

Scanner Reads Emits
manifest AndroidManifest.xml debuggable, allowBackup, cleartext, network security config, targetSdk/minSdk behaviour, dangerous and weakly-protected custom permissions, exported components, deep-link schemes. An activity exported only as the launcher entry (MAIN/LAUNCHER, no other action or scheme) is not reported: every app has one, and what it does with its Intent is left to the agent and the review pass. An activity reached only by BROWSABLE VIEW links (and possibly as the launcher) is listed as an Informational PLATFORM-02 deep-link entry instead of "no permission protection": it is public by design, and any flaw is in its handler. Each finding is placed on the manifest line it is about (_attach_lines): a component on its android:name, an app-wide setting on its attribute, or on the <application> element when the point is that an attribute is missing; every manifest finding used to cite line 0 and show no XML. The backup and network notes are worded for the declared target: with no network security config, targetSdk 28 and above blocks cleartext and trusts only system CAs, below it cleartext is still permitted; backup below targetSdk 31, or on a debuggable build, means adb backup over USB without root, while from 31 the data goes into cloud and device-transfer backups and Android 12 and later leave it out of adb backup. Both notes name the target SDK, so their anchors are tried before the SDK ones; the backup note once cited targetSdkVersion. The title is searched before the description, which mentions other settings in passing: the minSdkVersion note was placed on <application> because its description named the network security config, and the claim gate then refuted it. Exported components are filed under OWASP M8 (Security Misconfiguration), as their class is
webview Decompiled Java WebView settings (file, content and universal access as PLATFORM-05; JavaScript enabled as PLATFORM-06, the class its wording infers, which once kept it apart from an agent's copy of the same line), taint from Intent extras into loadUrl, a URL typed into a text field loaded with no scheme check (PLATFORM-06, Medium: file:// opens the app's private files), @JavascriptInterface bridge classes, onReceivedSslError overrides; onReceivedHttpAuthRequest() calling handler.proceed(user, pass) without comparing the host argument (Medium PLATFORM-06); and an overridden shouldOverrideUrlLoading()/shouldInterceptRequest() whose body is only logging and the default return (Informational PLATFORM-06), the hook in place with the check left out - not overriding is not reported; and a file that loads a URL from the Intent into a WebView without ever calling setAcceptCookie(false) gets a Low PLATFORM-06 note that the page shares the app's cookie store (cookie tossing or session fixation)
network-config res/xml/ cleartext per domain, user CA trust (NETWORK-05, Medium with AV:N/AC:H/PR:N/UI:R/… since the attacker has to get a CA installed first; held as a chain step by WEAK-13, like cleartext permitted by configuration; the manifest scanner files the targetSdk < 24 default the same way), debug-overrides, missing pin-set
tls Decompiled Java trust-all TrustManager, empty checkServerTrusted, always-true HostnameVerifier, pinning disabled by flag, and the two SSLCertificateSocketFactory uses Android Lint flags: getInsecure(), and createSocket() given an InetAddress (by a variable declared as one, or an InetAddress factory call), which leaves the factory no hostname to check; and a plain java.net.Socket in a file that never layers TLS over it (no createSocket, SSLSocket or SSLEngine), filed as NETWORK-02 cleartext. Ghera plants all three, and its scans reported only the other TLS flaws in the same apps
injection Decompiled Java SQL by concatenation, escalated to Critical inside a ContentProvider; input from outside the app is High, and so is the app's own text-field input reaching a read (the device's user can pull rows the screen hides), but text-field input reaching a statement that only writes is Low (ui-write: the user can change nothing the app does not already let them). The statement is judged by its riskiest variable operand, not its first: "UPDATE " + Table.TABLE_NAME + " SET v = '" + this.value + "'" is a value in quotes, not a table name. UPPER_CASE names and locals assigned only literals or arrays of them count as constants, a statement made only of constants is not reported, and this.field is traced as field. A selection clause is read even when it opens with a column name (selection = projection[0] + " = " + name). A method parameter is followed to the calls in the same file, two hops at most, and counts as constant only when every caller passes a constant. Runtime.exec and DexClassLoader/PathClassLoader graded by their input: a command made only of string literals and constant names is not reported (root checks run getprop and which su this way), a runtime-built command is Medium only in a file that reads an Intent, a deep link, a JavaScript bridge or a broadcast, and class loading is Medium only beside external storage or a download with no signature or digest check in the file (getCertificates, Signature, MessageDigest); otherwise each is a low-confidence lead the confidence gate turns into a note. A biometric prompt with no CryptoObject is reported only where the file shows a prompt (constructs one or calls authenticate), so androidx's availability checks are not. A command-execution hit's title names its file ("Runtime.exec() invocation in shellEx.java"), so two hits in one plugin are not two cards with one title
secrets Every source file Typed secret patterns and endpoints, downgraded for keys in known config files. A private (RFC 1918) address is an Informational SECRET-03 note, not a credential, and its title names the address; the pattern takes all four parts of a 10.x address (it once matched "10.0.2" of 10.0.2.2)
flutter-build The recovered Flutter tree One BUILD-01 finding when the app shipped as a debug build carrying its full Dart source
dart-tls The app's own Dart (Blutter disassembly or recovered source) A badCertificateCallback that always returns true. In a release build the setter's name does not survive: (cert, host, port) => true compiles to Dart's shared Object::_simpleInstanceOfTrue closure stored into the _HttpClient the same function built, and that pair is what is matched. Only the app's own packages are read
sdk-inventory Package layout 28 SDK signatures with versions; debug SDKs (Flipper, Stetho, LeakCanary, Hyperion) in a release build. A cross-platform framework (Flutter, React Native, Cordova, Xamarin) is the app's own runtime and is left out of the third-party list; a Flutter app's note once read "1 third-party SDK embedded: Flutter"
crypto-misuse The app's own Java A SecretKeySpec or IvParameterSpec built from a literal, a zero-filled array or a literal constant (CRYPTO-02) - an empty new byte[16] stays zero-filled only until its file writes into it, so one filled by nextBytes, read, readFully, get, System.arraycopy or an element assignment is a random or loaded key, not a fixed one (Ghera's fixed constant-key app fills its key from SecureRandom and was reported as hardcoded), and a PBEKeySpec with fewer than 10,000 iterations (CRYPTO-01). A key from a variable the rule cannot resolve is left to the agent; and a PBEKeySpec salt fixed in the app - a literal, a constant or a string resource (R.string, getString) - followed one call up when it is the enclosing method's parameter, by matching the method's calls in the app's code (Medium CRYPTO-02)
platform-misuse The app's own Java Each risky call paired with the guard that makes it safe: a ZIP entry name used to build an output file with no canonical-path check (Zip Slip, CODE-04); ObjectInputStream.readObject (CODE-03); isValidFragment returning true (PLATFORM-02); Intent.parseUri launched without clearing component and selector (PLATFORM-03); setWebContentsDebuggingEnabled(true) outside a debug check (PLATFORM-06); ClipData.newPlainText beside a password, token, PIN, OTP or card name (STORAGE-02); and permission checks that test the app instead of its caller (PLATFORM-01, Medium): check/enforceCallingOrSelf[Uri]Permission, which passes whenever the app itself holds the permission, and check/enforcePermission given Binder.getCallingPid() in onStartCommand, onHandleIntent, onReceive or another callback a component is started through, where there is no binder transaction and the pid is the app's own. An AIDL method's check, and checkPermission(perm, Process.myPid(), Process.myUid()) (how an app asks about itself), are not reported. Four Ghera benchmarks plant these; the agents reported the exported service and blamed a normal-level permission, or nothing; an ordered broadcast's result read in onReceive() (getResultData()/getResultExtras(), Low PLATFORM-02), which any higher-priority receiver can rewrite; a file that locates a file on shared external storage and reads files (Informational STORAGE-02, the file being the unit because the read is usually a helper); and an implicit Intent on an app-defined action (not android.*) carrying extras into startActivity/startService with no package, component or class set within the next lines (Low PLATFORM-07); and a PendingIntent.get*() without FLAG_IMMUTABLE around a base Intent that names no component - empty, an action alone, or a variable built that way in the preceding lines with no setComponent/setClass/setClassName/setPackage (High PLATFORM-08), as Android's PendingIntent guidance defines it. Ghera's fix for its empty-base benchmark adds only an action, which is still implicit by that definition and is reported; and an exported provider guarded by a separate readPermission or writePermission but no overall android:permission whose call() writes files or data with no caller check of its own (Medium PLATFORM-01): Android checks only read access for call(), so the write permission does not cover it. The provider list comes from the decoded manifest; and permission re-delegation: an exported component with no permission whose own code uses an API that a permission the app requests guards - sending SMS, placing a call, the camera, the microphone, location, contacts, SMS or phone-state reads, the keyguard, a wake lock (PLATFORM-01, severity by permission, CWE-441), since Android checks the permission against the app, not the caller. Components come from the decoded manifest (merged library manifests included), and an activity exported only as the launcher entry is left out, since opening it does what the user's taps do
oauth The app's Java, React Native app modules, recovered Dart source The implicit grant (response_type=token), the password grant, and PKCE with code_challenge_method=plain (AUTH-01), in query-string or key-value form
credential-storage The app's own Java A credential written in plain text, one finding per file and sink: putString with a password/PIN/token key or value, in a file that uses SharedPreferences and with a non-null value (STORAGE-01; Bundle and Intent extras share the method name), an execSQL INSERT/UPDATE whose values come from credential-named identifiers (STORAGE-01), a write into a file made by createTempFile (STORAGE-01) or on external storage (STORAGE-02). Sensitivity is read from the identifiers written, split on camel case, with string literals removed; schema statements and literal seed rows are skipped
hardcoded-check The app's own Java A text field's getText().toString() compared with equals against a literal of six or more characters with no spaces - the app deciding locally that this exact value is the secret (AUTH-04)
screen-capture All decompiled code outside the framework embeddings One Informational PLATFORM-12 note (screen contents not protected from capture, WEAK-14) when nothing sets FLAG_SECURE - by name, as addFlags(8192)/setFlags(8192, …), or through a common Flutter or React Native screenshot plugin. React Native's Modal, which only copies the flag from its parent window, does not count
script-rules React Native app_modules/, the Flutter app's own Blutter disassembly The app logic those frameworks keep outside Java. JavaScript: setItem under a credential-named key without an encrypting store (STORAGE-01), console.* logging credential-named values (SECRET-02), new Function/eval on a non-literal (CODE-02), AES.encrypt/decrypt with a literal key or one assigned from a literal (CRYPTO-02), a WebView onMessage handler that never reads nativeEvent.url (PLATFORM-04), allowUniversalAccessFromFileURLs / allowFileAccessFromFileURLs (PLATFORM-05), originWhitelist={["*"]} / mixedContentMode="always" (PLATFORM-06). Dart, matched on the disassembly digest: a SharedPreferences setter whose key literal names a credential (STORAGE-01), print/debugPrint after a credential-named literal (SECRET-02), an SQL literal interpolated into rawQuery/execute (CODE-01), Key/IV built from a literal (CRYPTO-02, citing the literal's own row rather than the call after it, and saying "an" for an IV), a hash call followed by a hex-digest literal (AUTH-04). a pinned SecurityContext whose exception handler then builds a plain HttpClient - pinning that fails open (NETWORK-03, Low); pinning in the app's own code (HttpCertificatePinning.check, CertificatePinningInterceptor, SecureHttpClient.build, SecurityContext.setTrustedCertificates…), noted once per file at Informational (BUILD-04) as the client-side control it is. Both: an http:// endpoint used for a request, with namespace, loopback and private hosts left out (NETWORK-02)
signature-derived-key Decompiled Java The app's own APK signing certificate (getPackageInfo(..., GET_SIGNATURES), signatures[0], toCharsString()) read alongside an HMAC/cipher/native call in the same file - a certificate anyone holding the APK can extract, standing in for a secret
semgrep Decompiled Java The bundled Android rules

signature-derived-key only fires when both shapes are in the same file; reading the certificate on its own to check the app has not been re-signed (the common, safe case) is not reported. extractors/signature_derived_key.py.

Per-profile selection (runner._BY_PROFILE):

Profile Scanners
java_kotlin every scanner except flutter-build, dart-tls and script-rules
flutter manifest, secrets, flutter-build, dart-tls, webview, tls, injection, crypto-misuse, platform-misuse, oauth, credential-storage, hardcoded-check, script-rules, screen-capture, sdk-inventory
react_native manifest, secrets, webview, tls, injection, crypto-misuse, platform-misuse, oauth, credential-storage, hardcoded-check, script-rules, screen-capture, sdk-inventory
cordova, xamarin manifest, secrets
unknown key manifest, secrets (never nothing)

A rule finding that names no CWE or OWASP category gets its class's from the catalogue (to_scan_finding), as an agent finding does, so two findings of one class never show different labels; one that names its own keeps it.

For Flutter and React Native, a rule hit in the platform layer's third-party plugin code is a dependency note, not the app's flaw: any finding under platform/sources/ in a readable package outside the app's own packages (the manifest package and each launcher activity's package, from manifest.app_code_packages) is capped at Low, its CVSS vector cleared so the cap survives, and its description says which plugin it is in - also when the hit was already Low, since a published Runtime.exec() hit inside a root-detection plugin read as the app's own code. R8-obfuscated paths are left alone, since the app's own classes are hidden the same way. runner.demote_plugin_findings.

Flutter and React Native run the Java rules because their analysis roots carry the JADX-decompiled platform layer under platform/, where WebView, TLS and injection issues are written in Java like any app. network-config is left out of Flutter because Dart networking ignores network_security_config.

Task affinity (PLATFORM-09): an activity with a foreign affinity, or an application affinity other than the package, is Medium. The default affinity, the package name, is what the StrandHogg attack claims (another app gives its activity this app's package as its affinity and lands in this app's task); Android 11 (API 30) fixed that in the OS, so when minSdkVersion is below 30, or undeclared, and the application has not set android:taskAffinity="", an Informational note "Task hijacking (StrandHogg) possible on Android 10 and lower" says so. The empty affinity only partly mitigates it, since the later runtime variant does not depend on the manifest; see Android's guidance. Two Ghera benchmarks plant this default. The app-level recommendation used to say "leave taskAffinity unset so it defaults to the package name", which is the default the attack claims.

An exported component guarded by a permission the app never declares, and the platform does not define (android., com.android., com.google.android.), is reported as unguarded (Medium, High for a service or provider): whichever app declares a permission first owns it, so any app can declare that one and hold it. A custom permission the app declares at a weak level (or with no level, which defaults to normal) is graded by what holding it takes: normal is Medium, since any app that lists it in its manifest is granted it at install without the user being asked; dangerous is Low, since any app gets it once the user accepts one prompt.

A custom permission the app declares (PLATFORM-01) is graded by who can get it. At normal level it is Medium: any app that lists it in its manifest is granted it at install, without the user being asked. At dangerous level it is Low: the user has to accept a prompt first. Signature level is not reported.

The manifest scanner also reports android:testOnly (BUILD-01) and FileProvider path files that share the whole filesystem (root-path) or a whole files/cache directory (PLATFORM-11), read from the decoded res/xml/ beside the manifest.

Every Java-reading scanner skips bundled library and framework paths (androidx/, kotlin/, okhttp3/, okio/, retrofit2/, com/facebook/react/, io/flutter/ and similar): a defect inside a library is not the app owner's to fix. Two real false positives drove this: OkHttp's internal hostname verifier reported as the app accepting every hostname, and React Native's own Runtime.exec of getprop reported as the app's command execution. secrets also skips the scan overviews this tool writes at the analysis root, which quote the app's leads and would report each a second time.

The tls rules understand Kotlin as JADX renders it. An empty checkServerTrusted still carries Intrinsics.checkNotNullParameter calls, so a body of nothing but null checks counts as empty. A hostname-verifier lambda compiles to a static method with a $lambda$ name taking (String, SSLSession), which verify() merely delegates to, so any boolean method taking an SSLSession that returns true counts as the verifier. A real trust-all OkHttpClientFactory written in Kotlin was missed entirely before this.

apk_path is threaded through so the manifest scanner can decode AndroidManifest.xml straight from the APK with androguard. Non-Java source roots have no plain-XML manifest.

Two regexes carry comments about traps that failed silently:

  • WebView taint matches its argument with [^;]*?, not [^)]*. Taint arrives nested (loadUrl(getIntent().getStringExtra("u"))) and a class excluding ) stops at the inner paren.
  • The SQL rule writes literals as "[^"]*". SQL contains apostrophes (WHERE name='), so [^"']* stops at the first one.

Semgrep

An optional extra, pip install "lu77U-MobileSec[semgrep]" (semgrep>=1.100.0), or any semgrep on PATH; it is not a base dependency because its pinned dependencies carry known vulnerabilities (see Installation). Without it this pass is skipped and the other scanners run as usual. Invoked as:

semgrep scan --json --quiet --config <bundled rules> --metrics off --no-git-ignore --timeout 30

--metrics off keeps client app data off a third party. Every failure path (missing, wrong version, sandboxed, hung) degrades to an empty list.

Bundled rules live in rules/semgrep/android/mobile.yml, each carrying metadata.vuln_class and where relevant metadata.chain_tag:

Rule id vuln_class chain_tag
webview.loadurl-from-intent PLATFORM-02 deeplink_to_webview
webview.js-interface-added PLATFORM-04 js_bridge
webview.universal-file-access PLATFORM-05 webview_file_access
intent.redirect PLATFORM-03 —
ssl.bypass-handler-proceed NETWORK-01 —
crypto.weak-algorithm CRYPTO-01 —
pendingintent.mutable-implicit PLATFORM-08 —
storage.world-accessible-prefs STORAGE-01 —

Leads

analyzers/agent/leads.py turns SAST findings into a worklist the agent confirms or refutes.

Constant Value Meaning
MAX_LEADS 120 Total leads carried into the agent phase
MAX_LEADS_PER_REGION 24 Leads rendered in one region's slice

Leads are ranked by severity, routed to the region that owns the lead's file (exact path, else a basename with exactly one owner), and unowned leads (manifest facts, res/xml/) go to whichever region currently holds the fewest. Nothing is dropped before the per-region cap. Each lead carries a scanner-specific instruction: what to check to turn "the construct is present" into "the value is exploitable".

With leads present the region's mission becomes verify first, explore second. With none, the prompt is byte-identical to the pre-leads version, which is what every non-Java framework still gets.

4. Code graph

Three layers, built before the agent starts.

Ownership

analyzers/agent/ownership.py decides which DEX classes are the app's own code. Package-prefix matching fails on obfuscated release builds, so ownership propagates over inbound class references:

  1. Seed. Packages holding a class under the application id or a manifest-declared component → app. Packages matching the framework list → framework. Packages matching the SDK tables → vendor.
  2. Propagate. An undecided package whose callers are mostly app packages → app; decisively vendor callers → vendor. Repeat to convergence.
  3. Exclude the rest. A package nothing internal calls has no evidence either way and is left out of the graph.

classify_packages(dx, package, manifest_components) returns {"owner": {pkg: app|vendor|framework}, "stats": {…}}. Stats reach the report as agent_coverage.scope (app_classes, vendor_classes, framework_classes, undecided_classes, packages, synthetic_classes_skipped, plus source_checked / source_missing / source_repaired).

Source resolution runs alongside: obfuscated class names that differ only by letter case cannot coexist on a case-insensitive filesystem, so some classes have no file in the decompiled tree. Those stay in the call graph (callers and callees remain correct) but cannot be read, and the count is reported (see Coverage).

Class map

CodeNode / CodeGraph (analyzers/agent/code_graph.py) hold the containers, render() / flagged_files() / node_for_file(), and the shared secret regex. Each framework builds nodes its own way (see the per-framework sections).

A node is flagged, meaning the agent should read it before finishing, when it is exported, carries any sink signal, has hardcoded strings, or has a role that is always flagged (ALWAYS_FLAGGED_ROLES): native-bridge, app-code, app-entry, platform-channel-handler (Flutter) and native-module (React Native). The app-code roles exist because a cross-platform app's own logic often matches no sink pattern at all: a screen gating a feature on a client-side flag, or a module holding a key.

CodeGraph.render() caps at 120 entries.

Call graph

analyzers/agent/call_graph.py builds a directed method-level caller → callee graph, scoped to the ownership-decided app classes. Calls that leave the app are not edges; the security-relevant ones are recorded on the node as sinks, so rawQuery stays visible without android.database joining the graph.

The graph is never rendered into the prompt. It is reached through tools:

Limit Value
MAX_NEIGHBOURS 40
MAX_PATH_DEPTH 12
MAX_PATHS 5
MAX_MATCHES 40

build_call_graph(dx, app_descriptors, class_roles) returns None on any failure; the agent then works from text search alone.

5. Region partitioning

analyzers/agent/partition.py splits the call graph into disjoint regions, one per agent. This replaced category-based (attack-surface) partitioning, which read shared classes twice and split a deep-link → WebView chain across two agents.

The algorithm is a Voronoi partition on the call graph:

  1. Seeds. Entry points, best first: exported + intent filter, then exported, then intent filter, then the rest. Ties break on SAST hit weight for that node's file, then len(signals), then node key (so the partition is byte-identical on every run). Apps declaring no reachable components fall back to the most sink-heavy classes.
  2. Grow. Multi-source BFS over undirected adjacency; every node goes to the entry point that reaches it in fewest hops. Smaller regions claim first at each depth.
  3. Rebalance. If largest/smallest exceeds BALANCE_RATIO, re-grow claiming one node at a time from whichever region is currently smallest, weighted by SAST hits rather than raw class count.
  4. Cap and merge. Regions above the node cap are split; regions below the floor are merged into a neighbour.
Constant Value
MAX_REGION_NODES 110
MIN_REGION_NODES 8
MAX_REGIONS 8
BALANCE_RATIO 2.0

A Region carries key, members, seeds and families (sink families present, commonest first).

Region guidance

analyzers/agent/surfaces.py still defines the five Android attack surfaces, but they now supply guidance rather than the partition. guidance_for_families(families) maps a region's sink families to up to three surfaces and returns their objectives plus the skills to preload.

Surface Node roles / sink families Objective
component_exposure exported-*, ipc What can an unprivileged third-party app invoke, and what does it get? (preloads android_ipc_ui_attacks)
deeplinks_intents ipc, uri, nodes with intent filters Where does Intent and deep-link data end up? (preloads deeplink_clipboard_trust and deeplink_endpoint_analysis)
storage prefs, sql, storage What is written at rest, and what is in it? (preloads storage_crypto_review)
network_webview webview, js_bridge What does each WebView load, and what is bound into it?
native_secrets native, native-call, crypto, logging, nodes with strings, plus native libraries What secrets and broken primitives are in the app and its native code?

Native libraries are not in the call graph, so no region owns them; _assign_native_libs distributes them round-robin.

6. Budgets

Three independent ceilings, configurable in Settings (agent_budget, see Configuration). 0 in any field means unbounded.

Setting Default Scope
max_steps_per_region 40 Per region, one LLM call per step
max_minutes 45 Wall clock across the whole fan-out (regions run in parallel, so they share the clock)
max_review_parts 40 Requests the file review may make after the agents; the lowest-priority parts are dropped first

allocate_steps splits the step budget proportionally to region size, with a floor so no region gets too few turns to do anything. max_steps=None maps every region to None.

In analyzers/agent/budget.py, Deadline is a drop-in replacement for a bare time.monotonic() float, registered with BaseAIProvider.add_throttle_observer. Every throttle credits its blocked seconds back to the clock, so a provider outage is not charged to the user's coverage budget. Credit is capped at MAX_CREDIT_FRACTION = 0.5 of the original budget. deadline.close() is called when the fan-out ends so later throttles (validation, chain building) cannot extend a finished budget. run_agent_analysis still accepts a plain float, so every other caller is unaffected.

7. Coverage reporting

Every analyzer returns agent_coverage, and the HTML report renders it as a notice at the top when the phase did not finish.

{
  "regions": [{"key": "...", "nodes": 110, "steps": 29, "files_read": 41,
               "stop_reason": "budget_time", "findings": 6}],
  "complete": false,
  "regions_incomplete": 1,
  "regions_total": 2,
  "degraded_reason": "the scan's time budget was reached",
  "leads": {"total": 66, "routed": 48, "unowned": 4, "per_region": {"...": 24}},
  "scope": {"app_classes": 552, "source_checked": 552, "source_missing": 12, "...": "..."},
  "file_review": {"files": 19, "parts": 2, "parts_skipped": 0, "parts_failed": 0, "findings": 17}
}

stop_reason values:

Value Meaning
reported The model submitted a report. The only value that counts as complete
budget_steps Per-region step budget exhausted; a final report was forced
budget_time Wall-clock budget reached
provider_error / provider_unavailable The provider failed or its circuit opened. A single failed turn while the provider is still serving (typically a reply the model reasoned past its output cap) does not end the region: the loop notes the lost reply, asks for one short action and carries on; a third consecutive failure (_MAX_FAILED_TURNS = 2 tolerated) or an unavailable provider ends it
unparseable Output could not be parsed into an action
cancelled Scan stopped
failed The region's worker raised

degraded_reason prefers the provider's own unavailable message, then budget_time, then budget_steps, then a generic "one or more regions did not finish".

Two report notices come from this block: Incomplete analysis (the AI phase stopped early) and Incomplete source (classes the decompiler never emitted). They are separate because one is about the model's budget and the other about the input.

8. Agent loop

run_agent_analysis() (analyzers/agent/agent_loop.py) drives one region. It stops on report, an exhausted step or time budget, a provider failure, or cancellation. Cancellation is polled every turn.

Each turn sends a system prompt plus a user prompt of three parts:

  1. Initial context, re-sent verbatim every turn, never truncated: detected framework; the region's objective and (when present) its leads worklist; the orientation file capped at 6000 characters; then the code map, capped at 120 entries and 20000 characters (CodeGraph.render). With a graph, the flat file tree is replaced by the map plus a short list of resources the graph doesn't cover (app_resource_files(), driven by profile.resource_globs, capped at 150 entries).
  2. Rolling transcript. Entry-level compaction with hysteresis, not a sliding character window: entries append for free until the rendered transcript would exceed 60000 characters, then whole oldest entries (never split mid-entry) are dropped down to 35000 characters, with a … [N earlier turns dropped] stub. Between compactions the prefix handed to the model (initial_context immediately followed by the transcript's start) is byte-identical turn to turn, which a sliding window (the old _truncate_tail, which shifted by roughly one entry's length every turn) could never give a provider's prefix cache to hold onto. transcript itself is never trimmed; only what's rendered into the prompt is, so checkpointing, the salvage path and a forced final report always see every turn.
  3. Coverage note, only once turns have been dropped: the files already examined and the flagged files not yet examined (each list bounded at 1500 characters with a count), or a line saying every flagged file has been examined. Compaction drops the only record the agent had of which files it opened; without this note a real React Native scan dropped 221 turns and re-read the same handful of files for over 300 steps without reporting. With it, the same scan finished on its own in 67.
  4. Steps remaining (omitted when unbounded).

The reply is one JSON object matching NEXT_ACTION_SCHEMA. The system prompt and core skill are resolved fresh every call from profile.key, so a prompt override saved in Settings applies to the next scan with no restart.

On a provider that can hold this region's conversation as a live CLI session (provider.has_session(region_key), see AI providers), turns after the first send none of the above: only the newest transcript entry, since the session itself already has everything from prior turns.

Tools

Action Arguments Behaviour
list_files path Immediate children with sizes, capped at 200
read_file path or paths, optional start_line File text with a 1-based line gutter, up to 12000 characters. A single line over 2000 characters is cut with a note (minified bundles carry lines of 100 000+)
search_code pattern, optional path Case-insensitive regex over the profile's source extensions, file:line: match, stops at 60. With an explicit path it also covers resource files such as the manifest. An invalid regex is retried as a literal
inspect_native path to a .so, optional start_line Security signals, then Ghidra's decompiled C (JNI entry points first) when Ghidra is configured, then the symbol table; paged like read_file. Without Ghidra: signals and objdump -T symbols, one page
find_method method Resolves a bare, qualified or full-key name to app methods
callers method One hop back
callees method One hop forward
call_path method (source), target Whether and how a sink is reachable from an entry point
entry_points — Attacker-reachable methods to start from. Flutter and React Native have no call graph, so they get files instead: the main() library, the platform-channel calls and exported components (Flutter); module 0, the root component and the native modules (React Native)
add_finding vulnerabilities Records confirmed findings without ending the loop
report vulnerabilities Merges final findings and ends the loop

Division of labour: text search locates, the call graph explains. A shared helper can have 100+ callers; call_path returns the one route that reaches it from the code under review.

Findings do not depend on the final report. add_finding accumulates server-side (deduplicated on title + file + line) and survives a forced final report and a mid-run provider error. Only cancellation discards them.

Details:

  • Paging. A file larger than one read budget is paged. Repeating read_file on the same path with no start_line continues after the last line shown; tracked in AgentTools._read_progress.
  • Batching. read_file with paths reads up to 8 files or 28000 characters in one step.
  • Sandboxing. Every path resolves against the artifact root and is rejected on escape. objdump output has the absolute host path replaced with the sandbox-relative one.
  • Noise filtering. An unscoped search_code skips the profile's noise fragments. An explicit path searches everything under it.

Native libraries (Ghidra)

With ghidra_path set (Configuration), inspect_native shows the library's decompiled C rather than only its symbols, which is what lets the agent follow a Java string from GetStringUTFChars into a strcpy or a comparison against a constant. decompiler/ghidra_runner.py:

  • On demand. Ghidra runs the first time the agent inspects a library, not eagerly after JADX: most libraries are third-party runtimes nobody needs decompiled. Runtime libraries (libflutter.so, libhermes.so, libreactnativejni.so, libmonosgen-2.0.so, libunity.so and others) are never decompiled.
  • Headless. analyzeHeadless with the bundled Java post-script ghidra_scripts/ExportNativeDecompilation.java, which exports the decompiled functions and their addresses as JSON. A Java GhidraScript runs in every Ghidra install; a Python one would need PyGhidra.
  • JNI annotation. Calls through the JNIEnv/JavaVM function tables ((*env + 0x548)) are annotated with the function name (GetStringUTFChars), computed for the library's pointer size.
  • Limits. 240 s of analysis, 240 s decompile budget, 30 s per function, at most 4000 functions, a 720 s process timeout (the whole process group is killed), libraries over 64 MB skipped. Runs are serialised (each is a JVM of a gigabyte or more) and cached in-process by content hash, failures included, so several regions inspecting one library pay once.
  • Without Ghidra, or when it cannot decompile a library, the output says why there is no code, so the agent does not present inferences as something it read.

A native finding's citation is repaired before enrichment (locate_native_citation): models often cite a function's entry address or a line past the end, so the function is found by address, then by name, and the span narrowed to the first call of an API the finding names (strcpy, strncmp). Its code context is the whole function, labelled as Ghidra pseudo-C, never as the developer's source.

Coverage and anti-loop control

  • A report while flagged files remain unread is rejected once, with a nudge listing up to 12 unread files and an example batched read. The second report is accepted.
  • Two consecutive identical action signatures, or a read past the end of an already-read file, append the same nudge and reset the counter.
  • After compaction, every turn carries the coverage note described above, so an agent whose history was trimmed still knows what it has read and what is left.

Parsing model output

  1. Thinking-token stripping. Paired <think>…</think> removed; a lone </think> means only text after the last one is kept.
  2. Fence stripping, then json.loads via utils/json_utils.py, which uses object_pairs_hook to keep the first populated value of a repeated key (stock json.loads keeps the last, which is usually a short restatement).
  3. Brace-counting extraction of the first balanced top-level object, string-aware.
  4. Report coercion. A bare array, or an object with vulnerabilities / findings / results and no action, is treated as a report.
  5. Salvage. Every balanced {…} containing exactly one "title" is extracted and its fields pulled with regex.

If the provider errors before a single valid action, completed_ok=False. Java/Kotlin then falls back to the legacy full-dump path; no other framework has a fallback.

Running out of steps

_force_final_report makes one more call with a system prompt permitting only a JSON array of findings: no tool calls, no prose.

File review

The agent decides what to read and when to stop, and a smaller model routinely stops after a handful of files - or reads one and never reports what was in it. A benchmark Flutter app's agent read three of six screens and reported two of ten known issues. After the agents finish, BaseAnalyzer._with_file_review runs analyzers/agent/file_review.py over the same assignment the agents were steered towards, so each flagged file is read once with nothing else competing for attention:

  • Native libraries the app's own code loads (the graph's native_libs) come first, rendered as the numbered view the agent's inspect_native gives - Ghidra pseudo-C with JNI entry points first, or the symbol and strings summary without Ghidra - bounded to 60,000 characters. A cited line resolves through the same native-context step as an agent's. They used to be left to the agent alone, and two benchmark scans lost every native finding when the agent stopped early or reported without opening the library. native_library_analysis is added to the skills only when a library is in the pass.
  • Files: the graph's flagged files plus every lead file, ordered lead files first, then entry points (any role other than plain class), then the rest. Native libraries and framework paths are excluded. For Flutter and React Native, platform-layer Java is reviewed only under the app's own package; the rest is plugin code, usually obfuscated.
  • Rendering: source is shown line by line with real line numbers (long lines cut at 800 characters). Blutter disassembly is shown as a digest (recovered.digest_disassembly): class and function declarations, string loads, booleans, named callbacks, constants and resolved calls, at their real line numbers - an order of magnitude shorter, with every literal and call kept. Mixin-application owners are cut to the mixin that defines the method. Review transcripts showed what a reader could not recover from calls alone, so the digest also keeps: the strings inside a loaded const object (Instance_HomePage {"FLAG{…}"}, from objs.txt - a secret in a const field was otherwise never in the request) or const list (const list of 4 objects {…}, followed from its pp.txt slot to the objects it lists - a developer menu's debug key and gateway secret sit in a const list of ListTiles), a run of integer stores as one int array row with its characters (an encoded flag built from char codes) and, when a constant shift or a one-byte XOR turns it into clearly better text, the decoding (decodes (minus 5) as "FLAG{…}": a lab flag stored shifted by five had two codes above printable ASCII, so it showed as bare numbers and went unreported; candidates are ranked by character class and English bigrams, and short or evenly spaced runs are left alone), xor with #N, an anonymous closure as closure -> line N <signature>, which calls … (a Duration parameter is marked as a frame callback - a deep-link screen that submitted a transfer from a post-frame callback in initState was read as only pre-filling a form), and return / catch: exception handler starts here (pinning that falls back to a default client in a catch block read as two unexplained clients).
  • Parts: small files share a request and large ones are split on line boundaries (PART_CHARS = 32,000, large enough that a small app's screens - a link handler and the screen it opens - share one request), greedy and in priority order, so the max_review_parts budget cuts from the end.
  • Checklist: the system prompt lists what to look for in the app's own logic - secrets (including encoded ones decoded at runtime and ones held in const objects), plain storage and logging of credentials, injection, WebView exposure, unguarded entry points and deep links (including a link handler that opens a screen which then acts on the link's parameters by itself, in initState, a post-frame callback or useEffect), client-side authorization, weak local authentication, cleartext and TLS, weak crypto, dynamic code, hidden debug screens, native memory handling, missing screenshot protection - plus client-side protections (root, emulator or debugger detection, integrity checks, pinning), reported once each at Informational as context. It also tells the model that the files of one request are one app and to follow a link handler into the screen it opens before deciding the link only fills in a form.
  • Requests: one per part, four at a time under the provider's own concurrency gate, with the framework overview or manifest summary (cut to 4,000 characters), a checklist system prompt, and the core, finding_quality, vulnerability_classes, business_logic_abuse, storage_crypto_review and deeplink_endpoint_analysis skills. No tools.
  • Findings: tagged agent_origin: "file_review", region_key: "file-review", region_files_read = the files the request showed. A citation by basename is mapped to the shown file; one naming a file the request did not show is marked cited_file_read: false, which the evidence gate caps. They are appended after the agent's findings and folded by the validation stage's deduplication.

The pass never removes anything: an unavailable provider skips it, a failed request costs its part (parts_failed), and any other error leaves the agent's findings as they were. Its telemetry is recorded under agent_coverage["file_review"] (files, parts, parts_skipped, parts_failed, findings).

9. Parallel execution

analyzers/agent/fanout.py runs one run_agent_analysis per region, in parallel. There is no sub-agent runtime: these are independent invocations sharing only the provider and the read-only source tree.

Four threading hazards are handled explicitly:

  1. contextvars do not cross threads. Verbose output reaches a scan's live log through the current_scan_id contextvar. Each worker starts under its own contextvars.copy_context(), one copy per thread, since a single Context may only be entered by one thread at a time.
  2. emit_progress is an unlocked read-modify-write of meta.json. Only the parent emits, holding a lock across the counter bump and the emit. Each completed region moves the bar within 64–82.
  3. Thread exceptions do not reach the parent. Each worker's exception is captured and re-raised on the parent after the join, with ScanCancelled taking priority over any partial result.
  4. Provider logs collide. OutputManager.get_llm_log_path builds a second-resolution filename; the worker's thread name (its region key) disambiguates it.

Fan-out is unlimited by design: all regions launch together, up to MAX_REGIONS. Combined with the job manager's two concurrent scans, that multiplies burst LLM load; per-provider concurrency is capped by max_concurrent_requests (see AI providers).

Duplicate findings are merged on (title, file, line), first occurrence winning, with the region recorded on the survivor. Transcripts are stitched with a ===== REGION: <key> ===== header each.

10. Resumable scans

web/checkpoint.py makes a scan resumable after Ctrl+C, a crash or a pause. Layout inside the scan folder:

checkpoint/progress.json        stage marker + cheap-to-lose facts
checkpoint/agent-<region>.json  one file per region worker

Stages, in order: decompiled, sast_done, agents_done. A checkpoint at stage S means every stage up to and including S finished and its output is recorded. Only the Java/Kotlin analyzer records stages; the other frameworks redo decompilation and resume per region. agents_done is written after the file review, so it holds the review's findings too.

A region resumed with steps already spent counts as having driven the loop, so if its first new turn fails it ends with the findings it restored instead of reporting that the model could not drive the loop at all, which once made a resumed Flutter scan discard its whole analysis. One file per region means no shared writer, so region workers checkpoint concurrently with no coordination. Region keys are stable across runs because partition_graph is deterministic, so a checkpoint file matches its region by key. A region that already reported is skipped entirely on resume.

The file review has no checkpoint of its own: a resume that reaches it (every framework but a Java/Kotlin scan already past agents_done) reviews every part again.

Everything degrades to "start over": a missing, unreadable or malformed checkpoint just runs the scan from the top. Nothing in the module may raise into a scan.

See Getting started for the UI and HTTP API for the endpoints.

11. Skills

Markdown files in lu77U_MobileSec/skills/ are appended to the agent's system prompt.

Core skill, always loaded, keyed by profile (skills_loader.CORE_SKILLS):

Profile Core skill
java_kotlin java_kotlin_security
flutter flutter_dart_security
react_native react_native_security
cordova cordova_hybrid_security
xamarin xamarin_dotnet_security

Profile skills (skills_loader.PROFILE_SKILLS), also loaded up front for every region of that framework: flutter_reverse_engineering (Flutter) and react_native_reverse_engineering (React Native), plus business_logic_abuse and deeplink_clipboard_trust for both. The first two teach how to read what this tool recovered (Blutter output, kernel source, Metro modules, Hermes decompilation), how to join the Dart or JavaScript side to the Java side, and what a defensible finding in that framework needs. The other two are there because a cross-platform app's logic lives in JavaScript or Dart that no manifest signal selects, and benchmark scans of both frameworks repeatedly missed a client-side entitlement gate and a deep link that acted on arrival.

Planned up front (_planned_skills): _ALWAYS_LOADED = ("vulnerability_classes", "finding_quality") comes first, ahead of the region's own surface skills (from guidance_for_families, keyed on its sink families), so the assembled skill text is [core, vulnerability_classes, finding_quality, <surface skills>] for every region of a scan, not [core, <surface skills>, vulnerability_classes, finding_quality]. Deciding up front keeps the system prompt stable across turns, which is what makes provider-side prompt caching possible; putting the always-loaded pair right after core makes that stable span a shared PREFIX across regions too, since two regions' differing surface skills then sit after it rather than between it and core.

Contextual (_contextual_skills), added as the agent works and sticky once loaded:

Trigger Adds
Manifest path or keyword manifest_review, android_analysis
exported, intent-filter, provider, receiver, getintent, deep link, scheme, addJavascriptInterface, pendingintent, rawquery, execsql vulnerability_classes, chain_building
buildconfig, sdk, gradle, google-services, firebase, flipper, stetho sdk_analysis
dexclassloader, class.forName, getdeclaredmethod, obfuscat, proguard, decrypt, smali, or a path of one/two-letter segments reading_obfuscated_code
\b(ssl|tls|trust|https?|cert|hostname|network|socket|pinning)\b (word boundary; plain substring fired inside clasSSLoader) network_security
inspect_native, .so, jni, native offensive_android, native_library_analysis
jiagu, stubapp, dexhelper, secneo, nesec, stubshell, libshell, apkwrapper, packer, loadlibrary, attachbasecontext packed_app_triage
cipher, secretkeyspec, messagedigest, mac, frida, hook, sharedpreferences, okhttp frida_hook_recipes
objection, sslpinning, keystore, sqlite, shared_preferences, root detection, rootbeer, isrooted, run-as, keygenparameterspec objection_runtime_toolkit
dart, ffi, pubspec, platform channel, methodchannel, .asm flutter_dart_security
blutter, libapp, libflutter, kernel_blob, pp.txt, invokemethod, awaitstub, returnasync, flutter flutter_reverse_engineering
hermes, app_modules, nativemodules, reactmethod, turbomodule, index.android.bundle, react-native, asyncstorage react_native_reverse_engineering
hermes, bundle, asyncstorage, webview, requirenativecomponent, react-native react_native_security
cordova, config.xml, inappbrowser, phonegap, www/, innerhtml, deviceready cordova_hybrid_security
oauth, pkce, redirect_uri, response_type, code_challenge, grant_type, id_token, appauth, openid oauth_oidc_mobile
clipboard, setprimaryclip, getprimaryclip, newplaintext, deep link, getqueryparameter, linking., app_links, uni_links, autoverify, browsable deeplink_clipboard_trust
deep link, getqueryparameter, intent://, uri_intent_scheme, browser_fallback_url, router, evaluatejavascript, shouldoverrideurlloading, onnewintent deeplink_endpoint_analysis
premium, subscription, entitlement, purchase, billing, receipt, coupon, promo, referral, redeem, wallet, isadmin, ispro business_logic_abuse
secretkeyspec, ivparameterspec, pbekeyspec, cipher.getinstance, keygenparameterspec, encryptedsharedpreferences, asyncstorage, mmkv, sqlcipher, flag_secure storage_crypto_review
pendingintent, getparcelableextra, parseuri, zipentry, objectinputstream, taskaffinity, filtertoucheswhenobscured, preferenceactivity, isvalidfragment, biometricprompt, bindservice, sendbroadcast android_ipc_ui_attacks
inspect_native, am start/broadcast/startservice, content://, adb, reachab, exploitab, proof, osv, sbom, cyclonedx, purl, advisory, verified evidence_discipline
inspect_native, objection, frida, mitmproxy, burp, repackag, apktool, logcat, sslpinning, authoriz, in scope/in-scope, out of scope/out-of-scope authorized_dynamic_testing
exported, md5, sha1/sha-1, getinstance, addjavascriptinterface, javascriptinterface, dexclassloader, class.forname, buildconfig, allowbackup, usescleartext, granturipermissions, placeholder, client_id/client id, api_key/apikey, false positive false_positive_patterns
getintent, getstringextra, getparcelableextra, getserializableextra, getdata, getqueryparameter, rawquery, execsql, loadurl, loaddata, evaluatejavascript, runtime.exec, processbuilder, startactivity, readobject, taint, source to/-sink, dataflow/data flow taint_source_to_sink

Thirty skills ship. tests/test_skills.py asserts every bundled skill is reachable by at least one route, that every referenced name resolves to a real file, and that none carries third-party attribution. Reachability is gathered from CORE_SKILLS, the surface tuples, and the bare string literals in agent_loop.py — so a skill added to the directory without a route is an orphan and fails that test.

vulnerability_classes defines the catalogue codes findings carry in vuln_class. Prefixes are OWASP MASVS control groups: PLATFORM-01…11, STORAGE-01…04, NETWORK-01…05, CRYPTO-01…03, SECRET-01…03, CODE-01…05, SUPPLY-01…02, AUTH-01…04, BUILD-01…04, BACKEND-01. validation/taxonomy.py is the single source of truth for a class's label, standalone-reportability and required proof, and the schema description the model receives is generated from it.

Two splits are load-bearing: NETWORK-01 (TLS validation disabled, standalone High) is separate from NETWORK-03 (no pinning, defence in depth); and the BUILD group exists so build configuration is never tagged as a vulnerability class, which is what stopped minSdkVersion 14 being proposed as half of a deep-link chain.

Users can add or shadow skills through the settings API (POST /api/settings/skills); see Configuration.

12. Code context enrichment

Before the artifact tree is deleted, BaseAnalyzer.enrich_vulnerabilities() attaches real source to each finding:

  1. Resolve file via resolve_source_path.
  2. Take line_number / line_end. With no usable line, locate the reported code_snippet by its most specific line, skipping bare braces.
  3. Build a window of 4 lines either side; store raw lines, per-line Pygments HTML, and the exact vulnerable span as code_snippet.

The model is never asked to echo code back. Pygments picks the lexer from the extension, so Dart, JS/TS and C# highlight correctly with no extra code. A finding whose file cannot be resolved keeps its other fields and has no code_context.

A finding citing a native library is resolved differently: against the decompiled view the agent read, with the citation repaired as described in Native libraries, and the context is the whole function rather than four lines either side, because the buffer declarations and the function's name sit well above the defect.

13. Analyzer result shape

Every analyze() returns the keys AnalysisService reads:

Key Meaning
success Decompilation/extraction and analysis completed
vulnerabilities Findings, enriched with code context
analysis_time, files_analyzed Report statistics
jadx_output_dir, source_root Same value, two keys. The artifact root, kept on disk when phase 2 follows (defer_cleanup)
static_transcript Full investigation transcript, passed to phase 2 when agent memory is on
code_graph Reused by phase 2 for per-finding structure hints
agent_coverage What the AI phase examined and why it stopped
error Present (with success: False) on failure

14. Java/Kotlin

JavaKotlinAnalyzer (analyzers/java_kotlin_analyzer.py).

Decompilation

jadx --output-dir <scan folder>/<apk stem>_jadx_output_<timestamp> \
     --no-imports --show-bad-code <apk>

--show-bad-code keeps partially-decompiled methods as comments instead of dropping them. A non-zero exit is tolerated when the output directory exists and is non-empty. Error count is parsed from stdout (ERROR - <n>). The tree has sources/ (Java) and resources/ (manifest, res, assets, native libs).

androguard analysis is prefetched on a background thread while JADX runs, so the code-graph build does not pay for it serially. The join is normally instant.

Class map

Built with androguard for classes ownership decided are the app's own.

Field Source
role Manifest: exported-activity/-provider/-service/-receiver, or the unexported equivalent
intent_actions Intent filter actions, minus MAIN
extends Superclass of the outer class
methods Up to 12 method names, excluding constructors
signals Sink families matched against outgoing calls
strings Up to 6 const-string literals matching a secret or URL pattern, truncated to 60 chars
refs Up to 8 other app classes this class calls

Sink families: sql (execSQL, rawQuery, SQLiteDatabase;->query), prefs, logging (Landroid/util/Log;), crypto (Cipher, MessageDigest, SecretKeySpec), webview (loadUrl, addJavascriptInterface, setJavaScriptEnabled), runtime (Runtime;->exec, ProcessBuilder), storage (getExternalStorage, openFileOutput, MODE_WORLD), uri (getLastPathSegment, getQueryParameter), native (System;->loadLibrary), ipc (getStringExtra, getParcelableExtra), display (TextView;->setText).

A class loading a native library gets role native-bridge (unless already exported); its callers gain a native-call signal. Native .so files are listed separately, deduplicated by filename across ABI directories. Any failure returns None and the agent falls back to the flat file tree.

_flag_js_bridges scans the JADX sources/ tree (bounded to 60 000 files) for @JavascriptInterface annotations, which androguard does not surface per method, and adds a js_bridge signal listing the exposed method names. That makes the bridge class flagged, so coverage tracking requires it be read. The bridge implementation is the data-exposure surface, distinct from the addJavascriptInterface call site the webview sink already flags.

Legacy full-dump fallback

If the agent loop cannot run, analyze_files_for_vulnerabilities() builds one prompt containing the manifest, filtered strings.xml, app layouts, backup and data-extraction rules, and every app Java file, then asks for a JSON array in a single call. File selection skips R.java, framework packages, and files under 500 characters with no class declaration. Java/Kotlin only.

15. Flutter

FlutterAnalyzer (analyzers/flutter_analyzer.py) recovers the Dart side the right way for the build mode, then decompiles the Java/Kotlin platform layer beside it. The build mode is read from the archive, so a debug build never waits on Blutter.

Release builds: Blutter

  1. extract_native_libs() (decompiler/apk_payload.py) pulls lib/arm64-v8a/*.so with zipfile, since Blutter is arm64-v8a only. No arm64-v8a slice falls back to the snapshot strings (below).
  2. Check libapp.so is present.
  3. run_blutter() (decompiler/blutter_runner.py) runs python3 blutter.py <lib dir> <out dir>. First run against an unseen Dart version compiles the SDK; the timeout is 30 minutes and the progress message says so. Success is judged by artifacts (pp.txt, or a non-empty asm/), not the return code. A Blutter failure falls back to the snapshot strings too.

Output: asm/<package>/<library>.dart (per-library disassembly, with each function's libapp.so offset), pp.txt (object pool including string literals and MethodChannel names), objs.txt, blutter_frida.js (not used by the pipeline; the Flutter skill points the reader at it for runtime hooks).

When Blutter cannot disassemble the build

Blutter is configured but this build is out of its reach in two cases: the APK has no arm64-v8a slice (an APK pulled from an x86_64 emulator carries only lib/x86_64/), or Blutter fails on the binary (usually a Dart version it cannot build yet). Neither is fixable from Settings, so the scan continues in a reduced mode instead of ending with no findings. A missing Blutter is different: preflight still refuses with the setting to fix, and the report says so.

A general disassembler cannot stand in for Blutter. libapp.so exports five symbols: _kDartVmSnapshotInstructions and _kDartIsolateSnapshotInstructions (one blob each, with no function boundaries), their two data blobs, and a build id. Dart's calling convention reaches every constant through the object-pool register, so Ghidra or objdump output for it names nothing a reader can tie to a screen. The isolate snapshot keeps its strings as plain bytes, though, and decompiler/dart_snapshot.py recovers them:

  • Slice. The first of arm64-v8a, armeabi-v7a, x86_64, x86 that holds a libapp.so. Every slice is the same program compiled differently, so the strings match.
  • Strings. Printable ASCII runs of six or more characters, deduplicated in first-appearance order (a library's strings sit together), each cut at 400 characters, written to snapshot_strings/libapp_strings.txt.
  • Key strings. snapshot_strings/libapp_key_strings.txt keeps what findings rest on: credential shapes from the shared secret table, endpoints (framework documentation hosts excluded), SQL, platform-channel names, JWTs, emails, lib*.so names, digest-length hex (32, 40 or 64 characters, with no run of six repeated characters, which is what sets a compared hash apart from the elliptic-curve constants crypto packages ship), strings carrying the app's package, and whole-word sensitive vocabulary split at camel case (password, secret, token, admin, premium, vip, pin, flag, frida, emulator and similar). Dropped first: dart: and package: URIs, library hash-tagged private names (_foo@1234567), the engine's keyboard key names, and a few framework identifiers. On DVFA this keeps 67 of 14,362 strings, among them the hardcoded key, the notes SQL and the VIP check.

The rest of the pipeline runs as usual on what remains readable: the JADX platform layer, the manifest, the native libraries (Ghidra decompiles any architecture), the overview, the graph, the agent, the file review and the scanners (secrets reads the strings files). Specifically:

  • The strings are recovered after the platform layer, so the manifest's package can mark the app's own identifiers.
  • The overview opens with "libapp.so could NOT be disassembled", lists the key strings and tells the agent to base a Dart-side finding on a string together with the platform layer or a native library, and to say what could not be checked.
  • The graph adds the key-strings file and every Java/Kotlin file under the app's package as app-code nodes, so both are flagged, read by the agent and covered by the file review. Channel-shaped key strings join the channel names, so their Java handlers are found by literal as in a Blutter scan. A string that is exactly a bundled library's name counts as the app loading it.
  • The agent's label is "Flutter (release build - no Dart disassembly: libapp.so strings, the platform layer and native libraries only)".
  • The result carries limitation, naming why Blutter could not be used and what was analysed instead. The scan page and the HTML report show it as Reduced coverage, and the warning is logged so it reaches the dashboard feed and scan.log.

Debug builds: original source from the kernel

A debug build ships assets/flutter_assets/kernel_blob.bin and no libapp.so; it used to be rejected for that. The kernel keeps a source table for stack traces and hot reload, and extract_kernel_sources() (decompiler/dart_kernel.py) recovers it by scanning for one stable shape (a length-prefixed URI followed by length-prefixed UTF-8 source) rather than parsing the whole kernel format, which changes between Dart releases. App files go to dart_source/, third-party packages to dart_packages/<name>/; the Flutter and Dart SDK sources are dropped. Every output path is rebuilt from sanitised components and checked to stay inside the destination, and the kernel is capped at 256 MB before it is read. Blutter is not needed for these builds, and preflight() lets them through without it.

The flutter-build scanner records the debug build as a deterministic BUILD-01 finding.

Platform layer and overview

decompile_platform_layer() (shared in BaseAnalyzer) runs JADX into platform/ in both modes. Flutter cannot check for root, debuggers, emulators or tampering itself: those checks, and much plugin behaviour, live in Java/Kotlin behind a MethodChannel. Without JADX configured the platform layer is skipped with a log line and the scan continues.

write_flutter_overview() writes flutter_scan_overview.txt, the profile's orientation file. Most decision-relevant first: the build mode and how to read it, where each artifact lives, the manifest's exported components, then the channel map for the channels the app's own code uses (each MethodChannel name with its Dart call sites and the Java/Kotlin files that handle the same literal, which survives R8 renaming), the native libraries the app loads with where it loads them, and the strings the app's own code loads, including those inside the const objects it references. A const widget tree is in objs.txt, not pp.txt (the pool holds only List<Widget>(4) [Obj!ListTile@...]), so parse_object_dump() indexes objs.txt and the referenced objects' strings are followed; a lab app's developer-menu secrets were invisible to a pool search. Channels only third-party plugins use are one line at the end: their pigeon calls once filled the 5500-character bound and pushed everything after them out.

Graph

build_flutter_graph() (analyzers/flutter/graph.py) classifies each Dart library by its top directory under asm/ (or by source path in debug mode) as the app's own code, a third-party package, or the Flutter SDK. A real Blutter recovery is a few app libraries beside hundreds of framework ones, and the framework matches every sink pattern; scoring every file flagged the framework and missed the app's main.dart. So:

  • Flutter SDK libraries are left out of the graph (still readable through the tools).
  • The app's own libraries are always flagged: app-entry for main.dart, else app-code.
  • Third-party packages (dart-package) the app reaches within two calls stay in the graph, linked from the app code that calls them, but are never flagged: on a lab app with the usual storage, database, WebView and crypto plugins, flagging the ones that touch a sink sent a third of the agent's steps into plugin internals.
  • Java/Kotlin files handling a channel the Dart side uses become platform-channel-handler nodes, always flagged.
  • An obfuscated build has no package layout, so every file is scored on its signals as before (entry-point, native-bridge, app-class).
  • Native libraries the app's own code loads (a lib*.so literal handed to dart:ffi, or System.loadLibrary in the app's Java/Kotlin package) are the graph's native libraries, so inspecting them counts toward coverage (agent/native_loading.py).

Dart sinks: network (HttpClient, package:http, Dio(, WebSocket(), tls (badCertificateCallback, HttpOverrides, SecurityContext), storage (SharedPreferences, path_provider, sqflite, Hive., File(), secure_storage (flutter_secure_storage), crypto (pointycastle, package:encrypt, Cipher(, Digest(), webview (webview_flutter, InAppWebView, loadUrl, loadRequest), platform_channel (MethodChannel, EventChannel, BasicMessageChannel), ffi, logging (print(, debugPrint().

Secrets from pp.txt are attached to a synthetic ObjectPool node rather than guessed onto a class. Nothing recoverable → None → flat file tree.

A finding that cites pp.txt or objs.txt is moved to the app code that loads the value before enrichment (FlutterAnalyzer._recite_pool_findings, recovered.LiteralLocator). The pool says nothing about which screen uses a constant; a debug key cited at objs.txt line 20285 was really shown by the hidden developer screen. Each quoted value in the finding, and on the cited pool line, is looked up in the app's own disassembly: as a literal on a summary line, as a const object (Obj!…@id) whose dump holds it, or as a pool slot that lists such an object (a List<Widget> of tiles). A value the model quoted cut short ('pvgw_live_secr...') is first completed to the one dump string that starts with it (LiteralLocator.complete, at least eight characters, refused when ambiguous). The first hit becomes the citation, moved up to its summary line; the original is kept as pool_reference for the gates and the transcript, though like the other internal fields it is not carried into the report. A value the app never loads leaves the finding as it was.

16. React Native

ReactNativeAnalyzer (analyzers/react_native_analyzer.py) recovers the bundle as one file per Metro module, split into the app and the framework, and decompiles the Java/Kotlin platform layer beside it.

Bundle format and preflight

find_js_bundle() looks for assets/index.android.bundle, else any assets/*.bundle. Hermes bytecode starts c6 1f bc 03 c1 03 19 1f, followed by the bytecode version as a little-endian u32. preflight() reads the format straight from the APK, so the right tool is required for this app rather than "either tool":

Bundle Needs Recovery
Plain JavaScript (JSC) nothing Built-in Metro splitter (decompiler/rn_metro.py). A bundle it does not recognise (Webpack, Haul) goes to react-native-decompiler when rn_decompiler_path is set
Hermes bytecode hermes_decomp_path hermes-decomp extract <bundle> -o <dir> (one file per module, into a scratch directory removed once the tree is written); an older hermes-decomp without extract falls back to decompile of the whole bundle

A package-metadata.json recording the bundle member and its format is written beside the tree. hermes-decomp's modules and secrets output is written to modules.txt and secrets.txt at the root.

Metro modules: app vs framework

Metro wraps every module the same way, whatever the engine: __d(function(g,r,i,a,m,e,d){…}, <id>, [<deps>]), and module 0 is the entry (index.js). Release bundles carry no source maps or file paths, so the split is computed from that shape (classify_modules):

  • The entry's dependencies are react-native (whose closure is most of the bundle) and the app's root component. The framework root is the entry dependency that another entry dependency also reaches. Simply taking the largest closure picked the app on a real bundle, because the root component's closure contains react-native's.
  • App region = everything the entry's other dependencies reach, minus the framework closure, plus the entry.
  • Imported libraries are then taken out (library_modules). A Hermes bundle keeps no paths, so react-native-webview, AsyncStorage, crypto-js and the like reach the app region through the app's own imports, and benchmark reports listed their internals (an origin matcher, crypto-js's MD5-based KDF) as the app's flaws. A module carrying a string only that library's own code has (rn_metro.LIBRARY_MARKERS: its native module or component name such as "RNCWebView"/"RNAsyncStorage", its [AsyncStorage] error prefix, the CryptoJS global its wrapper registers, redux's @@redux/INIT) is a barrier: the app region is recomputed without passing through one, so the library and everything only it reaches go to framework_modules/, while a small re-export the app imports directly stays.

write_module_tree() writes app_modules/<id>_<name>.js and framework_modules/<id>_<name>.js, each starting with a // Module ID / Name / Dependencies header. Names come from hermes-decomp's recovery, or for plain bundles from a dev build's verbose name or the module's first named export; they are reduced to safe characters and every write is checked to stay inside the output directory.

A plain bundle is minified onto a few enormous lines, so format_js() lays each module out on short lines. It only ever inserts whitespace (it tracks strings, template literals, regex literals and comments), so it can mis-break a line but never change a token. Recovery takes well under a second for plain bundles and about half a second with hermes-decomp.

Platform layer and overview

JADX decompiles the platform layer into platform/ (as for Flutter). write_rn_overview() writes rn_scan_overview.txt, the profile's orientation file:

  • engine and bytecode version, React Native version (from ReactNativeVersion), old-bridge vs new-architecture library markers
  • the module layout and the manifest summary
  • native libraries the app's own Java/Kotlin loads (System.loadLibrary), with where, each flagged to inspect_native; React Native's own runtimes are listed apart
  • native modules: every class extending ReactContextBaseJavaModule / BaseJavaModule / a codegen Native*Spec outside React Native itself, with its JavaScript name (getName(), literal or constant) and @ReactMethod methods, app-owned first, each joined to the app JS that calls it. An app-owned module nothing calls is flagged as still exposed, because any JavaScript that runs in the app can call it. A codegen spec and its implementation are merged under one name.
  • entitlement and role flags the app JS reads (isPremium, hasProAccess, isAdmin), the most common client-side logic flaw and invisible to sink scanning
  • WebView bridge props, AsyncStorage keys, URLs, credential-shaped strings (values withheld unless public), and hermes-decomp's own string-table secret scan

The overview is bounded to 5500 characters.

Graph

build_rn_graph() (analyzers/react_native/graph.py) works over the module tree when app_modules/ exists:

  • one node per app-region module, all flagged: app-entry for module 0, else app-code
  • refs follow each module's dependency header within the app region
  • each app-owned native module is a native-module node, always flagged
  • native libraries the app's own code loads are the graph's native libraries, so inspecting them counts toward coverage
  • framework modules are left out

On the DVRN benchmark this took the flagged set from 113–185 files, mostly framework fragments, to 33–34 files, all app code plus the DebugModule. The older shapes (per-module files or a single bundle.js from an external decompiler) are still handled when the module tree is absent.

JS sinks: network (fetch(, XMLHttpRequest, axios.), storage (AsyncStorage, react-native-fs, RNFS, MMKV), secure_storage (react-native-keychain, EncryptedStorage, expo-secure-store), webview (WebView, injectedJavaScript, onMessage, postMessage), eval (eval(, new Function(), crypto (crypto-js, CryptoJS, createCipher, createHash), native_module (NativeModules, TurboModuleRegistry), deeplink (Linking.getInitialURL, Linking.openURL, Linking.addEventListener), logging (console.log, console.warn, console.error).

17. Cordova

CordovaAnalyzer (analyzers/cordova_analyzer.py). Nothing to decompile: the app ships plain HTML/JS/CSS under assets/www/. No external tool; preflight() is always ready.

extract_cordova_www() unzips every assets/www/** member preserving the tree below assets/www/, and pulls config.xml (from res/xml/config.xml, else root) to the root. Directory entries are skipped; any member escaping the destination (zip-slip) is refused. No assets/www/ → the analyzer reports the APK isn't a Cordova app.

build_cordova_graph() (analyzers/cordova/graph.py) builds one node per .js/.html/.htm. role: entry-page (HTML with deviceready/cordova.js), page (other HTML), app-script (JS). refs from <script src> and require(...). The Cordova runtime and common vendored libraries are noise; the app's own plugins/, its native-bridge surface, is kept.

Sinks: dom_xss (innerHTML, document.write, .html(, insertAdjacentHTML), eval, network (XMLHttpRequest, fetch(, $.ajax), cordova_exec, inappbrowser (InAppBrowser, window.open(), file (requestFileSystem, resolveLocalFileSystemURL, FileTransfer), storage (localStorage, openDatabase(, sqlitePlugin), webintent, geolocation, crypto (CryptoJS), deeplink (handleOpenURL), logging.

config.xml defines the trust boundary: the whitelist (<access origin>, <allow-navigation>), the CSP and the plugin list. The cordova_hybrid_security skill directs the agent to read it first.

The prebuilt DVHMA APKs under etc/vulnerable-apps/ are the Cordova test fixtures (tests/test_cordova_dvhma.py, skipped when absent).

18. Xamarin / .NET MAUI

XamarinAnalyzer (analyzers/xamarin_analyzer.py). The DEX is a launcher plus Mono bindings; the app is .NET assemblies inside the APK. preflight() is always ready, because recovery is pure Python. An optional decompiler changes the scan's quality, not its existence.

Assembly recovery

extract_xamarin_assemblies() (decompiler/xamarin_extractor.py) handles three container formats:

Format Shape Where
Plain PE .dll stored as-is assemblies/, assets/assemblies/, unknown/assemblies/
XALZ Per-DLL LZ4 behind a 12-byte header (magic, index, uncompressed size) Same; Xamarin.Android 9.4+ with compression on
XABA One AssemblyStore blob with an offset index assemblies.blob; in MAUI 9, lib/<abi>/libassemblies.*.blob.so

Detection is by magic bytes, not filename. Stores get renamed, and a MAUI blob carries a .so extension while being no such thing. The XABA magic reads as BAAX on disk (little-endian 0x41424158), so a naive startswith(b"XABA") finds nothing.

LZ4 block format has no stdlib decoder, so _lz4_block_decompress implements it. Matches may overlap the write cursor, which is how LZ4 encodes runs, so a match is copied byte by byte; slicing produces silently wrong output.

The AssemblyStore index layout varies by Xamarin version. _try_descriptors tries several descriptor sizes and accepts a layout only when every entry points inside the blob with a plausible length. A wrong guess is rejected rather than producing garbage.

Two levels of fidelity

write_string_sidecars() writes a <Assembly>.dll.txt of printable strings beside every recovered .dll, in ASCII and UTF-16LE, since .NET stores user strings as UTF-16LE. That is what makes the scan work without a decompiler: agent tools read text, a .dll is binary, and Xamarin builds ship largely unobfuscated, so the string table holds endpoint URLs, connection strings and keys.

With xamarin_decompiler_path set (or ilspycmd on PATH), decompile_assemblies() (decompiler/ilspy_runner.py) additionally decompiles the app's own assemblies to C#. Framework assemblies are skipped.

An assemblies.txt inventory separating app from framework assemblies is written either way, and is the profile's orientation file.

Code graph

build_xamarin_graph() (analyzers/xamarin/graph.py) maps decompiled C# only. With string sidecars alone there is no structure to graph, so it returns None and the agent works from the flat file tree.

role comes from C# attributes: [Activity], [Service], [BroadcastReceiver], [ContentProvider], with Exported = true or an [IntentFilter] making it exported-*.

.NET sinks: tls (ServerCertificateValidationCallback, DangerousAcceptAnyServerCertificateValidator), network (HttpClient, WebClient), webview (Xamarin.Forms.WebView, AddJavascriptInterface, BlazorWebView), sql (SqliteCommand, CommandText), prefs (Preferences.Set, Application.Current.Properties; note that SecureStorage is the Keystore-backed one and the others are not), storage, crypto (TripleDES, CipherMode.ECB, Rfc2898DeriveBytes), serialization (BinaryFormatter, TypeNameHandling), ipc, native (DllImport), logging, reflection.

ServerCertificateValidationCallback returning true disables TLS verification for every request the app makes.

Verification status

No real Xamarin APK was available while this was written. Every parse path is bounds-checked and returns rather than raising, and the container formats are exercised against synthetic fixtures in tests/test_xamarin.py, including an LZ4 round-trip with an overlapping match. Treat the AssemblyStore path as unverified against a production build.

Clone this wiki locally