Skip to content
Back to search

Android-Pentesting-Skill

Comprehensive Android APK security audit with static analysis, dynamic instrumentation, source-to-sink tracing, IPC/component abuse analysis, and CVSS 4.0 reporting. Covers decompilation, manifest analysis, deep links and intent injection, secrets detection, crypto analysis, Frida/Objection integration, and APK repackaging. Use when user says "audit APK", "analyze android app", "mobile pentest", "APK security", "decompile APK", "android vulnerability assessment", "reverse engineer android", "modify APK", "intent injection", "deep link abuse", "bypass SSL pinning", "bypass root detection", or provides an APK for security review, decompiled Android sources, or decoded resources.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/dragonjar--android-pentesting-skill/badge.svg)](/listings/dragonjar--android-pentesting-skill)

HTML

<a href="/listings/dragonjar--android-pentesting-skill"><img src="/api/listings/dragonjar--android-pentesting-skill/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Option 1: Clone into Agent Skills Directory

# For Claude Code / OpenCode agents
cd ~/.agents/skills/
git clone https://github.com/DragonJAR/Android-Pentesting-Skill Android-Pentesting-Skill

# For other agents, place in your skills directory

Option 2: Install Globally

# Clone to any location
git clone https://github.com/DragonJAR/Android-Pentesting-Skill.git

# Add to your agent's skill path configuration

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 1,043 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. ---
  2. name: Android-Pentesting-Skill
  3. description: >
  4. Comprehensive Android APK security audit with static analysis, dynamic instrumentation, source-to-sink tracing, IPC/component abuse analysis, and CVSS 4.0 reporting. Covers decompilation, manifest analysis, deep links and intent injection, secrets detection, crypto analysis, Frida/Objection integration, and APK repackaging. Use when user says "audit APK", "analyze android app", "mobile pentest", "APK security", "decompile APK", "android vulnerability assessment", "reverse engineer android", "modify APK", "intent injection", "deep link abuse", "bypass SSL pinning", "bypass root detection", or provides an APK for security review, decompiled Android sources, or decoded resources.
  5. license: Apache-2.0
  6. allowed-tools: "Bash(apktool:*) Bash(jadx:*) Bash(aapt2:*) Bash(d8:*) Bash(frida:*) Bash(objection:*) Bash(adb:*) Bash(keytool:*) Bash(zipalign:*) Bash(apksigner:*) Bash(python3:*) Bash(apkid:*) Bash(android:*) Read Write Edit Glob Grep"
  7. metadata:
  8. author: DragonJAR SAS
  9. version: "1.9.0"
  10. category: mobile-security
  11. tags:
  12. - android
  13. - apk-audit
  14. - static-analysis
  15. - dynamic-analysis
  16. - frida
  17. - objection
  18. - security-pentest
  19. - cvss-scoring
  20. - reverse-engineering
  21. - ai-powered
  22. - ai-analysis
  23. ---
  24. # Android APK Security Audit
  25. ## Overview
  26. Deterministic 6-phase static analysis + optional dynamic confirmation workflow. Remove noise early, keep the package scope tight. Only report vulnerabilities where source, propagation, and sink are understood or clearly marked as needing dynamic confirmation.
  27. ## When to Use
  28. - User provides an APK file for security review
  29. - User asks to analyze decompiled Android source code
  30. - User needs to modify or repackage an APK for testing
  31. - User wants mobile security testing or vulnerability assessment
  32. - User needs help testing exported components, deep links, or intent injection
  33. - User mentions Android reverse engineering or malware analysis
  34. ## Critical Rules
  35. 1. NEVER report bare grep hits without traced context
  36. 2. ALWAYS constrain searches to the app namespace (avoid library noise)
  37. 3. STOP and report immediately if decoding fails
  38. 4. ALWAYS use imperative language in findings
  39. 5. NEVER skip validation — if unsure, mark as "Needs Dynamic Confirmation"
  40. 6. ALWAYS provide concrete PoC (adb command, Frida hook, or malicious intent)
  41. 7. NEVER duplicate findings for the same root cause
  42. > **Quality Note**: Take your time to analyze thoroughly. Quality is more important than speed. Do not skip validation steps — a false positive is worse than a missed finding.
  43. ## Execution Model
  44. Tools to use: bash, write, edit, read, glob, grep for core workflow.
  45. ## Toolchain Requirements
  46. Before starting, verify these tools are installed:
  47. - **APKTool** 3.0.2+ (`apktool --version`) — aapt2-only mode; requires Java 17+
  48. - **JADX** 1.5.5+ (`jadx --version`)
  49. - **Android SDK Platform Tools 36.0.2** (`adb`, `fastboot`)
  50. - **Android SDK Build Tools 36.0.0** (`apksigner`, `zipalign`, `aapt2`, `d8`)
  51. - **Frida** 17.x (`frida --version`) — ⚠️ Frida-server on device must match the **frida core** version (the `frida` Python package), NOT frida-tools
  52. - **Objection** 1.12.5+ (`objection --version`)
  53. - **APKiD** 3.1.0+ (`apkid --version`)
  54. - **android-cli** (optional, recommended) — official Google CLI; preferred wrapper for install/run/screen/layout/emulator/docs when present. Graceful fallbacks to adb live in `scripts/lib/android-cli-or-fallback.sh` (single switch point). See `references/quick-commands.md` → "Optional: android-cli".
  55. Run `scripts/06-setup/preflight-check.sh` (bash), `scripts/06-setup/preflight-check.py` (universal, JSON output), or `scripts/06-setup/preflight-check.ps1` (PowerShell) to verify all tools. See `references/environment-setup.md` for installation instructions.
  56. ---
  57. ## AI-Powered Analysis
  58. This skill includes AI-powered analysis capabilities. The AI model running this skill has built-in code analysis - use it strategically to enhance findings.
  59. ### When to Use AI
  60. - Analyzing decompiled code for semantic vulnerabilities
  61. - Tracing complex data flows (source-to-sink)
  62. - Generating Proof-of-Concept exploits
  63. - Filtering false positives from automated scans
  64. - Understanding obfuscated code behavior
  65. - Enhancing report quality and context
  66. ### How to Use AI
  67. 1. **Analyze specific code sections**: Don't ask AI to find ALL vulnerabilities - target specific suspicious code
  68. 2. **Provide context**: Include the full function/class, not just snippets
  69. 3. **Ask for CVSS scoring**: Request severity assessment with CVSS 4.0
  70. 4. **Verify findings**: Always validate AI findings against code and Frida testing
  71. ### AI Analysis Prompts
  72. See `references/ai-pentesting-guide.md` for complete methodology and prompt templates.
  73. Quick examples:
  74. ```
  75. ANALYZE: Is this SQL injection exploitable?
  76. Code: <vulnerable_query_with_user_input>
  77. Context: <userId from Intent extra>
  78. For each finding provide:
  79. - CWE ID and CVSS 4.0 score
  80. - Exploitation scenario
  81. - Frida script to demonstrate (if applicable)
  82. ```
  83. > **Reference**: `references/ai-pentesting-guide.md` - Complete AI analysis methodology
  84. > **Inventory**: [`references/project-manifest.md`](references/project-manifest.md) is the ground-truth list of every packaged file and directory.
  85. ---
  86. ## Audit Mode Selection
  87. Select the smallest mode that satisfies the user request. See `references/audit-modes.md` for full feature flags and presets.
  88. | Mode | Default Use | Notes |
  89. |------|-------------|-------|
  90. | `quick` | First-pass triage | Decode, manifest, focused static checks, coverage statement. |
  91. | `static` | No device/emulator | Static analysis only; mark runtime-only issues `Needs Dynamic Confirmation`. |
  92. | `full` | Standard APK audit | Static + dynamic + MASVS + optional executive risk score. |
  93. | `protected-app` | Packing/RASP blocks analysis | Follow protected-app fallback and record coverage gaps. |
  94. | `osint` | Public exposure enrichment | Passive, in-scope OSINT only. |
  95. | `reporting-only` | Existing findings JSON | Deduplicate, triage, MASVS, risk score, report. |
  96. ---
  97. ## Optional Input Adapter — Gmail APK Ingestion
  98. `scripts/00-ingestion/fetch-apk-gmail.py` downloads APK attachments from Gmail into a working directory **before** the audit workflow starts. It is an optional input adapter, not an audit phase: it never modifies Phases -1 through 5 and produces only files plus `ingestion-manifest.json` (sender, message id, attachment id, sha256 per file).
  99. ```bash
  100. # List matches without downloading
  101. python3 scripts/00-ingestion/fetch-apk-gmail.py --output-dir ./ingested/ --dry-run
  102. # Download (requires OAuth credentials outside the repo)
  103. python3 scripts/00-ingestion/fetch-apk-gmail.py --output-dir ./ingested/ --sender audits@corp.com --max 5
  104. ```
  105. Safety model: Gmail **read-only** OAuth scope, sender allowlist, APK magic-byte validation with quarantine of invalid files, sha256 idempotency, no auto-install. Credentials paths are provided via `GMAIL_INGEST_CREDENTIALS` / `GMAIL_INGEST_TOKEN` env vars and are git-ignored. See `scripts/00-ingestion/README.md`.
  106. ---
  107. ## Phase 0 — Decode and Detect Framework
  108. ### Decode APK
  109. ```bash
  110. apktool d app.apk -o decoded/ # Decode resources + smali
  111. jadx -d jadx_output app.apk # Decompile to Java
  112. apkid app.apk # Detect framework/packer
  113. ```
  114. ### Framework Detection
  115. Identify the app's architecture early to tailor analysis.
  116. **React Native**: `grep -r "com.facebook.react" decoded/AndroidManifest.xml` · Check for `libhermes.so` and `index.android.bundle` in assets/
  117. **Flutter**: `grep -r "io.flutter" decoded/AndroidManifest.xml` · Check for `libflutter.so` and `assets/flutter_assets/`
  118. **Cordova/Ionic**: `grep -r "org.apache.cordova" decoded/AndroidManifest.xml` · Check `assets/www/` for cordova.js
  119. **Xamarin**: `grep -r "mono\|com.xamarin" decoded/AndroidManifest.xml` · Check for `libmonodroid.so`
  120. **.NET MAUI**: check for `assemblies/*.dll` (managed DLL bundle), `assemblies/TrimmerRoots.xml`, and `libxamarin-android` / `Mono.Android.dll` artifacts · Run `scripts/01-cross-platform/dotnet-maui-analysis.sh <apk> <out>` for automated managed-assembly extraction, ilspycmd decompilation, and C# security triage
  121. > **Reference**: `references/hybrid-webview-frameworks.md` for complete detection scripts, Frida detection hooks, and framework-specific security considerations.
  122. > **Reference**: `references/dotnet-maui-security.md` for .NET MAUI/Xamarin managed-assembly extraction (IL/DLL), C#-specific security checklist, and mono-runtime Frida hooks.
  123. > **Cross-Platform Analysis Scripts**: Use `scripts/01-cross-platform/cordova-analysis.sh`, `scripts/01-cross-platform/flutter-analysis.sh`, `scripts/01-cross-platform/react-native-analysis.sh`, and `scripts/01-cross-platform/unity-analysis.sh` for framework-specific static analysis of Cordova/Ionic, Flutter, React Native, and Unity applications respectively. These scripts extract framework-specific metadata, identify native module usage, and highlight security considerations unique to each framework.
  124. ### Obfuscation Detection
  125. - **ProGuard/R8**: Class names like `a.b.c`, `a$a`, `a$1`
  126. - **DexGuard**: Additional string encryption and native methods
  127. - **Custom obfuscation**: Unusual patterns, mixed naming schemes
  128. > **Reference**: `references/static-analysis-patterns.md` for detailed detection patterns.
  129. ---
  130. ## Phase 1 — Attack Surface Mapping
  131. ### Analyze AndroidManifest.xml
  132. ```bash
  133. cat decoded/AndroidManifest.xml
  134. aapt2 dump badging app.apk
  135. ```
  136. ### Exported Components
  137. Exported components are attack surfaces:
  138. | Component | Exported If | Security Checks |
  139. |-----------|-------------|-----------------|
  140. | Activities | `android:exported="true"` | Intent filters, permission requirements |
  141. | Services | `android:exported="true"` | Intent filters, permission requirements |
  142. | Receivers | `android:exported="true"` | Intent filters, permission requirements |
  143. | Providers | `android:exported="true"` | Path permissions, read/write permissions |
  144. ### Deep Link Schemes
  145. Extract and document all deep link schemes:
  146. ```xml
  147. <intent-filter>
  148. <data android:scheme="scheme" android:host="host" />
  149. </intent-filter>
  150. ```
  151. ### Security-Relevant XML Resources
  152. Check `res/xml/` for: `network_security_config.xml` (TLS/cleartext), file provider paths, preferences.
  153. > **Reference**: `references/android-manifest-checklist.md` for complete 50+ manifest checks.
  154. > **IPC / intent abuse**: see `references/intent-injection.md` and `references/pendingintent-security.md`.
  155. ---
  156. ## Phase 2 — Targeted Triage
  157. ### Scoped Grep Patterns
  158. ALWAYS grep within the app namespace only. Use patterns from `references/static-analysis-patterns.md`:
  159. | Category | Example Patterns | What to Look For |
  160. |----------|------------------|------------------|
  161. | WebView sinks | `loadUrl\(`, `evaluateJavascript` | Loading untrusted URLs |
  162. | IPC sources | `getIntent()`, `onNewIntent()` | Unsanitized data entry |
  163. | Intent relays | `getParcelableExtra`, `getSerializableExtra`, `startActivity\(`, `sendBroadcast\(` | Nested intent / confused deputy patterns |
  164. | Hardcoded secrets | `password\s*=`, `api[_-]?key` | Credentials in code |
  165. | Encoded literals | `Base64\.decode`, `"\x[0-9a-f]"` | Obfuscated strings |
  166. | Weak crypto | `DES/`, `MD5`, `"AES/ECB"` | Insecure algorithms |
  167. | Insecure storage | `SharedPreferences`, `MODE_WORLD_READABLE` | Unprotected data → `references/data-storage-auditing.md` |
  168. | Network/TLS | `TrustManager`, `X509TrustManager` | SSL validation bypass |
  169. | Native bridges | `System\.loadLibrary`, JNI methods | Native code interfaces |
  170. ### Resource File Analysis
  171. Check `res/values/strings.xml` for secrets:
  172. ```bash
  173. grep -iE "(key|token|secret|password|api)" decoded/res/values/strings.xml
  174. ```
  175. > **Reference**: `references/static-analysis-patterns.md` for 100+ grep patterns organized by vulnerability type.
  176. ### Phase 2.5 — Static Analysis Rules (Optional)
  177. The semgrep-based static analysis module augments grep patterns with OWASP MASTG rules:
  178. ```bash
  179. # Enable semgrep in auto-audit-static.sh
  180. bash scripts/auto-audit-static.sh app.apk --semgrep
  181. # Run semgrep scan standalone
  182. python3 scripts/03-static-analysis/semgrep-scan.py decoded/ --output findings-semgrep.json
  183. # Merge findings with existing findings
  184. python3 scripts/03-static-analysis/merge-findings.py --input findings.json semgrep.json --output merged.json
  185. # Update rules from upstream
  186. bash scripts/03-static-analysis/update-rules.sh --fetch
  187. ```
  188. **Features**:
  189. - 70+ MASTG-aligned rules covering crypto, network, storage, authentication
  190. - Non-blocking fallback (continues if semgrep is not available)
  191. - Deduplication by CWE + title before merging
  192. - Phase 2.5 runs after grep patterns, before data flow tracing
  193. > **Reference**: `scripts/03-static-analysis/semgrep-scan.py --help` for rule categories and update workflow.
  194. ### Advanced Static Detectors — ZipSlip, XEE, Accessibility, Clipboard
  195. Four gap-filling detector families beyond grep patterns and semgrep rules:
  196. ```bash
  197. # Run against an already-decoded directory (from Phase 0)
  198. bash scripts/03-static-analysis/advanced-static-checks.sh -d decoded/ -o adv-static/
  199. # Or decode + check in one step
  200. bash scripts/03-static-analysis/advanced-static-checks.sh -a app.apk -o adv-static/
  201. ```
  202. **Detectors**: zip path traversal (CWE-22/23), XML external entity (CWE-611), exported accessibility services (CWE-926), background clipboard capture (CWE-200). Emits `advanced-static-findings.json` (`source: grep`) plus a human report.
  203. ### APK Version Diffing — N-day Hunting (Optional)
  204. When two versions of the target APK are available (e.g. pre/post security fix), diff them to spot the fix and rediscover the underlying vulnerability:
  205. ```bash
  206. # Full diff: inventory, decompiled sources, secrets rotation
  207. bash scripts/03-static-analysis/version-diff-audit.sh --old app-v1.2.apk --new app-v1.3.apk
  208. # Fast path without jadx decompilation
  209. bash scripts/03-static-analysis/version-diff-audit.sh --old v1.apk --new v2.apk --skip-jadx
  210. ```
  211. **Signals**: secrets removed in the new version (fix confirmation → N-day), new exported components in the manifest diff, new native libraries. Emits `version-diff-findings.json` (`source: diff`). Secret values are never printed — only pattern name + file + hash prefix.
  212. > **Reference**: `references/app-version-diffing.md` for the full bughunter workflow.
  213. ---
  214. ## Phase 3 — Data Flow Tracing
  215. ### Source-to-Sink Methodology
  216. Map data flow from untrusted sources to dangerous sinks:
  217. #### Common Sources
  218. | Source | Method | Example |
  219. |--------|--------|---------|
  220. | IPC (Activities) | `getIntent()` | Malicious intent data |
  221. | IPC (Services) | `onStartCommand()` | Start extras |
  222. | Deep Links | `getIntent().getData()` | URL parameters |
  223. | WebView | `JavascriptInterface` | Untrusted JS calls |
  224. | Network | `HttpResponse` | API responses |
  225. | Storage | `SharedPreferences` | Stored user input |
  226. | External | `Environment.getExternalStorageDirectory()` | File system data |
  227. #### Common Sinks
  228. | Sink | Method | Impact |
  229. |------|--------|--------|
  230. | Command Execution | `Runtime.exec()`, `ProcessBuilder` | RCE |
  231. | WebView Load | `loadUrl()`, `loadData()` | XSS, Phishing |
  232. | File Operations | `FileWriter`, `FileOutputStream` | Path traversal, LFI |
  233. | IPC Broadcast | `sendBroadcast()` | Intent injection |
  234. | Reflection | `Class.forName()`, `getMethod()` | Code execution |
  235. | Native Calls | JNI | Native code execution |
  236. | SQL | `SQLiteDatabase.execSQL()` | SQL injection |
  237. ### Decision Rules
  238. | Rule | Condition | Action |
  239. |------|-----------|--------|
  240. | 1 | Direct flow source → sink | Report as **Likely** |
  241. | 2 | Indirect flow via static analysis | Report as **Likely** if path clear |
  242. | 3 | Dynamic/reflective call | Mark as **Needs Dynamic Confirmation** |
  243. | 4 | Native boundary | Mark as **Needs Dynamic Confirmation** |
  244. | 5 | Library code | Verify if app wraps securely |
  245. | 6 | No sanitization | Escalate severity |
  246. ### Manual Checks Grep Misses
  247. | Check | Why grep misses | How to verify |
  248. |-------|----------------|---------------|
  249. | Runtime permissions | `requestPermissions()` calls | Trace `onRequestPermissionsResult` |
  250. | Custom permission protections | `checkPermission()` | Look for permission checks |
  251. | Activity transitions & intent relays | `startActivity()` hides nested-intent forwarding and grant flags | Follow intent construction, `Parcelable` relays, and `FLAG_GRANT_*` usage |
  252. | File provider paths | XML + code | Map paths to exposed content URIs |
  253. | Content provider queries | `query()` | Trace URI construction |
  254. > **Reference**: `references/attack-patterns.md` for modern attack vectors: intent injection, deep link abuse, WebView universal XSS, task hijacking, file provider path traversal, broadcast theft, component hijacking.
  255. ---
  256. ## Phase 4 — Dynamic Analysis (Optional)
  257. Use when static analysis hits a wall: obfuscation, reflection, native code, runtime protections.
  258. ### Runtime Defense Analysis (RDA)
  259. The Runtime Defense Analysis module provides Frida-based detection and bypass for anti-analysis mechanisms:
  260. ```bash
  261. # Run static audit first; RDA is a separate Phase 4 module
  262. bash scripts/auto-audit-static.sh app.apk --semgrep
  263. # Or via frida-exploit-helper.py
  264. python3 scripts/07-tools/frida-exploit-helper.py -p com.target.app --runtime-defense
  265. # List available detectors
  266. bash scripts/02-rasp/runtime-defense-analyzer.sh --list
  267. # Run with active bypass mode (attempt to bypass detections)
  268. bash scripts/02-rasp/runtime-defense-analyzer.sh app.apk com.target.app --active-mode --authorized-lab
  269. ```
  270. **Available detector catalog** (18 entries: 14 executable detectors + 4 not-applicable backend/cloud entries):
  271. - `rootbeer` — RootBeer library detection
  272. - `safetynet` — SafetyNet attestation
  273. - `emulator` — Emulator detection
  274. - `debug` — Debugger detection
  275. - `frida-detect` — Frida detection
  276. - `screenshot` — Screenshot prevention detection
  277. - `screenrecorded` — Screen recording detection
  278. - `talsec`, `approov`, `dexguard`, `appdome`, `doverunner`, `digitalai` — commercial RASP/shielding detection
  279. - `contrast`, `imperva`, `dynatrace`, `accuknox` — cataloged as not-applicable for direct Android APK detection
  280. **Output**: `findings-rda.json` with detector results
  281. > **Reference**: `scripts/02-rasp/README.md` for detailed detector documentation.
  282. ### Drozer IPC Probing
  283. Complement static component mapping with binder-level interaction via drozer (providers, activities, services, receivers):
  284. ```bash
  285. # Safe enumeration only (default)
  286. bash scripts/07-tools/drozer-automated.sh -p com.target.app
  287. # Print exact commands without running them
  288. bash scripts/07-tools/drozer-automated.sh -p com.target.app --print-commands
  289. # Exploitation probes (SQLi strings, path traversal) — authorized lab only
  290. bash scripts/07-tools/drozer-automated.sh -p com.target.app --authorized-lab
  291. ```
  292. **Output**: `drozer-findings.json` (`source: drozer`) + `drozer-report.md` with raw per-stage evidence.
  293. > **Reference**: `references/drozer-ipc-playbook.md` for the component-by-component playbook.
  294. ### Firebase Exposure Check (Authorized Assets Only)
  295. Automated verification of Firebase URLs/API keys extracted from the APK (shallow reads only, no writes):
  296. ```bash
  297. # From APK sources/resources
  298. bash scripts/07-tools/firebase-check.sh -a app.apk -o firebase/
  299. # Direct URL or offline key extraction
  300. bash scripts/07-tools/firebase-check.sh -u "https://proj.firebaseio.com" -o firebase/
  301. bash scripts/07-tools/firebase-check.sh -a app.apk --offline
  302. ```
  303. **Verdicts**: HTTP 200 on `/.json?shallow=true` = open DB (Critical); 401/403 = secured; `--offline` emits informational key-inventory findings only.
  304. > **Reference**: `references/firebase-security.md` → automated verification section.
  305. ### ADB Backup Extraction
  306. Test what an attacker with USB/PC access can extract when `allowBackup` is enabled:
  307. ```bash
  308. # Interactive: triggers adb backup on the connected device
  309. bash scripts/07-tools/adb-backup-extract.sh -a com.target.app
  310. # Parse an existing .ab file (24-byte header, zlib)
  311. bash scripts/07-tools/adb-backup-extract.sh --from-file backup.ab -o backup-audit/
  312. ```
  313. **Output**: `backup-findings.json` (`source: adb`) + verdict on backup sensitivity. Encrypted backups exit code 3 (unsupported, by design).
  314. > **References**: `references/adb-backup-enterprise.md` for the .ab format, MDM/work-profile surface, and the enterprise checklist.
  315. ### Elite Dynamic Techniques
  316. gRPC interception, SMS/OTP interception testing, rootless Play Integrity bypass paths (LSPatch, Zygisk+PIF), emulator-vs-device decision matrix, and greybox coverage via the repo's tracer scripts:
  317. > **Reference**: `references/advanced-dynamic-techniques.md`.
  318. ### Authorized RASP Bypass Validation
  319. After RDA detection, use the DRY bypass runner instead of duplicating Frida logic per detector:
  320. ```bash
  321. # List reusable bypass profiles
  322. bash scripts/02-rasp/rasp-bypass-runner.sh --list-profiles
  323. # Build a reviewed command from detector names
  324. bash scripts/02-rasp/rasp-bypass-runner.sh \
  325. --package com.target.app \
  326. --detectors rootbeer,frida_detect,talsec \
  327. --print-command
  328. # Execute only in an authorized lab
  329. bash scripts/02-rasp/rasp-bypass-runner.sh \
  330. --package com.target.app \
  331. --from-rda findings-rda.json \
  332. --run --authorized-lab
  333. ```
  334. The single source of truth is `scripts/02-rasp/bypass-profiles.json`; the runner reuses scripts under `assets/frida-scripts/`. Do not copy bypass logic into detector files. See `references/rasp-bypass-workflow.md` for coverage, limits, and reporting requirements.
  335. ### Frida Integration
  336. ```bash
  337. # Spawn app with hook
  338. frida -U -f com.example.app -l script.js
  339. # Attach to running process
  340. frida -U com.example.app -l script.js
  341. ```
  342. ### Using frida-exploit-helper.py
  343. The `frida-exploit-helper.py` script provides a convenient wrapper for Frida operations with bundled scripts and common patterns.
  344. **When to use**: Prefer `frida-exploit-helper.py` over direct Frida CLI for:
  345. - Bundled Frida scripts (SSL pinning bypass, root detection bypass, etc.)
  346. - Quick memory operations (read, write, find base address)
  347. - Discovering available scripts
  348. - Simplified Frida workflow
  349. **Examples with bundled scripts**:
  350. ```bash
  351. # SSL pinning bypass
  352. python3 scripts/07-tools/frida-exploit-helper.py -p com.target.app --script ssl-pinning-bypass
  353. # Root detection bypass
  354. python3 scripts/07-tools/frida-exploit-helper.py -p com.target.app --script root-detection-bypass
  355. # List all available bundled scripts
  356. python3 scripts/07-tools/frida-exploit-helper.py --list-scripts
  357. # Display app memory layout (find base addresses)
  358. python3 scripts/07-tools/frida-exploit-helper.py -p com.target.app --layout
  359. # Hook specific functions (malloc, free, etc.)
  360. python3 scripts/07-tools/frida-exploit-helper.py -p com.target.app --hook malloc,free
  361. # Read memory at address
  362. python3 scripts/07-tools/frida-exploit-helper.py -p com.target.app --read 0x12345678 64
  363. # Write to memory address
  364. python3 scripts/07-tools/frida-exploit-helper.py -p com.target.app --write 0x12345678 deadbeef
  365. ```
  366. **Key flags**:
  367. - `-p, --package` — Target package name (required for most operations)
  368. - `--script` — Use bundled script name (use `--list-scripts` to see options) or path to a .js file
  369. - `--spawn` / `-s` — Spawn a new process for the target package
  370. - `--attach` / `-a` — Attach to a running process
  371. - `--list-scripts` — Display all available bundled Frida scripts
  372. - `--layout` — Show memory layout and base addresses
  373. - `--hook` — Comma-separated list of functions to hook
  374. - `--read ADDRESS SIZE` — Read memory at address (hex) with size in bytes
  375. - `--write ADDRESS DATA` — Write data to address (hex). Data can be hex or string
  376. - `--base <library>` — Get base address of specified module (requires library name)
  377. > **Reference**: See `scripts/07-tools/frida-exploit-helper.py --help` for complete options and bundled script catalog.
  378. > **Reference**: bundled Frida scripts in `assets/frida-scripts/`. See `references/frida-scripts-index.md` for the canonical catalog.
  379. > **Focused runtime triage**: use `assets/frida-scripts/android-file-access-monitor.js` for filesystem/storage visibility, `assets/frida-scripts/jni-tracer.js` for JNI/native boundary discovery, and `assets/frida-scripts/ipc-abuse-helper.js` for passive IPC logging plus intentional provider/deep-link validation.
  380. > **Script Maturity Levels**:
  381. > - **STABLE** (with known scope): Production-ready within documented coverage. `ssl-pinning-bypass.js` covers core Java TLS/TrustManager paths (see its header for exact list — not a full universal OkHttp/WebView solution). `root-detection-bypass.js`, `biometric-bypass.js`, `network-interceptor.js`, etc. have broad but not infinite coverage.
  382. > - **BETA**: Functional but incomplete — use with caution
  383. ### JNI Trace (Native Library Tracing)
  384. For advanced JNI and native library analysis, use `jnitrace`:
  385. ```bash
  386. # Install jnitrace
  387. pip install jnitrace
  388. # Trace all JNI functions in a native library (spawn mode)
  389. jnitrace -l libnative-lib.so -m spawn com.target.app
  390. # Trace with attach mode (attach to already-running app)
  391. jnitrace -l libnative-lib.so -m attach com.target.app
  392. # Trace only JNI methods matching a regex (include filter)
  393. jnitrace -l libnative-lib.so -m spawn com.target.app \
  394. -i ".*decrypt.*|.*sign.*"
  395. # Exclude noisy JNI methods
  396. jnitrace -l libnative-lib.so -m spawn com.target.app \
  397. -e "GetStringUTFChars|ReleaseStringUTFChars"
  398. # Hide JNIEnv/JavaVM struct calls to reduce noise
  399. jnitrace -l libnative-lib.so -m spawn com.target.app \
  400. --ignore-env --ignore-vm
  401. # Output trace to JSON file for later analysis
  402. jnitrace -l libnative-lib.so -m spawn com.target.app \
  403. -o trace-output.json
  404. ```
  405. **Programmatic usage** (via npm package):
  406. ```bash
  407. npm install jnitrace-engine
  408. ```
  409. Use `jnitrace` when:
  410. - Analyzing custom JNI bindings
  411. - Understanding native library behavior
  412. - Debugging native crashes
  413. - Tracing crypto operations in native code
  414. > **Note**: `jnitrace` requires the app to be started with Frida spawn mode. For more details, see `references/native-analysis.md` and `jni-tracer.js` for an alternative Frida-based approach.
  415. ### Objection Commands
  416. ```bash
  417. # Modern syntax (preferred): objection -n <package> start
  418. objection -n com.example.app start
  419. # Legacy syntax (deprecated but still works): objection -g <package> explore
  420. objection -g com.example.app explore
  421. # Enumerate components
  422. android hooking list activities
  423. android hooking list services
  424. android hooking list receivers
  425. # Bypass protections
  426. android sslpinning disable
  427. # Enumerate Android Keystore entries
  428. android keystore list
  429. ```
  430. ### ADB Runtime Testing
  431. ```bash
  432. # Test exported activity
  433. adb shell am start -n com.example.app/.MainActivity -a android.intent.action.VIEW -d "scheme://host"
  434. # Test exported receiver
  435. adb shell am broadcast -a com.example.app.ACTION -e key "value"
  436. # Monitor logs
  437. adb logcat | grep com.example.app
  438. ```
  439. > **SSL Pinning bypass**: `references/dynamic-analysis-setup.md` + `assets/frida-scripts/ssl-pinning-bypass.js`
  440. > **Split APK / AAB runtime handling**: `references/dynamic-analysis-setup.md#9-split-apk--aab-runtime-handling` for `pm path`, `adb install-multiple`, and `bundletool` workflows.
  441. > **RASP bypass**: `references/rasp-bypass.md` + `assets/frida-scripts/native-root-detection-probe.js` for anti-debug, anti-frida, emulator detection, and native root-check escalation.
  442. > **Protected-app fallback**: `references/packer-modern-unpacking.md#protected-app-fallback-decision-tree` for runtime extraction, spawn-mode instrumentation, embedded instrumentation fallback, and static-only coverage handling.
  443. > **Sandbox audit**: `scripts/07-tools/inspect-app-sandbox.sh <pkg> <out>` pulls `/data/data/<pkg>` from a rooted device/emulator via tar-over-adb and audits plaintext credentials, world-readable files, and unencrypted databases (findings `source=sandbox`).
  444. > **Logcat leak monitor**: `python3 scripts/07-tools/live-logcat-analyzer.py --package <pkg> --output findings.json [--duration 120]` streams logcat, detects tokens/PII/stack traces with redaction, and emits `source=logcat` findings.
  445. ---
  446. ## Phase 5 — Classification and Reporting
  447. ### Compliance Score (Optional)
  448. Generate a MASVS v2 compliance score alongside CVSS findings:
  449. ```bash
  450. # Generate MASVS compliance score
  451. python3 scripts/05-scoring/calculate-score.py findings.json --json-output > score.json
  452. # Generate full report with MASVS score
  453. python3 scripts/07-tools/generate-report.py --input findings.json --masvs --output report.html
  454. # Use custom MASVS mapping
  455. python3 scripts/07-tools/generate-report.py --input findings.json --masvs --masvs-mapping scripts/05-scoring/masvs-mapping.json --output report.html
  456. ```
  457. **Scoring methodology**:
  458. - 23 MASVS v2 controls assessed
  459. - Weighted deduction based on severity (Critical×10, High×5, Medium×2, Low×1)
  460. - Final score: 0–100 with letter grade (A/B/C/D/F)
  461. **Grade thresholds**:
  462. - A: 90–100 (Excellent)
  463. - B: 80–89 (Good)
  464. - C: 70–79 (Acceptable)
  465. - D: 60–69 (Poor)
  466. - F: 0–59 (Critical)
  467. > **References**: `scripts/05-scoring/README.md` and `references/masvs-scoring-model.md` for control definitions, mapping semantics, and not-tested handling.
  468. ### Executive Risk Score (Optional)
  469. When generating an executive report, include an aggregate risk score only after deduplication and confidence triage. Use `references/risk-score-model.md` to keep this separate from CVSS and MASVS:
  470. - CVSS = severity of individual vulnerabilities
  471. - MASVS = control coverage/compliance posture
  472. - Executive risk score = aggregate operational exposure and coverage gaps
  473. Do not deduct score for rejected false positives. Treat unresolved protected code, missing splits, or skipped dynamic validation as coverage gaps rather than confirmed vulnerabilities.
  474. ### OSINT Enrichment (Optional)
  475. If the engagement scope allows passive reconnaissance, enrich Phase 5 with `references/osint-apk-recon.md`:
  476. 1. Correlate package name, app label, first-party domains, endpoints, and redacted secret fingerprints.
  477. 2. Search passive public sources only unless active probing is explicitly authorized.
  478. 3. Classify domains as first-party, likely first-party, third-party SDK, or unknown before reporting.
  479. 4. Promote OSINT evidence only when it supports an in-scope app finding or public exposure claim.
  480. ### Confidence Levels
  481. | Level | Definition | Example Evidence |
  482. |-------|-----------|------------------|
  483. | **Confirmed** | Full source-to-sink trace validated | Direct call chain from IPC source to `Runtime.exec()` with no sanitization |
  484. | **Likely** | Strong evidence, minor gaps | Static trace clear but reflection obscures final sink |
  485. | **Needs Dynamic Confirmation** | Static analysis inconclusive | Obfuscated code or native boundary requiring runtime verification |
  486. ### Severity
  487. Use CVSS 4.0. See `references/cvss-scoring-guide.md` for complete methodology and severity mapping.
  488. ### Finding Template
  489. ```markdown
  490. ## [ID] - [Title]
  491. **Confidence**: [Confirmed/Likely/Needs Dynamic Confirmation]
  492. **Severity**: [Critical/High/Medium/Low] (CVSS: [X.X])
  493. **CWE**: [CWE-ID]
  494. **OWASP**: [OWASP Category]
  495. ### Description
  496. [1-2 sentences explaining what the vulnerability is]
  497. ### Affected Components
  498. - **File**: `path/to/file.java`
  499. - **Method**: `methodName()`
  500. - **Component**: `[Activity/Service/Receiver/Provider]` (if applicable)
  501. ### Attack Scenario
  502. 1. Attacker [action, e.g., sends malicious intent with crafted data]
  503. 2. App [processing step, e.g., extracts parameter without validation]
  504. 3. Data propagates through [call chain]
  505. 4. Reaches sink [dangerous operation]
  506. 5. Results in [impact, e.g., arbitrary command execution]
  507. ### Proof of Concept
  508. ```bash
  509. adb shell am start -n com.example.app/.MainActivity \
  510. -a android.intent.action.VIEW \
  511. -d 'exploit://host/path?payload=cmd%7Ccat%20/data/data/com.example.app/databases/db'
  512. ```
  513. Or provide Frida hook script for dynamic verification.
  514. ### Impact
  515. - **Confidentiality**: [High/Medium/Low/None] — [explanation]
  516. - **Integrity**: [High/Medium/Low/None] — [explanation]
  517. - **Availability**: [High/Medium/Low/None] — [explanation]
  518. ### Remediation
  519. ```java
  520. // Provide secure code example
  521. Intent intent = getIntent();
  522. if (intent != null && intent.getData() != null) {
  523. String input = intent.getData().getQueryParameter("path");
  524. if (isValidPath(input)) {
  525. loadUrl(input);
  526. } else {
  527. Log.w(TAG, "Invalid path detected");
  528. }
  529. }
  530. private boolean isValidPath(String path) {
  531. return path != null && !path.contains("..") &&
  532. path.matches("^/safe/\\w+\\.html$");
  533. }
  534. ```
  535. ### CVSS 4.0 Calculation
  536. [Show vector string and score breakdown]
  537. ```
  538. ### Coverage Statement
  539. End your report with:
  540. ```
  541. Coverage Analysis:
  542. - Static Analysis: Complete (all decompiled sources analyzed)
  543. - Dynamic Analysis: [Complete/Partial/Not Performed] (reason if partial)
  544. - Scope: [com.example.app.* namespace only]
  545. - Framework: [React Native/Flutter/Native/Standard]
  546. - Obfuscation: [ProGuard/R8/DexGuard/Custom/None]
  547. Limitations:
  548. - [List any limitations, e.g., "Native code analysis requires additional tools"]
  549. - [Any components that could not be analyzed]
  550. - [Any findings requiring additional verification]
  551. Total Findings: X (Critical: Y, High: Z, Medium: A, Low: B)
  552. ```
  553. > **Reference**: `references/reporting-templates.md` for executive summary format, remediation priority matrix, and presentation templates.
  554. ### Automated Report Generation
  555. Use the `generate-report.py` script to generate professional HTML or Markdown reports from findings JSON:
  556. ```bash
  557. # Generate HTML report
  558. python3 scripts/07-tools/generate-report.py \
  559. --input findings.json \
  560. --output report.html \
  561. --app-name "My App" \
  562. --package-name "com.example.app"
  563. # Generate Markdown report
  564. python3 scripts/07-tools/generate-report.py \
  565. --input findings.json \
  566. --output report.md \
  567. --app-name "My App" \
  568. --package-name "com.example.app"
  569. ```
  570. The script supports both JSON array format and JSONL (one finding per line) and automatically:
  571. - Sorts findings by severity (Critical first)
  572. - Calculates CVSS 4.0 severity scores
  573. - Generates executive summary with risk rating
  574. - Maps OWASP MASTG categories
  575. - Provides formatted proof of concept and remediation sections
  576. See `scripts/test-findings.json` for the expected JSON structure. The normative contract is `references/schemas/finding.schema.json` — every emitter script validates findings against it.
  577. ---
  578. ## APK Modification Workflow
  579. ### 1. Decode
  580. ```bash
  581. apktool d app.apk -o app-modified/
  582. ```
  583. ### 2. Modify — Smali Patching
  584. Edit smali files in `app-modified/smali/`:
  585. ```smali
  586. .method public checkSecurity()Z
  587. .locals 1
  588. # Original: iget-boolean v0, p0, Lcom/example/App;->securityEnabled:Z
  589. # Patched — always return true
  590. const/4 v0, 0x1
  591. return v0
  592. .end method
  593. ```
  594. #### Resource Modification
  595. Edit XML or resource files in `app-modified/res/`:
  596. ```xml
  597. <!-- Example: enable debug flag -->
  598. <bool name="debug_mode">true</bool>
  599. ```
  600. ### 3. Rebuild
  601. ```bash
  602. apktool b app-modified/ -o app-modified.apk
  603. ```
  604. ### 4. Sign
  605. ```bash
  606. # Generate keystore (first time only)
  607. keytool -genkeypair -v -keystore my-release-key.jks -alias androiddebugkey -keyalg RSA -keysize 2048 -validity 10000
  608. # Align first
  609. zipalign -v 4 app-modified.apk app-aligned.apk
  610. # Sign (apksigner supports v1, v2, v3, v3.1 signatures)
  611. # Verify keystore exists before signing
  612. if [ ! -f "my-release-key.jks" ]; then
  613. echo "Error: Keystore not found. Create it with keytool first."
  614. exit 1
  615. fi
  616. # --ks-key-alias is required when the keystore contains multiple keys; recommended in all cases
  617. apksigner sign \
  618. --ks my-release-key.jks \
  619. --ks-key-alias androiddebugkey \
  620. --ks-pass pass:myPassword \
  621. --key-pass pass:myPassword \
  622. --out app-signed.apk \
  623. app-aligned.apk
  624. # Verify signature
  625. apksigner verify --verbose app-signed.apk
  626. ```
  627. ### 5. Install and Verify
  628. Preferred (android-cli present — delta-install speeds up smali patch → test iteration):
  629. ```bash
  630. android install --apks=app-signed.apk --device=<serial>
  631. ```
  632. Fallback (no android-cli):
  633. ```bash
  634. adb install -r app-signed.apk
  635. ```
  636. Source `scripts/lib/android-cli-or-fallback.sh` and call `android_install app-signed.apk` to get the switch automatically.
  637. > **Reference**: `references/dynamic-analysis-setup.md` for advanced repackaging, signature verification bypass, and ADB debugging. See `references/apk-modification-guide.md` for smali editing edge cases and troubleshooting.
  638. ---
  639. ## Troubleshooting
  640. ### APK Decoding Fails
  641. ```bash
  642. apktool d -f app.apk -o decoded/ # Force mode (re-decodes even if output dir exists)
  643. aapt2 dump badging app.apk # Verify APK integrity
  644. apkid app.apk # Detect packer/protector
  645. ```
  646. > Note: Apktool 3.0+ removed the `-api`/`--api-level` flag. The API level is now auto-detected from the APK.
  647. If packed → see `references/packing-unpacking.md` for unpacking techniques.
  648. ### JADX Shows Bad Code
  649. ```bash
  650. jadx --show-bad-code -v app.apk # Show code even with errors
  651. jadx --decompilation-mode fallback app.apk
  652. jadx-gui app.apk # GUI for manual inspection
  653. ```
  654. ### Frida Cannot Attach
  655. ```bash
  656. adb shell ps -A | grep frida
  657. adb shell getprop ro.product.cpu.abi
  658. adb shell "su -c 'killall frida-server'"
  659. adb shell "su -c '/data/local/tmp/frida-server -D &'"
  660. ```
  661. > Full setup: `references/dynamic-analysis-setup.md`
  662. ### Obfuscated Code Unreadable
  663. - Identify obfuscator: `apkid app.apk`
  664. - Enable JADX deobfuscation: `jadx --deobf app.apk`
  665. - See `references/static-analysis-patterns.md` → "Obfuscation Patterns"
  666. - Switch to Phase 4 for runtime behavior
  667. ### When to Escalate to Dynamic Analysis
  668. Static analysis reaches limits when: obfuscation unclear, reflection, JNI boundaries, anti-debug/root detection, SSL pinning. → Proceed to Phase 4 using `references/dynamic-analysis-setup.md`.
  669. ---
  670. ## Examples
  671. ### Example 1: Quick Assessment
  672. `com.example.app.apk` → Decode → Framework detect → Manifest audit → Secrets grep → CVSS report
  673. ### Example 2: SSL Pinning Bypass
  674. `frida -U -f com.target.app -l ssl-pinning-bypass.js` → See `references/rasp-bypass.md` if fails
  675. ### Example 3: APK Repackaging
  676. Decode → Modify → Rebuild → Sign → Install (see `references/apk-modification-guide.md`)
  677. ---
  678. ## Agent Operating Contract
  679. This contract defines what every audit must produce, when to advance, when to stop, and how to report findings.
  680. ### Required Audit Artifacts
  681. For every APK audit, produce these artifacts:
  682. | Artifact | Phase | Description |
  683. |----------|-------|-------------|
  684. | `scope.json` | -1 | Package name, target scope, authorization confirmation |
  685. | `toolchain-report.json` | 0 | Tool versions, availability, preflight results |
  686. | `app-profile.json` | 0 | Framework, obfuscation, architecture |
  687. | `attack-surface.json` | 1 | Exported components, deep links, permissions |
  688. | `findings.json` | 2-4 | All findings in standard schema |
  689. | `evidence/` | 2-4 | Screenshots, logs, PoC commands |
  690. | `coverage-matrix.json` | 5 | MASVS control coverage status |
  691. | `final-report.html` | 5 | Executive summary + technical findings |
  692. ### Stop Conditions — STOP AND REPORT IMMEDIATELY
  693. | Condition | Action |
  694. |-----------|--------|
  695. | APK decode fails | Report `DECODE_FAILURE` with error log |
  696. | Package name cannot be determined | Report `SCOPE_UNCLEAR` and stop |
  697. | Target namespace cannot be isolated | Report `SCOPE_TOO_BROAD` |
  698. | Dynamic testing requested but no Frida/device | Mark findings `Needs Dynamic Confirmation` |
  699. | Encrypted/packed APK blocks analysis | Report `PACKED_APK` with partial coverage |
  700. ### Finding States
  701. | State | When to Use | CVSS Required |
  702. |-------|-------------|---------------|
  703. | **Confirmed** | Full source-to-sink trace validated | Yes |
  704. | **Likely** | Strong evidence, minor gaps in trace | Yes |
  705. | **Needs Dynamic Confirmation** | Static inconclusive (obfuscation, reflection, JNI) | TBD |
  706. | **Informational** | Best practice violation, low risk | Optional |
  707. | **Rejected** | Previously reported, confirmed false positive | N/A |
  708. ### APK Type Handling
  709. | Type | Analysis Approach |
  710. |------|------------------|
  711. | **Standard APK** | Full 6-phase workflow |
  712. | **Split APK / AAB** | Phase 0 → detect base vs dynamic features, pull/install full split set, analyze each split separately; see `dynamic-analysis-setup.md#9-split-apk--aab-runtime-handling` |
  713. | **Packed/Protected** | Phase 0 → static baseline, runtime extraction/spawn-mode/embedded instrumentation fallback; if blocked → `PACKED_APK` report with coverage gap |
  714. | **React Native** | Phase 0 → extract Hermes bytecode, use `scripts/01-cross-platform/react-native-analysis.sh` |
  715. | **Flutter** | Phase 0 → Blutter analysis, native SSL hooks |
  716. | **Xamarin** | Phase 0 → identify Mono runtime, analyze bundled assemblies |
  717. | **Obfuscated** | Phase 2 → enhanced grep + Phase 4 dynamic if available |
  718. ### Evidence Standards
  719. Every finding must have:
  720. 1. **File + line reference** (or Frida trace for dynamic)
  721. 2. **Evidence snippet** (relevant code/data)
  722. 3. **Attack scenario** (how attacker exploits)
  723. 4. **CVSS 4.0 vector** (Confirmed/Likely) or `TBD` (Needs Dynamic)
  724. ### Coverage Declaration
  725. End every report with:
  726. ```json
  727. {
  728. "coverage": {
  729. "static_analysis": "complete | partial | not-performed",
  730. "dynamic_analysis": "complete | partial | not-performed",
  731. "framework": "react-native | flutter | cordova | xamarin | native",
  732. "obfuscation": "proguard | dexguard | custom | none",
  733. "native_code": "analyzed | not-analyzed | not-applicable",
  734. "rasp": "detected | not-detected | not-tested"
  735. },
  736. "total_findings": { "critical": 0, "high": 0, "medium": 0, "low": 0 }
  737. }
  738. ```
  739. ---
  740. ## References Index
  741. | Phase | Files | Phase | Files |
  742. |-------|-------|-------|-------|
  743. | 0 | `environment-setup`, `opencode-tooling`, `static-analysis-patterns`, `hybrid-webview-frameworks`, `kotlin-patterns`, `kotlin-async-security`, `kotlin-compose-security`, `kotlin-multiplatform-security`, `malware-analysis`, `tool-installation` | 3 | `attack-patterns`, `intent-injection`, `pendingintent-security`, `firebase-security`, `deep-link-exploitation`, `real-world-android-vulnerabilities` |
  744. | 1 | `android-manifest-checklist`, `android-version-security`, `android-14-15-security-changes`, `android-15-security-guide`, `android-16-security-guide`, `androidx-security-migration`, `secure-storage-migration`, `data-storage-auditing` | 4 | `dynamic-analysis-setup`, `native-code-analysis`, `native-analysis`, `rasp-bypass`, `rasp-bypass-workflow`, `packing-unpacking`, `packer-modern-unpacking`, `react-native-hermes-analysis`, `frida-version-matching-guide`, `android-keystore2-testing`, `biometric-testing-comprehensive`, `frida-advanced-patterns`, `android-anti-frida-countermeasures` |
  745. | 2 | `dependency-analysis`, `supply-chain-security` | 5 | `cvss-scoring-guide`, `cvss-calculator`, `reporting-templates`, `finding-template-cards`, `finding-quality-triage`, `masvs-scoring-model`, `risk-score-model`, `osint-apk-recon`, `audit-modes`, `frida-scripts-index`, `cheat-sheet-commands`, `cheat-sheet-frida-scripts` | Schemas | `schemas/finding.schema.json` (canonical finding contract), `schemas/audit-report.schema.json` (final report) |
  746. | Mod | `apk-modification-guide`, `modern-android-coverage` | FW | `react-native-security`, `react-native-new-arch`, `flutter-security`, `flutter-blutter-analysis`, `jetpack-compose-security-deep-dive`, `fuzzing-guide`, `passkey-fido2-security`, `mobsf-integration` |
  747. | CI | `automation-scripts`, `ci-cd-integration` | AI | `ai-pentesting-guide`, `ai-prompts/java-security-analyzer`, `ai-prompts/native-binary-analyzer`, `ai-prompts/exploit-generator`, `ai-prompts/report-enhancer` |
  748. | Plat | `scripts/04-android-15-16/android15-apis.js`, `scripts/04-android-15-16/passkey-test.js`, `scripts/04-android-15-16/privacy-sandbox-test.sh` | Ker | `android-binder-cve-2023-20938` |
  749. | All | `mastg-quick-reference`, `mastg-best-practices`, `mastg-privacy-testing`, `quick-commands`, `quick-start-guide`, `workflow-diagram`, `cross-platform-testing-setup`, `play-integrity-api-testing`, `burp-mobsf-integration-guide` |
  750. **Scripts**:
  751. - `scripts/01-cross-platform/` — Framework-specific analysis (Cordova, Flutter, React Native, Unity)
  752. - `scripts/02-rasp/` — Runtime Defense Analysis (RDA)
  753. - `scripts/03-static-analysis/` — semgrep scan + merge-findings
  754. - `scripts/04-android-15-16/` — Android 15/16 specific APIs
  755. - `scripts/05-scoring/` — MASVS v2 compliance scoring
  756. - `scripts/06-setup/` — preflight-check + validation. Validate the skill itself after changes: `bash scripts/06-setup/validate-frida-scripts.sh` (all `assets/frida-scripts/*.js` + RASP detectors) and `bash scripts/06-setup/validate-shell-scripts.sh` (all `*.sh`).
  757. - `scripts/07-tools/` — Core tools (frida-exploit-helper, generate-report, correlate-findings, mobsf-api-scan, burp-findings-export, rop-helper)
  758. - `auto-audit-static.sh` — Main orchestrator
  759. - `audit-android-components.sh` — Component audit
  760. **Exploitation**: `exploitation-guide`, `heap-exploitation`, `exploitation-decisions`, `android-binder-cve-2023-20938`
  761. **RASP bypass**: `scripts/02-rasp/rasp-bypass-runner.sh` uses `scripts/02-rasp/bypass-profiles.json` to compose reusable Frida bypass stacks. See `references/rasp-bypass-workflow.md`.
  762. **Assets**: Frida scripts in `assets/frida-scripts/` (see `references/frida-scripts-index.md`); full file inventory is in [`references/project-manifest.md`](references/project-manifest.md)
  763. > **Loading Strategy**: Load reference files only when encountering the specific technical challenge they cover. Do NOT load all references at once.
  764. > **Self-verification**: `benchmarks/` runs the audit pipeline against known-vulnerable canary APKs (InsecureBankv2, OWASP MASTG) and emits a CWE-coverage scorecard. Run it before claiming coverage improvements: `bash benchmarks/run-benchmark.sh`. See [`benchmarks/README.md`](benchmarks/README.md).
  765. ---
  766. ## Platform-Specific Notes
  767. > See `references/environment-setup.md` for detailed Windows (PowerShell), macOS, and Linux setup. On macOS, use `rg` (ripgrep) instead of `grep -P` — BSD grep does not support PCRE.
  768. ## Known Implementation Gaps (as of remediation pass, April 2026)
  769. The following gaps were identified and partially mitigated during a full code + claims audit:
  770. - **Semgrep integration** (Phase 2.5): Previously completely non-functional (no `--json` flag was passed). Now fixed in `semgrep-scan.py`.
  771. - **Preflight in agent contexts**: Interactive safety/scope prompts would hang or fail under `--json` / non-TTY. Now auto-skips with clear notes when run by agents/CI.
  772. - **Frida bypass coverage claims**: Several "STABLE" / "30+ implementations" statements (especially `ssl-pinning-bypass.js`) were overstated vs. actual code. Script headers and key docs have been qualified; the script itself is now honest about scope.
  773. - **Shell error handling**: Multiple blanket `&>/dev/null` and unquoted loops existed (especially in `audit-android-components.sh`). Critical decode path now uses `run_logged` helper with real log capture + timeouts. More work remains on other heavy-tool calls.
  774. - **DRY / shared library**: `scripts/lib/` (findings schema, normalizers, MASVS helpers) was mostly dead code due to import hacks. Partial wiring started; full centralization of the 5–6 duplicated `load_findings` implementations is still pending.
  775. - **Committed artifacts**: Many `__pycache__/` and `*.pyc` files were present. `.gitignore` has been expanded.
  776. These are tracked in the remediation plan for this change. Always run the preflight + validators before trusting a full audit in a new environment.
  777. > **Update 2026-09-23**: the full gap matrix (inventory vs. external methodology, with disposition per gap) lives in [`references/skill-gap-analysis.md`](references/skill-gap-analysis.md) — consult it before opening new remediation work.
  778. > The skill prioritizes **honest, reproducible results over impressive-sounding claims**. When in doubt, mark "Needs Dynamic Confirmation" and surface coverage gaps explicitly.
README.md · README · 537 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # Android Pentesting Skill
  2. [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
  3. [![Version](https://img.shields.io/badge/version-1.9.0-green.svg)](https://github.com/DragonJAR/Android-Pentesting-Skill/blob/main/SKILL.md)
  4. [![Skill iOS](https://img.shields.io/badge/iOS-Pentesting%20Skill-3DDC84.svg)](https://github.com/DragonJAR/iOS-Pentesting-Skill)
  5. [![Author](https://img.shields.io/badge/author-DragonJAR%20SAS-orange.svg)](https://www.DragonJAR.org)
  6. [![Español](https://img.shields.io/badge/read%20in-Espa%C3%B1ol-blue.svg)](README.es.md)
  7. > World-class Android pentesting skill for AI agents. It combines static analysis, dynamic instrumentation, RASP detection, authorized bypass validation, source-to-sink tracing, MASVS scoring, and professional reporting in one DRY workflow.
  8. ## 🎯 What This Skill Does
  9. This skill turns an AI agent into an Android APK security auditor. It can:
  10. - Decode and inspect APKs with APKTool, JADX, APKiD, Android SDK tools, and Frida.
  11. - Map attack surface: manifest, exported components, deep links, WebViews, storage, crypto, networking, native code, and framework-specific code.
  12. - Run static analysis with curated grep patterns and MASTG-aligned Semgrep rules, then merge and deduplicate findings.
  13. - Trace source-to-sink flows and separate confirmed issues from findings that need dynamic validation.
  14. - Detect runtime defenses and RASP/shielding SDKs, then build authorized Frida bypass stacks using reusable profiles instead of duplicated logic.
  15. - Validate common client-side protections such as SSL pinning, root/debug/emulator checks, anti-Frida, FLAG_SECURE, RASP callbacks, and packer/native checks where technically feasible.
  16. - Score and report findings with CVSS 4.0, MASVS mapping, executive risk context, JSON schemas, and professional report templates.
  17. - Support APK modification workflows: smali/resource patching, repackaging, signing, and validation.
  18. - Ingest APKs from a read-only Gmail mailbox (optional OAuth adapter) and audit on-device `/data/data` storage on rooted lab devices.
  19. > **Important:** Client-side hooks do not forge server-side attestation verdicts. For Approov, Play Integrity, SafetyNet, or similar backend-enforced controls, use an authorized test tenant, backend allowlist, mock verifier, or approved lab configuration.
  20. ## 📦 Installation
  21. ### Option 1: Clone into Agent Skills Directory
  22. ```bash
  23. # For Claude Code / OpenCode agents
  24. cd ~/.agents/skills/
  25. git clone https://github.com/DragonJAR/Android-Pentesting-Skill Android-Pentesting-Skill
  26. # For other agents, place in your skills directory
  27. ```
  28. ### Option 2: Install Globally
  29. ```bash
  30. # Clone to any location
  31. git clone https://github.com/DragonJAR/Android-Pentesting-Skill.git
  32. # Add to your agent's skill path configuration
  33. ```
  34. ## ⚙️ Prerequisites
  35. The skill expects these tools to be installed:
  36. | Tool | Version | Purpose |
  37. |------|---------|---------|
  38. | APKTool | 3.0.1+ | APK decoding/rebuilding (aapt2-only mode) |
  39. | JADX | 1.5.5+ | Java/Kotlin decompilation |
  40. | Android SDK | Platform 36+, Build 36+ | adb, aapt2, zipalign, apksigner |
  41. | Frida | 17.9+ | Dynamic instrumentation |
  42. | Objection | 1.12.4+ | Mobile exploration (maintenance mode) |
  43. | APKiD | 3.0.0+ | Framework detection |
  44. ### Verification
  45. Run the Python preflight check to verify all dependencies:
  46. ```bash
  47. python3 scripts/06-setup/preflight-check.py
  48. ```
  49. Shell variant for Linux or macOS with Homebrew Bash 4+:
  50. ```bash
  51. /opt/homebrew/bin/bash scripts/06-setup/preflight-check.sh
  52. ```
  53. Or, on systems where `/usr/bin/env bash` is Bash 4+:
  54. ```bash
  55. ./scripts/06-setup/preflight-check.sh
  56. ```
  57. PowerShell variant for Windows environments:
  58. ```powershell
  59. ./scripts/06-setup/preflight-check.ps1
  60. ```
  61. ## 🛡️ RASP Detect → Bypass Workflow
  62. The RASP workflow is intentionally DRY:
  63. 1. **Detect** protections with RDA.
  64. 2. **Map** triggered detectors to bypass profiles.
  65. 3. **Reuse** existing Frida scripts from `assets/frida-scripts/`.
  66. 4. **Print first, run only when authorized** with `--run --authorized-lab`.
  67. ```bash
  68. # 1) Detect RASP/runtime defenses
  69. bash scripts/02-rasp/runtime-defense-analyzer.sh app.apk com.target.app --output findings-rda.json
  70. # 2) Review available bypass profiles
  71. bash scripts/02-rasp/rasp-bypass-runner.sh --list-profiles
  72. # 3) Generate a reviewed Frida command from findings
  73. bash scripts/02-rasp/rasp-bypass-runner.sh \
  74. --package com.target.app \
  75. --from-rda findings-rda.json \
  76. --print-command
  77. # 4) Execute only in an authorized lab
  78. bash scripts/02-rasp/rasp-bypass-runner.sh \
  79. --package com.target.app \
  80. --from-rda findings-rda.json \
  81. --run --authorized-lab
  82. ```
  83. Profiles live in `scripts/02-rasp/bypass-profiles.json` and reuse existing Frida scripts under `assets/frida-scripts/`. See `references/rasp-bypass-workflow.md` for coverage, limits, and reporting requirements.
  84. ## 🚀 Usage Examples
  85. ### Example 1: Basic APK Audit
  86. **User prompt:**
  87. ```
  88. Audit this APK: /path/to/app.apk
  89. ```
  90. **Agent response:**
  91. ```
  92. I'll analyze the APK for security vulnerabilities.
  93. [Phase 0] Decoding APK with APKTool...
  94. [Phase 1] Analyzing AndroidManifest.xml...
  95. [Phase 2] Running targeted security patterns...
  96. [Phase 3] Tracing data flows...
  97. [Phase 5] Generating findings report...
  98. Found 3 issues:
  99. 1. [HIGH] Exported Activity Without Permission (M8: Security Misconfiguration)
  100. 2. [MEDIUM] Hardcoded API Key (M1: Improper Credential Usage)
  101. 3. [LOW] Debug Logging Enabled (M8: Security Misconfiguration)
  102. ```
  103. ### Example 2: Full Audit with All Modules
  104. **User prompt:**
  105. ```
  106. Audit this APK with all modules: runtime defense, semgrep, and MASVS scoring.
  107. ```
  108. **Agent response:**
  109. ```
  110. [Phase 0] Decoding APK with APKTool + JADX...
  111. [Phase 0] Detected framework: Flutter
  112. [Phase 1] Mapping attack surface from AndroidManifest.xml...
  113. [Phase 2] Running targeted grep patterns...
  114. [Phase 2.5] Running Semgrep MASTG rules (70+ rules)...
  115. [Phase 3] Tracing source-to-sink data flows...
  116. [Phase 4] Running Runtime Defense Analysis (18 catalog entries, 14 executable detectors)...
  117. [Phase 5] Classifying findings and calculating MASVS compliance score...
  118. MASVS Score: 72.6/100 (Grade: C)
  119. - 16/23 controls passed
  120. - 7 controls failed (Critical: 1, High: 1, Medium: 1, Low: 4)
  121. Found 4 issues:
  122. 1. [CRITICAL] Hardcoded API Key (M1: Improper Credential Usage)
  123. 2. [HIGH] Exported Activity with Intent Redirection (M8: Security Misconfiguration)
  124. 3. [MEDIUM] Weak SSL Certificate Validation (M5: Insecure Communication)
  125. 4. [LOW] Debug Mode Enabled (M8: Security Misconfiguration)
  126. ```
  127. ### Example 3: SSL Pinning Bypass
  128. **User prompt:**
  129. ```
  130. The app has SSL pinning. Bypass it with Frida and intercept traffic.
  131. ```
  132. **Agent response:**
  133. ```
  134. I'll use the SSL pinning bypass script to intercept HTTPS traffic.
  135. [1] Identifying SSL pinning implementation...
  136. Found: OkHttp3 CertificatePinner
  137. [2] Loading Frida script: ssl-pinning-bypass.js
  138. [3] Hooking CertificatePinner.check()
  139. [4] SSL pinning bypassed. Traffic now decrypted.
  140. Intercepted request:
  141. POST /api/login
  142. {"email": "user@example.com", "password": "secret123"}
  143. ```
  144. ### Example 4: React Native Analysis
  145. **User prompt:**
  146. ```
  147. Analyze this React Native APK for hardcoded secrets in the JavaScript bundle.
  148. ```
  149. **Agent response:**
  150. ```
  151. [Phase 0] Detected React Native framework (libhermes.so found)
  152. [Phase 0] Extracting JavaScript bundle from assets/index.android.bundle
  153. [Phase 2] Scanning for secrets in JavaScript bundle...
  154. Found 2 hardcoded secrets:
  155. - API_KEY = "sk_live_abc123..." at bundle.js:4521 (M1: Improper Credential Usage)
  156. - AWS_SECRET = "wJalrXUtnFEMI/K7MDENG..." at bundle.js:8912 (M1: Improper Credential Usage)
  157. ```
  158. ### Example 5: Flutter Analysis
  159. **User prompt:**
  160. ```
  161. Analyze this Flutter APK. I need to intercept HTTPS traffic from the app.
  162. ```
  163. **Agent response:**
  164. ```
  165. [Phase 0] Detected Flutter framework (libflutter.so found)
  166. [Phase 0] Flutter uses BoringSSL natively - Java SSL hooks won't work
  167. [Phase 0] Using Blutter to extract Dart code: python3 blutter.py lib/arm64-v8a/
  168. [Phase 4] Loading Frida script: native-hook.js (BoringSSL targets)
  169. [Phase 4] Hooking SSL_CTX_set_custom_verify() for certificate bypass
  170. [Phase 4] Hooking SSL_read/SSL_write() for traffic interception
  171. Flutter traffic now intercepted and decrypted.
  172. ```
  173. ### Example 6: APK Modification
  174. **User prompt:**
  175. ```
  176. Disable the root detection in this APK and repackage it.
  177. ```
  178. **Agent response:**
  179. ```
  180. [1] Decoding APK with APKTool...
  181. [2] Locating root detection code...
  182. Found: com/app/security/RootDetector.checkRoot()
  183. [3] Patching smali to return false...
  184. const/4 v0, 0x0 # Always return false
  185. [4] Rebuilding with APKTool...
  186. [5] Aligning with zipalign...
  187. [6] Signing with apksigner...
  188. [7] Verifying signature...
  189. Modified APK ready: app_patched.apk
  190. SHA-256: abc123def456...
  191. ```
  192. ### Example 7: Runtime Defense Analysis
  193. **User prompt:**
  194. ```
  195. Run the runtime defense analysis to check what protections this app has.
  196. ```
  197. **Agent response:**
  198. ```
  199. [Phase 4] Loading Runtime Defense Analysis...
  200. Detector catalog: 18 entries (14 executable Frida detectors + 4 backend/cloud entries marked not applicable).
  201. Executable detectors include:
  202. - rootbeer, safetynet, emulator, debug, frida_detect
  203. - screenshot, screenrecorded, custom
  204. - talsec, approov, dexguard, appdome, doverunner, digitalai
  205. Running passive detection...
  206. Results: 3 protections detected:
  207. - [DETECTED] Root detection (RootBeer library)
  208. - [DETECTED] Emulator detection
  209. - [NOT DETECTED] Frida detection
  210. findings-rda.json generated with full detector report.
  211. ```
  212. ## 📖 Skill Capabilities
  213. ### Static Analysis (Phases 0-3)
  214. | Capability | Description |
  215. |------------|-------------|
  216. | APK Decompilation | JADX for Java/Kotlin, APKTool for smali/resources |
  217. | Framework Detection | React Native, Flutter, Cordova, Xamarin, Native |
  218. | Obfuscation Analysis | ProGuard/R8, DexGuard, custom patterns |
  219. | Manifest Analysis | 50+ security checks for exported components, permissions, deep links |
  220. | IPC / Intent Abuse | Intent injection, nested intent relays, PendingIntent, FileProvider, deep link pivot patterns |
  221. | Secrets Detection | API keys, passwords, tokens in code and resources |
  222. | Data Flow Tracing | Source-to-sink methodology with confidence levels |
  223. | **Semgrep SAST (Phase 2.5)** | 70+ MASTG-aligned rules for automated code scanning |
  224. ### Dynamic Analysis (Phase 4)
  225. | Capability | Description |
  226. |------------|-------------|
  227. | Frida Scripts | 37 scripts for hooking, bypass, interception, and native triage |
  228. | SSL Pinning Bypass | Java/Conscrypt focused (HttpsURLConnection, TrustManagerImpl etc.). See script header for exact current coverage and gaps (OkHttp, WebView, NSC, Flutter require extra work). |
  229. | Root Detection Bypass | 30+ root packages, 80+ paths, native hooks (fopen, access, stat) plus a focused native root detection probe |
  230. | **Runtime Defense Analysis (RDA)** | 18 catalog entries, 14 executable Frida detectors, and authorized bypass profile runner |
  231. | Crypto Interception | Monitor Cipher, MessageDigest, Mac, Signature operations |
  232. | Biometric Bypass | BiometricPrompt, FingerprintManager, crypto-object binding |
  233. | Keystore Inspection | List entries, extract metadata, check security flags |
  234. | Network Interception | OkHttp chains, HttpURLConnection, WebSocket monitoring |
  235. | Native Hooking | JNI_OnLoad, RegisterNatives, by-offset hooks, and library-load-aware native probes |
  236. ### Frida Exploit Helper
  237. ```bash
  238. # List available bundled scripts
  239. python3 scripts/07-tools/frida-exploit-helper.py --list-scripts
  240. # Hook memory functions
  241. python3 scripts/07-tools/frida-exploit-helper.py -p com.target.app --hook malloc,free
  242. # Use bundled SSL pinning bypass script
  243. python3 scripts/07-tools/frida-exploit-helper.py -p com.target.app --script ssl-pinning-bypass
  244. # Memory layout analysis
  245. python3 scripts/07-tools/frida-exploit-helper.py -p com.target.app --layout
  246. # Runtime Defense Analysis (RDA) — detect app protections
  247. python3 scripts/07-tools/frida-exploit-helper.py -p com.target.app --runtime-defense
  248. ```
  249. ### Full Workflow with All Modules
  250. ```bash
  251. # Run static audit with Semgrep enrichment
  252. bash scripts/auto-audit-static.sh app.apk --semgrep
  253. # Run runtime defenses and scoring as explicit modules
  254. bash scripts/02-rasp/runtime-defense-analyzer.sh app.apk com.target.app --active-mode --authorized-lab --output findings-rda.json
  255. python3 scripts/03-static-analysis/semgrep-scan.py decoded/ --output semgrep.json
  256. python3 scripts/05-scoring/calculate-score.py findings.json --json-output
  257. ```
  258. ### APK Modification
  259. | Capability | Description |
  260. |------------|-------------|
  261. | Smali Patching | Modify Dalvik bytecode directly |
  262. | Resource Editing | Change XML, strings, configurations |
  263. | Static Pinning Tampering | Override `network_security_config`, replace pins, bundled certs, or `BKS/JKS` truststores |
  264. | Repackaging | Rebuild, align, sign with correct flow: zipalign → apksigner |
  265. ### Reporting (Phase 5)
  266. | Capability | Description |
  267. |------------|-------------|
  268. | CVSS 4.0 Scoring | FIRST.org compliant severity ratings |
  269. | **MASVS Compliance Score** | OWASP MASVS v2 control coverage with explicit pass/fail/not-tested semantics |
  270. | Executive Risk Score | Optional aggregate 0-100/A-F business-risk summary, separate from CVSS and MASVS |
  271. | OSINT Enrichment | Optional passive correlation of package, domains, endpoints, public leaks, and archived URLs |
  272. | Audit Modes | Presets for quick, static, full, protected-app, OSINT, and reporting-only workflows |
  273. | OWASP MASTG Mapping | Test IDs and MASVS categories |
  274. | Professional Templates | Executive summary, findings, remediation |
  275. ## 🔧 Skill Structure
  276. ```
  277. Android-Pentesting-Skill/
  278. ├── SKILL.md # Skill definition (Phases 0-5)
  279. ├── references/ # 90 reference/support files
  280. │ ├── attack-patterns.md # OWASP M1-M10 patterns
  281. │ ├── intent-injection.md # Nested intent / confused deputy guide
  282. │ ├── pendingintent-security.md # PendingIntent abuse and hardening
  283. │ ├── dynamic-analysis-setup.md # Frida/Objection + SSL pinning playbook
  284. │ ├── frida-scripts-index.md # Canonical bundled script catalog
  285. │ ├── cvss-scoring-guide.md # CVSS 4.0 methodology
  286. │ ├── reporting-templates.md # Finding templates
  287. │ ├── flutter-security.md # Flutter security guide
  288. │ ├── react-native-security.md # React Native security guide
  289. │ ├── android-keystore2-testing.md # Keystore2 testing (Android 12+)
  290. │ ├── biometric-testing-comprehensive.md # BiometricPrompt testing
  291. │ ├── deep-link-exploitation.md # Deep link attacks
  292. │ ├── project-manifest.md # Ground-truth file inventory
  293. │ └── ... (77 more)
  294. ├── assets/frida-scripts/ # 38 files (37 Frida scripts + README)
  295. │ ├── ssl-pinning-bypass.js # SSL pinning bypass
  296. │ ├── root-detection-bypass.js # Root detection bypass
  297. │ ├── native-root-detection-probe.js # Focused native root/RASP triage
  298. │ ├── native-hook.js # Generic JNI / native helper
  299. │ ├── biometric-bypass.js # Biometric auth bypass
  300. │ ├── network-interceptor.js # HTTP/HTTPS interception
  301. │ ├── crypto-intercept.js # Crypto operations hooking
  302. │ └── ... (30 more)
  303. ├── scripts/ # Utility and validation scripts
  304. │ ├── 00-ingestion/ # Optional input adapters (Gmail APK fetch)
  305. │ │ └── fetch-apk-gmail.py # Read-only Gmail → APK attachment ingester
  306. │ ├── 01-cross-platform/ # Framework-specific analysis
  307. │ │ ├── cordova-analysis.sh
  308. │ │ ├── flutter-analysis.sh
  309. │ │ ├── react-native-analysis.sh
  310. │ │ ├── unity-analysis.sh
  311. │ │ └── dotnet-maui-analysis.sh # MAUI / Xamarin: managed DLL extraction + decompilation
  312. │ ├── 02-rasp/ # Runtime Defense Analysis (RDA)
  313. │ │ ├── detector-catalog.json # 18 detector registry
  314. │ │ ├── runtime-defense-analyzer.sh # Phase 4 RDA entry point
  315. │ │ ├── rasp-bypass-runner.sh # Authorized bypass stack runner
  316. │ │ ├── bypass-profiles.json # DRY detector-to-bypass profile map
  317. │ │ ├── findings-schema.json # Shared findings schema
  318. │ │ └── rasp-detectors/ # 14 Frida detector scripts + 4 not-applicable catalog entries
  319. │ │ ├── rootbeer.js
  320. │ │ ├── safetynet.js
  321. │ │ ├── emulator.js
  322. │ │ ├── debug.js
  323. │ │ ├── frida-detect.js
  324. │ │ ├── screenshot.js
  325. │ │ ├── screenrecorded.js
  326. │ │ └── custom.js
  327. │ ├── 03-static-analysis/ # Semgrep SAST + merge
  328. │ │ ├── semgrep-scan.py # semgrep wrapper
  329. │ │ ├── merge-findings.py # Deduplication
  330. │ │ ├── update-rules.sh # Upstream rule sync
  331. │ │ ├── advanced-static-checks.sh # Beyond-semgrep static hardening probes
  332. │ │ ├── version-diff-audit.sh # Cross-version regression diff
  333. │ │ └── semgrep-rules/ # 70+ MASTG rules
  334. │ ├── 04-android-15-16/ # Android 15/16 specific scripts
  335. │ │ ├── android15-apis.js
  336. │ │ ├── passkey-test.js
  337. │ │ └── privacy-sandbox-test.sh
  338. │ ├── 05-scoring/ # MASVS compliance scoring
  339. │ │ ├── calculate-score.py # Score engine (0-100 + A-F)
  340. │ │ ├── masvs-matrix.json # 23 MASVS v2 controls
  341. │ │ ├── masvs-mapping.json # Finding-to-control mapping
  342. │ │ └── update-coverage.py # Coverage table generator
  343. │ ├── 06-setup/ # Preflight checks & validation
  344. │ │ ├── preflight-check.sh
  345. │ │ ├── preflight-check.py
  346. │ │ ├── preflight-check.ps1
  347. │ │ ├── validate-frida-scripts.sh
  348. │ │ └── validate-shell-scripts.sh
  349. │ ├── 07-tools/ # Core analysis tools
  350. │ │ ├── frida-exploit-helper.py
  351. │ │ ├── generate-report.py
  352. │ │ ├── rop-helper.py
  353. │ │ ├── correlate-findings.py
  354. │ │ ├── mobsf-api-scan.py
  355. │ │ ├── burp-findings-export.py
  356. │ │ ├── adb-backup-extract.sh # Pull /data/data via adb backup (no root)
  357. │ │ ├── drozer-automated.sh # Drozer IPC automation
  358. │ │ ├── firebase-check.sh # Firebase misconfiguration sweep
  359. │ │ ├── inspect-app-sandbox.sh # /data/data audit (rooted device/emulator)
  360. │ │ └── live-logcat-analyzer.py # Streaming logcat leak detector (tokens/PII/stack traces)
  361. │ ├── lib/ # Shared library (DRY helpers, severity, paths, MASVS)
  362. │ ├── auto-audit-static.sh # Main workflow orchestrator
  363. │ ├── audit-android-components.sh # Component security audit
  364. │ └── test-findings.json # Sample report input
  365. ├── references/schemas/ # 2 JSON schemas for report/finding contracts
  366. └── references/ai-prompts/ # AI-powered analysis prompts
  367. ├── java-security-analyzer.md # Java code analysis prompts
  368. ├── native-binary-analyzer.md # Native binary analysis prompts
  369. ├── exploit-generator.md # Exploit PoC generation prompts
  370. └── report-enhancer.md # Report enhancement prompts
  371. ```
  372. ## 🎓 Trigger Phrases
  373. The skill activates when the user says:
  374. - "audit this APK"
  375. - "analyze android app"
  376. - "mobile pentest"
  377. - "APK security"
  378. - "decompile APK"
  379. - "android vulnerability assessment"
  380. - "reverse engineer android"
  381. - "modify APK"
  382. - "bypass SSL pinning"
  383. - "bypass root detection"
  384. - "intent injection"
  385. - "deep link abuse"
  386. ## ⚠️ Limitations
  387. 1. **Dynamic analysis requires a device or emulator** — Frida needs a running Android system
  388. 2. **Some packers require manual unpacking** — DexGuard 9+, Arxan may need interactive debugging
  389. 3. **Android 14+ restrictions** — Certain Intent behaviors require explicit `-n package/activity` flags
  390. 4. **Frida version matching** — frida-server on device must match frida-tools on host exactly
  391. 5. **Flutter uses BoringSSL natively** — Java SSL hooks don't work, need native hooks
  392. ## 📚 Standards Alignment
  393. This skill is aligned with:
  394. - **OWASP MASTG** — Mobile Application Security Testing Guide
  395. - **OWASP MASVS** — Mobile Application Security Verification Standard
  396. - **Passive OSINT enrichment** — Scope-controlled public evidence correlation for APK findings
  397. - **OWASP Mobile Top 10 2024** — Top 10 mobile risks
  398. - **CVSS 4.0** — Common Vulnerability Scoring System
  399. ## 🔐 OWASP Mobile Top 10 (2024)
  400. | ID | Category |
  401. |----|----------|
  402. | M1 | Improper Credential Usage |
  403. | M2 | Inadequate Supply Chain Security |
  404. | M3 | Insecure Authentication/Authorization |
  405. | M4 | Insufficient Input/Output Validation |
  406. | M5 | Insecure Communication |
  407. | M6 | Inadequate Privacy Controls |
  408. | M7 | Insufficient Binary Protections |
  409. | M8 | Security Misconfiguration |
  410. | M9 | Insecure Data Storage |
  411. | M10 | Insufficient Cryptography |
  412. ## 🤝 Contributing
  413. Contributions are welcome! Please see the [references/](references/) directory for areas that need expansion.
  414. ## 📄 License
  415. Apache License 2.0 — See [LICENSE](LICENSE) for details.
  416. ## 👨‍💻 Author
  417. **DragonJAR SAS** — [https://www.DragonJAR.org](https://www.DragonJAR.org)
  418. [Experts in IT security services, proactive validation, and offensive security.](https://www.dragonjar.org/servicios-de-seguridad-informatica)
  419. ---
  420. ## 🔄 Source of Truth
  421. This repository (`main` branch) is the **canonical source** of the skill. If you keep copies in agent skill directories (e.g. `~/.agents/skills/android-pentesting-skill/` or `~/.config/opencode/skills/android-pentesting-skill/`), resync them after pulling:
  422. ```bash
  423. git -C /path/to/Android-Pentesting-Skill pull
  424. rsync -a --delete --exclude '.git' --exclude '__pycache__' --exclude '.pytest_cache' \
  425. /path/to/Android-Pentesting-Skill/ ~/.agents/skills/android-pentesting-skill/
  426. ```
  427. Unsynchronized copies will drift and silently serve outdated references.
  428. **⚠️ Disclaimer:** This skill is intended for **authorized security testing only**. Users must obtain proper authorization before conducting any security assessment. The authors are not responsible for misuse of this tool.
scripts/06-setup/preflight-check.sh · Bundled script · 380 lines · 1 finding marked
  1. #!/usr/bin/env bash
  2. if [ "${1:-}" = "--help" ] || [ "${1:-}" = "-h" ]; then
  3. cat <<EOF
  4. Android APK Audit - Preflight Check
  5. USAGE:
  6. $0 [--help|-h]
  7. Checks required Android APK audit tools and prints install guidance for missing dependencies.
  8. Use scripts/06-setup/preflight-check.py for JSON, strict, quiet, or cross-platform modes.
  9. EOF
  10. exit 0
  11. fi
  12. # Check bash version for associative arrays
  13. if [ -z "${BASH_VERSINFO:-}" ] || [ "${BASH_VERSINFO[0]}" -lt 4 ]; then
  14. newer_bash=""
  15. if [ -x /opt/homebrew/bin/bash ]; then
  16. newer_bash="/opt/homebrew/bin/bash"
  17. elif [ -x /usr/local/bin/bash ]; then
  18. newer_bash="/usr/local/bin/bash"
  19. fi
  20. echo "ERROR: This script must be run with bash 4+ (macOS default is bash 3.2)."
  21. echo "zsh is not supported."
  22. echo "Fix: brew install bash"
  23. if [ -n "$newer_bash" ]; then
  24. echo "Then run: $newer_bash \"$0\""
  25. else
  26. echo "Then run it with your Homebrew bash path, e.g. /opt/homebrew/bin/bash \"$0\""
  27. fi
  28. exit 1
  29. fi
  30. set -euo pipefail
  31. SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  32. source "$SCRIPT_DIR/../lib/colors.sh"
  33. # Track results
  34. declare -A tool_status
  35. declare -A tool_version
  36. critical_missing=0
  37. optional_missing=0
  38. # OS Detection
  39. detect_os() {
  40. case "$(uname -s)" in
  41. Darwin)
  42. echo "macOS"
  43. return
  44. ;;
  45. Linux)
  46. if [ -f /etc/os-release ]; then
  47. . /etc/os-release
  48. if echo "$ID" | grep -qE "ubuntu|debian"; then
  49. echo "linux-debian"
  50. elif echo "$ID" | grep -q "arch"; then
  51. echo "linux-arch"
  52. elif echo "$ID" | grep -qE "fedora|rhel|centos"; then
  53. echo "linux-fedora"
  54. else
  55. echo "linux-other"
  56. fi
  57. else
  58. echo "linux-other"
  59. fi
  60. return
  61. ;;
  62. MINGW*|MSYS*|CYGWIN*)
  63. echo "windows"
  64. return
  65. ;;
  66. *)
  67. echo "unknown"
  68. return
  69. ;;
  70. esac
  71. }
  72. OS=$(detect_os)
  73. # Get install command for current OS
  74. get_install_cmd() {
  75. local tool=$1
  76. local os=$2
  77. case "$os" in
  78. macOS)
  79. case "$tool" in
  80. jadx) echo "brew install jadx" ;;
  81. apktool) echo "brew install apktool" ;;
  82. adb) echo "brew install --cask android-platform-tools" ;;
  83. frida) echo "pip3 install frida-tools" ;;
  84. objection) echo "pip3 install objection" ;;
  85. apkid) echo "pip3 install apkid" ;;
  86. ilspycmd) echo "dotnet tool install -g ilspycmd" ;;
  87. java) echo "brew install openjdk" ;;
  88. zipalign) echo "brew install --cask android-commandlinetools" ;;
  89. python3) echo "brew install python@3" ;;
  90. sqlite3) echo "brew install sqlite" ;;
  91. android-cli) echo "curl -fsSL https://dl.google.com/android/cli/latest/darwin_arm64/install.sh | bash" ;;
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 103 on GitHub
  92. *) echo "manual installation required" ;;
  93. esac
  94. ;;
  95. linux-debian)
  96. case "$tool" in
  97. jadx) echo "sudo apt install jadx" ;;
  98. apktool) echo "sudo apt install apktool" ;;
  99. adb) echo "sudo apt install android-tools-adb" ;;
  100. frida) echo "sudo apt install frida-tools" ;;
  101. objection) echo "pip3 install objection" ;;
  102. apkid) echo "pip3 install apkid" ;;
  103. java) echo "sudo apt install default-jdk" ;;
  104. zipalign) echo "Install via Android SDK build-tools (android-sdk-build-tools)" ;;
  105. python3) echo "sudo apt install python3" ;;
  106. sqlite3) echo "sudo apt install sqlite3" ;;
  107. *) echo "sudo apt install $tool" ;;
  108. esac
  109. ;;
  110. linux-arch)
  111. case "$tool" in
  112. jadx) echo "yay -S jadx" ;;
  113. apktool) echo "sudo pacman -S apktool" ;;
  114. adb) echo "sudo pacman -S android-tools" ;;
  115. frida) echo "pip3 install frida-tools" ;;
  116. objection) echo "pip3 install objection" ;;
  117. apkid) echo "pip3 install apkid" ;;
  118. java) echo "sudo pacman -S jdk-openjdk" ;;
  119. zipalign) echo "sudo pacman -S android-tools" ;;
  120. python3) echo "sudo pacman -S python" ;;
  121. sqlite3) echo "sudo pacman -S sqlite" ;;
  122. *) echo "sudo pacman -S $tool" ;;
  123. esac
  124. ;;
  125. linux-fedora)
  126. case "$tool" in
  127. jadx) echo "sudo dnf install jadx" ;;
  128. apktool) echo "sudo dnf install apktool" ;;
  129. adb) echo "sudo dnf install android-tools" ;;
  130. frida) echo "pip3 install frida-tools" ;;
  131. objection) echo "pip3 install objection" ;;
  132. apkid) echo "pip3 install apkid" ;;
  133. java) echo "sudo dnf install java-latest-openjdk-devel" ;;
  134. zipalign) echo "sudo dnf install android-tools" ;;
  135. python3) echo "sudo dnf install python3" ;;
  136. sqlite3) echo "sudo dnf install sqlite" ;;
  137. *) echo "sudo dnf install $tool" ;;
  138. esac
  139. ;;
  140. windows)
  141. case "$tool" in
  142. jadx) echo "choco install jadx or scoop install jadx" ;;
  143. apktool) echo "choco install apktool or scoop install apktool" ;;
  144. adb) echo "choco install adb or scoop install adb" ;;
  145. frida) echo "pip3 install frida-tools" ;;
  146. objection) echo "pip3 install objection" ;;
  147. apkid) echo "pip3 install apkid" ;;
  148. java) echo "choco install openjdk or scoop install openjdk" ;;
  149. zipalign) echo "choco install android-sdk or scoop install android-sdk" ;;
  150. python3) echo "choco install python or scoop install python" ;;
  151. sqlite3) echo "choco install sqlite or scoop install sqlite" ;;
  152. *) echo "manual installation required" ;;
  153. esac
  154. ;;
  155. *)
  156. echo "manual installation required"
  157. ;;
  158. esac
  159. }
  160. # Compare semantic versions: version_ge "1.2.3" "1.2.0" returns 0 (true)
  161. version_ge() {
  162. local required="$1"
  163. local installed="$2"
  164. # Handle cases where version extraction might fail
  165. if [ -z "$installed" ] || [ "$installed" = "unknown" ]; then
  166. return 1
  167. fi
  168. # Extract numeric part only (e.g., "1.4.0" from "jadx 1.4.0")
  169. required=$(echo "$required" | sed 's/[^0-9.]//g')
  170. installed=$(echo "$installed" | sed 's/[^0-9.]//g')
  171. # Compare using sort -V (version sort)
  172. if printf '%s\n%s\n' "$required" "$installed" | sort -V -C 2>/dev/null; then
  173. return 0
  174. else
  175. return 1
  176. fi
  177. }
  178. # Check if a tool is installed
  179. check_tool() {
  180. local tool=$1
  181. local critical=$2
  182. local cmd=$3
  183. local version_cmd=$4
  184. if command -v "$cmd" &>/dev/null; then
  185. local version=""
  186. if [ -n "$version_cmd" ]; then
  187. # Special handling for java -version (writes to stderr)
  188. if [ "$tool" = "java" ]; then
  189. version=$("$version_cmd" 2>&1 | head -1 || echo "unknown")
  190. else
  191. version=$("$version_cmd" 2>/dev/null | head -1 || echo "unknown")
  192. fi
  193. fi
  194. tool_status[$tool]="found"
  195. tool_version[$tool]="$version"
  196. echo "${GREEN}✅${RESET} $tool found ${BLUE}($version)${RESET}"
  197. else
  198. local install_cmd=$(get_install_cmd "$tool" "$OS")
  199. tool_status[$tool]="missing"
  200. tool_version[$tool]=""
  201. echo "${RED}❌${RESET} $tool missing - ${YELLOW}$install_cmd${RESET}"
  202. if [ "$critical" = "true" ]; then
  203. : $((critical_missing++))
  204. else
  205. : $((optional_missing++))
  206. fi
  207. fi
  208. }
  209. # Print header
  210. echo ""
  211. echo "${BLUE}========================================${RESET}"
  212. echo "${BLUE} Android APK Audit - Preflight Check ${RESET}"
  213. echo "${BLUE}========================================${RESET}"
  214. echo "${BLUE}OS: ${RESET}$OS"
  215. echo "${BLUE}========================================${RESET}"
  216. echo ""
  217. # Critical tools
  218. echo "${BLUE}Critical Tools:${RESET}"
  219. check_tool "jadx" "true" "jadx" "jadx --version"
  220. check_tool "apktool" "true" "apktool" "apktool --version"
  221. check_tool "java" "true" "java" "java -version"
  222. # Version-specific warnings for critical tools
  223. echo ""
  224. echo "${BLUE}Version Checks:${RESET}"
  225. # jadx: warn if < 1.4
  226. if command -v jadx &>/dev/null; then
  227. jadx_version=$(jadx --version 2>/dev/null | head -1 || echo "")
  228. if ! version_ge "1.4" "$jadx_version"; then
  229. echo "${YELLOW}⚠️${RESET} jadx version $jadx_version may be old — consider upgrading to 1.4+ for better decompilation"
  230. fi
  231. fi
  232. # apktool: warn if >= 3.0 (requires -f/--force to overwrite existing dirs)
  233. if command -v apktool &>/dev/null; then
  234. apktool_version=$(apktool --version 2>/dev/null | head -1 || echo "")
  235. if version_ge "3.0" "$apktool_version"; then
  236. echo "${YELLOW}⚠️${RESET} apktool $apktool_version detected — requires -f/--force when the output dir exists; scripts have been updated"
  237. fi
  238. fi
  239. echo ""
  240. # grep or ripgrep (at least one required)
  241. echo "${BLUE}Search Tools (grep or rg required):${RESET}"
  242. grep_found=false
  243. rg_found=false
  244. if command -v grep &>/dev/null; then
  245. grep --version &>/dev/null
  246. tool_status["grep"]="found"
  247. tool_version["grep"]="$(grep --version 2>/dev/null | head -1)"
  248. echo "${GREEN}✅${RESET} grep found ${BLUE}($(grep --version 2>/dev/null | head -1))${RESET}"
  249. grep_found=true
  250. else
  251. echo "${RED}❌${RESET} grep missing - ${YELLOW}$(get_install_cmd "grep" "$OS")${RESET}"
  252. fi
  253. if command -v rg &>/dev/null; then
  254. rg --version &>/dev/null
  255. tool_status["rg"]="found"
  256. tool_version["rg"]="$(rg --version 2>/dev/null | head -1)"
  257. echo "${GREEN}✅${RESET} ripgrep (rg) found ${BLUE}($(rg --version 2>/dev/null | head -1))${RESET}"
  258. rg_found=true
  259. else
  260. echo "${YELLOW}⚠️${RESET} ripgrep (rg) missing - ${YELLOW}$(get_install_cmd "ripgrep" "$OS")${RESET}"
  261. fi
  262. # Check for GNU grep on macOS (installed as ggrep via brew)
  263. if [ "$OS" = "macOS" ]; then
  264. if command -v ggrep &>/dev/null; then
  265. tool_status["ggrep"]="found"
  266. tool_version["ggrep"]="$(ggrep --version 2>/dev/null | head -1)"
  267. echo "${GREEN}✅${RESET} GNU grep (ggrep) found ${BLUE}($(ggrep --version 2>/dev/null | head -1))${RESET}"
  268. echo "${BLUE}ℹ️${RESET} Use 'ggrep -P' for PCRE patterns on macOS"
  269. else
  270. echo "${YELLOW}ℹ️${RESET} GNU grep not installed — PCRE patterns require: ${YELLOW}brew install grep${RESET}"
  271. fi
  272. fi
  273. if [ "$grep_found" = false ] && [ "$rg_found" = false ]; then
  274. : $((critical_missing++))
  275. fi
  276. echo ""
  277. # Check adb (critical for dynamic analysis)
  278. check_tool "adb" "true" "adb" "adb version"
  279. echo ""
  280. # Optional tools
  281. echo "${BLUE}Optional Tools:${RESET}"
  282. check_tool "frida" "false" "frida" "frida --version"
  283. check_tool "objection" "false" "objection" "objection --version"
  284. check_tool "apkid" "false" "apkid" "apkid --version"
  285. check_tool "ilspycmd" "false" "ilspycmd" "ilspycmd --version"
  286. check_tool "zipalign" "false" "zipalign" "zipalign -v"
  287. check_tool "keytool" "false" "keytool" "keytool -help"
  288. check_tool "jarsigner" "false" "jarsigner" "jarsigner -help"
  289. check_tool "apksigner" "false" "apksigner" "apksigner --version"
  290. check_tool "python3" "false" "python3" "python3 --version"
  291. check_tool "strings" "false" "strings" ""
  292. check_tool "sqlite3" "false" "sqlite3" "sqlite3 --version"
  293. check_tool "semgrep" "false" "semgrep" "semgrep --version"
  294. check_tool "android-cli" "false" "android" "android --version"
  295. echo ""
  296. # Version-specific warnings for optional tools
  297. echo "${BLUE}Optional Version Checks:${RESET}"
  298. # frida: warn if >= 16 (--no-pause deprecated in frida 16+)
  299. if command -v frida &>/dev/null; then
  300. frida_version=$(frida --version 2>/dev/null | head -1 || echo "")
  301. if version_ge "16" "$frida_version"; then
  302. echo "${YELLOW}⚠️${RESET} frida $frida_version — --no-pause flag is deprecated; scripts have been updated"
  303. fi
  304. fi
  305. # semgrep: warn if < 1.0 (older versions may have compatibility issues)
  306. if command -v semgrep &>/dev/null; then
  307. semgrep_version=$(semgrep --version 2>/dev/null | head -1 || echo "")
  308. if ! version_ge "1.0" "$semgrep_version"; then
  309. echo "${YELLOW}⚠️${RESET} semgrep version $semgrep_version may be old — consider upgrading to 1.0+"
  310. fi
  311. fi
  312. echo ""
  313. # Summary
  314. total_critical=5
  315. total_found_critical=$((total_critical - critical_missing))
  316. total_optional=11
  317. total_found_optional=$((total_optional - optional_missing))
  318. total_tools=$((total_critical + total_optional))
  319. total_found=$((total_found_critical + total_found_optional))
  320. echo "${BLUE}========================================${RESET}"
  321. echo "${BLUE}Summary:${RESET}"
  322. echo "${GREEN}✅${RESET} $total_found/$total_tools tools found"
  323. echo "${RED}❌${RESET} $critical_missing critical tools missing"
  324. echo "${YELLOW}⚠️${RESET} $optional_missing optional tools missing"
  325. if [ "$critical_missing" -gt 0 ]; then
  326. echo ""
  327. echo "${RED}Missing critical tools:${RESET}"
  328. for tool in "${!tool_status[@]}"; do
  329. if [ "${tool_status[$tool]}" = "missing" ]; then
  330. case "$tool" in
  331. jadx|apktool|java|adb|grep) echo " - $tool" ;;
  332. esac
  333. fi
  334. done
  335. echo ""
  336. echo "${RED}CRITICAL: Install missing tools to proceed with APK audit${RESET}"
  337. exit 1
  338. else
  339. echo ""
  340. echo "${GREEN}✅ All critical tools installed! Ready for APK audit.${RESET}"
  341. exit 0
  342. fi

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.