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.
Badge for your README
Markdown
[](/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
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.
- ---
- name: Android-Pentesting-Skill
- description: >
- 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.
- license: Apache-2.0
- 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"
- metadata:
- author: DragonJAR SAS
- version: "1.9.0"
- category: mobile-security
- tags:
- - android
- - apk-audit
- - static-analysis
- - dynamic-analysis
- - frida
- - objection
- - security-pentest
- - cvss-scoring
- - reverse-engineering
- - ai-powered
- - ai-analysis
- ---
- # Android APK Security Audit
- ## Overview
- 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.
- ## When to Use
- - User provides an APK file for security review
- - User asks to analyze decompiled Android source code
- - User needs to modify or repackage an APK for testing
- - User wants mobile security testing or vulnerability assessment
- - User needs help testing exported components, deep links, or intent injection
- - User mentions Android reverse engineering or malware analysis
- ## Critical Rules
- 1. NEVER report bare grep hits without traced context
- 2. ALWAYS constrain searches to the app namespace (avoid library noise)
- 3. STOP and report immediately if decoding fails
- 4. ALWAYS use imperative language in findings
- 5. NEVER skip validation — if unsure, mark as "Needs Dynamic Confirmation"
- 6. ALWAYS provide concrete PoC (adb command, Frida hook, or malicious intent)
- 7. NEVER duplicate findings for the same root cause
- > **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.
- ## Execution Model
- Tools to use: bash, write, edit, read, glob, grep for core workflow.
- ## Toolchain Requirements
- Before starting, verify these tools are installed:
- - **APKTool** 3.0.2+ (`apktool --version`) — aapt2-only mode; requires Java 17+
- - **JADX** 1.5.5+ (`jadx --version`)
- - **Android SDK Platform Tools 36.0.2** (`adb`, `fastboot`)
- - **Android SDK Build Tools 36.0.0** (`apksigner`, `zipalign`, `aapt2`, `d8`)
- - **Frida** 17.x (`frida --version`) — ⚠️ Frida-server on device must match the **frida core** version (the `frida` Python package), NOT frida-tools
- - **Objection** 1.12.5+ (`objection --version`)
- - **APKiD** 3.1.0+ (`apkid --version`)
- - **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".
- 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.
- ---
- ## AI-Powered Analysis
- This skill includes AI-powered analysis capabilities. The AI model running this skill has built-in code analysis - use it strategically to enhance findings.
- ### When to Use AI
- - Analyzing decompiled code for semantic vulnerabilities
- - Tracing complex data flows (source-to-sink)
- - Generating Proof-of-Concept exploits
- - Filtering false positives from automated scans
- - Understanding obfuscated code behavior
- - Enhancing report quality and context
- ### How to Use AI
- 1. **Analyze specific code sections**: Don't ask AI to find ALL vulnerabilities - target specific suspicious code
- 2. **Provide context**: Include the full function/class, not just snippets
- 3. **Ask for CVSS scoring**: Request severity assessment with CVSS 4.0
- 4. **Verify findings**: Always validate AI findings against code and Frida testing
- ### AI Analysis Prompts
- See `references/ai-pentesting-guide.md` for complete methodology and prompt templates.
- Quick examples:
- ```
- ANALYZE: Is this SQL injection exploitable?
- Code: <vulnerable_query_with_user_input>
- Context: <userId from Intent extra>
- For each finding provide:
- - CWE ID and CVSS 4.0 score
- - Exploitation scenario
- - Frida script to demonstrate (if applicable)
- ```
- > **Reference**: `references/ai-pentesting-guide.md` - Complete AI analysis methodology
- > **Inventory**: [`references/project-manifest.md`](references/project-manifest.md) is the ground-truth list of every packaged file and directory.
- ---
- ## Audit Mode Selection
- Select the smallest mode that satisfies the user request. See `references/audit-modes.md` for full feature flags and presets.
- | Mode | Default Use | Notes |
- |------|-------------|-------|
- | `quick` | First-pass triage | Decode, manifest, focused static checks, coverage statement. |
- | `static` | No device/emulator | Static analysis only; mark runtime-only issues `Needs Dynamic Confirmation`. |
- | `full` | Standard APK audit | Static + dynamic + MASVS + optional executive risk score. |
- | `protected-app` | Packing/RASP blocks analysis | Follow protected-app fallback and record coverage gaps. |
- | `osint` | Public exposure enrichment | Passive, in-scope OSINT only. |
- | `reporting-only` | Existing findings JSON | Deduplicate, triage, MASVS, risk score, report. |
- ---
- ## Optional Input Adapter — Gmail APK Ingestion
- `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).
- ```bash
- # List matches without downloading
- python3 scripts/00-ingestion/fetch-apk-gmail.py --output-dir ./ingested/ --dry-run
- # Download (requires OAuth credentials outside the repo)
- python3 scripts/00-ingestion/fetch-apk-gmail.py --output-dir ./ingested/ --sender audits@corp.com --max 5
- ```
- 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`.
- ---
- ## Phase 0 — Decode and Detect Framework
- ### Decode APK
- ```bash
- apktool d app.apk -o decoded/ # Decode resources + smali
- jadx -d jadx_output app.apk # Decompile to Java
- apkid app.apk # Detect framework/packer
- ```
- ### Framework Detection
- Identify the app's architecture early to tailor analysis.
- **React Native**: `grep -r "com.facebook.react" decoded/AndroidManifest.xml` · Check for `libhermes.so` and `index.android.bundle` in assets/
- **Flutter**: `grep -r "io.flutter" decoded/AndroidManifest.xml` · Check for `libflutter.so` and `assets/flutter_assets/`
- **Cordova/Ionic**: `grep -r "org.apache.cordova" decoded/AndroidManifest.xml` · Check `assets/www/` for cordova.js
- **Xamarin**: `grep -r "mono\|com.xamarin" decoded/AndroidManifest.xml` · Check for `libmonodroid.so`
- **.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
- > **Reference**: `references/hybrid-webview-frameworks.md` for complete detection scripts, Frida detection hooks, and framework-specific security considerations.
- > **Reference**: `references/dotnet-maui-security.md` for .NET MAUI/Xamarin managed-assembly extraction (IL/DLL), C#-specific security checklist, and mono-runtime Frida hooks.
- > **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.
- ### Obfuscation Detection
- - **ProGuard/R8**: Class names like `a.b.c`, `a$a`, `a$1`
- - **DexGuard**: Additional string encryption and native methods
- - **Custom obfuscation**: Unusual patterns, mixed naming schemes
- > **Reference**: `references/static-analysis-patterns.md` for detailed detection patterns.
- ---
- ## Phase 1 — Attack Surface Mapping
- ### Analyze AndroidManifest.xml
- ```bash
- cat decoded/AndroidManifest.xml
- aapt2 dump badging app.apk
- ```
- ### Exported Components
- Exported components are attack surfaces:
- | Component | Exported If | Security Checks |
- |-----------|-------------|-----------------|
- | Activities | `android:exported="true"` | Intent filters, permission requirements |
- | Services | `android:exported="true"` | Intent filters, permission requirements |
- | Receivers | `android:exported="true"` | Intent filters, permission requirements |
- | Providers | `android:exported="true"` | Path permissions, read/write permissions |
- ### Deep Link Schemes
- Extract and document all deep link schemes:
- ```xml
- <intent-filter>
- <data android:scheme="scheme" android:host="host" />
- </intent-filter>
- ```
- ### Security-Relevant XML Resources
- Check `res/xml/` for: `network_security_config.xml` (TLS/cleartext), file provider paths, preferences.
- > **Reference**: `references/android-manifest-checklist.md` for complete 50+ manifest checks.
- > **IPC / intent abuse**: see `references/intent-injection.md` and `references/pendingintent-security.md`.
- ---
- ## Phase 2 — Targeted Triage
- ### Scoped Grep Patterns
- ALWAYS grep within the app namespace only. Use patterns from `references/static-analysis-patterns.md`:
- | Category | Example Patterns | What to Look For |
- |----------|------------------|------------------|
- | WebView sinks | `loadUrl\(`, `evaluateJavascript` | Loading untrusted URLs |
- | IPC sources | `getIntent()`, `onNewIntent()` | Unsanitized data entry |
- | Intent relays | `getParcelableExtra`, `getSerializableExtra`, `startActivity\(`, `sendBroadcast\(` | Nested intent / confused deputy patterns |
- | Hardcoded secrets | `password\s*=`, `api[_-]?key` | Credentials in code |
- | Encoded literals | `Base64\.decode`, `"\x[0-9a-f]"` | Obfuscated strings |
- | Weak crypto | `DES/`, `MD5`, `"AES/ECB"` | Insecure algorithms |
- | Insecure storage | `SharedPreferences`, `MODE_WORLD_READABLE` | Unprotected data → `references/data-storage-auditing.md` |
- | Network/TLS | `TrustManager`, `X509TrustManager` | SSL validation bypass |
- | Native bridges | `System\.loadLibrary`, JNI methods | Native code interfaces |
- ### Resource File Analysis
- Check `res/values/strings.xml` for secrets:
- ```bash
- grep -iE "(key|token|secret|password|api)" decoded/res/values/strings.xml
- ```
- > **Reference**: `references/static-analysis-patterns.md` for 100+ grep patterns organized by vulnerability type.
- ### Phase 2.5 — Static Analysis Rules (Optional)
- The semgrep-based static analysis module augments grep patterns with OWASP MASTG rules:
- ```bash
- # Enable semgrep in auto-audit-static.sh
- bash scripts/auto-audit-static.sh app.apk --semgrep
- # Run semgrep scan standalone
- python3 scripts/03-static-analysis/semgrep-scan.py decoded/ --output findings-semgrep.json
- # Merge findings with existing findings
- python3 scripts/03-static-analysis/merge-findings.py --input findings.json semgrep.json --output merged.json
- # Update rules from upstream
- bash scripts/03-static-analysis/update-rules.sh --fetch
- ```
- **Features**:
- - 70+ MASTG-aligned rules covering crypto, network, storage, authentication
- - Non-blocking fallback (continues if semgrep is not available)
- - Deduplication by CWE + title before merging
- - Phase 2.5 runs after grep patterns, before data flow tracing
- > **Reference**: `scripts/03-static-analysis/semgrep-scan.py --help` for rule categories and update workflow.
- ### Advanced Static Detectors — ZipSlip, XEE, Accessibility, Clipboard
- Four gap-filling detector families beyond grep patterns and semgrep rules:
- ```bash
- # Run against an already-decoded directory (from Phase 0)
- bash scripts/03-static-analysis/advanced-static-checks.sh -d decoded/ -o adv-static/
- # Or decode + check in one step
- bash scripts/03-static-analysis/advanced-static-checks.sh -a app.apk -o adv-static/
- ```
- **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.
- ### APK Version Diffing — N-day Hunting (Optional)
- 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:
- ```bash
- # Full diff: inventory, decompiled sources, secrets rotation
- bash scripts/03-static-analysis/version-diff-audit.sh --old app-v1.2.apk --new app-v1.3.apk
- # Fast path without jadx decompilation
- bash scripts/03-static-analysis/version-diff-audit.sh --old v1.apk --new v2.apk --skip-jadx
- ```
- **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.
- > **Reference**: `references/app-version-diffing.md` for the full bughunter workflow.
- ---
- ## Phase 3 — Data Flow Tracing
- ### Source-to-Sink Methodology
- Map data flow from untrusted sources to dangerous sinks:
- #### Common Sources
- | Source | Method | Example |
- |--------|--------|---------|
- | IPC (Activities) | `getIntent()` | Malicious intent data |
- | IPC (Services) | `onStartCommand()` | Start extras |
- | Deep Links | `getIntent().getData()` | URL parameters |
- | WebView | `JavascriptInterface` | Untrusted JS calls |
- | Network | `HttpResponse` | API responses |
- | Storage | `SharedPreferences` | Stored user input |
- | External | `Environment.getExternalStorageDirectory()` | File system data |
- #### Common Sinks
- | Sink | Method | Impact |
- |------|--------|--------|
- | Command Execution | `Runtime.exec()`, `ProcessBuilder` | RCE |
- | WebView Load | `loadUrl()`, `loadData()` | XSS, Phishing |
- | File Operations | `FileWriter`, `FileOutputStream` | Path traversal, LFI |
- | IPC Broadcast | `sendBroadcast()` | Intent injection |
- | Reflection | `Class.forName()`, `getMethod()` | Code execution |
- | Native Calls | JNI | Native code execution |
- | SQL | `SQLiteDatabase.execSQL()` | SQL injection |
- ### Decision Rules
- | Rule | Condition | Action |
- |------|-----------|--------|
- | 1 | Direct flow source → sink | Report as **Likely** |
- | 2 | Indirect flow via static analysis | Report as **Likely** if path clear |
- | 3 | Dynamic/reflective call | Mark as **Needs Dynamic Confirmation** |
- | 4 | Native boundary | Mark as **Needs Dynamic Confirmation** |
- | 5 | Library code | Verify if app wraps securely |
- | 6 | No sanitization | Escalate severity |
- ### Manual Checks Grep Misses
- | Check | Why grep misses | How to verify |
- |-------|----------------|---------------|
- | Runtime permissions | `requestPermissions()` calls | Trace `onRequestPermissionsResult` |
- | Custom permission protections | `checkPermission()` | Look for permission checks |
- | Activity transitions & intent relays | `startActivity()` hides nested-intent forwarding and grant flags | Follow intent construction, `Parcelable` relays, and `FLAG_GRANT_*` usage |
- | File provider paths | XML + code | Map paths to exposed content URIs |
- | Content provider queries | `query()` | Trace URI construction |
- > **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.
- ---
- ## Phase 4 — Dynamic Analysis (Optional)
- Use when static analysis hits a wall: obfuscation, reflection, native code, runtime protections.
- ### Runtime Defense Analysis (RDA)
- The Runtime Defense Analysis module provides Frida-based detection and bypass for anti-analysis mechanisms:
- ```bash
- # Run static audit first; RDA is a separate Phase 4 module
- bash scripts/auto-audit-static.sh app.apk --semgrep
- # Or via frida-exploit-helper.py
- python3 scripts/07-tools/frida-exploit-helper.py -p com.target.app --runtime-defense
- # List available detectors
- bash scripts/02-rasp/runtime-defense-analyzer.sh --list
- # Run with active bypass mode (attempt to bypass detections)
- bash scripts/02-rasp/runtime-defense-analyzer.sh app.apk com.target.app --active-mode --authorized-lab
- ```
- **Available detector catalog** (18 entries: 14 executable detectors + 4 not-applicable backend/cloud entries):
- - `rootbeer` — RootBeer library detection
- - `safetynet` — SafetyNet attestation
- - `emulator` — Emulator detection
- - `debug` — Debugger detection
- - `frida-detect` — Frida detection
- - `screenshot` — Screenshot prevention detection
- - `screenrecorded` — Screen recording detection
- - `talsec`, `approov`, `dexguard`, `appdome`, `doverunner`, `digitalai` — commercial RASP/shielding detection
- - `contrast`, `imperva`, `dynatrace`, `accuknox` — cataloged as not-applicable for direct Android APK detection
- **Output**: `findings-rda.json` with detector results
- > **Reference**: `scripts/02-rasp/README.md` for detailed detector documentation.
- ### Drozer IPC Probing
- Complement static component mapping with binder-level interaction via drozer (providers, activities, services, receivers):
- ```bash
- # Safe enumeration only (default)
- bash scripts/07-tools/drozer-automated.sh -p com.target.app
- # Print exact commands without running them
- bash scripts/07-tools/drozer-automated.sh -p com.target.app --print-commands
- # Exploitation probes (SQLi strings, path traversal) — authorized lab only
- bash scripts/07-tools/drozer-automated.sh -p com.target.app --authorized-lab
- ```
- **Output**: `drozer-findings.json` (`source: drozer`) + `drozer-report.md` with raw per-stage evidence.
- > **Reference**: `references/drozer-ipc-playbook.md` for the component-by-component playbook.
- ### Firebase Exposure Check (Authorized Assets Only)
- Automated verification of Firebase URLs/API keys extracted from the APK (shallow reads only, no writes):
- ```bash
- # From APK sources/resources
- bash scripts/07-tools/firebase-check.sh -a app.apk -o firebase/
- # Direct URL or offline key extraction
- bash scripts/07-tools/firebase-check.sh -u "https://proj.firebaseio.com" -o firebase/
- bash scripts/07-tools/firebase-check.sh -a app.apk --offline
- ```
- **Verdicts**: HTTP 200 on `/.json?shallow=true` = open DB (Critical); 401/403 = secured; `--offline` emits informational key-inventory findings only.
- > **Reference**: `references/firebase-security.md` → automated verification section.
- ### ADB Backup Extraction
- Test what an attacker with USB/PC access can extract when `allowBackup` is enabled:
- ```bash
- # Interactive: triggers adb backup on the connected device
- bash scripts/07-tools/adb-backup-extract.sh -a com.target.app
- # Parse an existing .ab file (24-byte header, zlib)
- bash scripts/07-tools/adb-backup-extract.sh --from-file backup.ab -o backup-audit/
- ```
- **Output**: `backup-findings.json` (`source: adb`) + verdict on backup sensitivity. Encrypted backups exit code 3 (unsupported, by design).
- > **References**: `references/adb-backup-enterprise.md` for the .ab format, MDM/work-profile surface, and the enterprise checklist.
- ### Elite Dynamic Techniques
- 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:
- > **Reference**: `references/advanced-dynamic-techniques.md`.
- ### Authorized RASP Bypass Validation
- After RDA detection, use the DRY bypass runner instead of duplicating Frida logic per detector:
- ```bash
- # List reusable bypass profiles
- bash scripts/02-rasp/rasp-bypass-runner.sh --list-profiles
- # Build a reviewed command from detector names
- bash scripts/02-rasp/rasp-bypass-runner.sh \
- --package com.target.app \
- --detectors rootbeer,frida_detect,talsec \
- --print-command
- # Execute only in an authorized lab
- bash scripts/02-rasp/rasp-bypass-runner.sh \
- --package com.target.app \
- --from-rda findings-rda.json \
- --run --authorized-lab
- ```
- 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.
- ### Frida Integration
- ```bash
- # Spawn app with hook
- frida -U -f com.example.app -l script.js
- # Attach to running process
- frida -U com.example.app -l script.js
- ```
- ### Using frida-exploit-helper.py
- The `frida-exploit-helper.py` script provides a convenient wrapper for Frida operations with bundled scripts and common patterns.
- **When to use**: Prefer `frida-exploit-helper.py` over direct Frida CLI for:
- - Bundled Frida scripts (SSL pinning bypass, root detection bypass, etc.)
- - Quick memory operations (read, write, find base address)
- - Discovering available scripts
- - Simplified Frida workflow
- **Examples with bundled scripts**:
- ```bash
- # SSL pinning bypass
- python3 scripts/07-tools/frida-exploit-helper.py -p com.target.app --script ssl-pinning-bypass
- # Root detection bypass
- python3 scripts/07-tools/frida-exploit-helper.py -p com.target.app --script root-detection-bypass
- # List all available bundled scripts
- python3 scripts/07-tools/frida-exploit-helper.py --list-scripts
- # Display app memory layout (find base addresses)
- python3 scripts/07-tools/frida-exploit-helper.py -p com.target.app --layout
- # Hook specific functions (malloc, free, etc.)
- python3 scripts/07-tools/frida-exploit-helper.py -p com.target.app --hook malloc,free
- # Read memory at address
- python3 scripts/07-tools/frida-exploit-helper.py -p com.target.app --read 0x12345678 64
- # Write to memory address
- python3 scripts/07-tools/frida-exploit-helper.py -p com.target.app --write 0x12345678 deadbeef
- ```
- **Key flags**:
- - `-p, --package` — Target package name (required for most operations)
- - `--script` — Use bundled script name (use `--list-scripts` to see options) or path to a .js file
- - `--spawn` / `-s` — Spawn a new process for the target package
- - `--attach` / `-a` — Attach to a running process
- - `--list-scripts` — Display all available bundled Frida scripts
- - `--layout` — Show memory layout and base addresses
- - `--hook` — Comma-separated list of functions to hook
- - `--read ADDRESS SIZE` — Read memory at address (hex) with size in bytes
- - `--write ADDRESS DATA` — Write data to address (hex). Data can be hex or string
- - `--base <library>` — Get base address of specified module (requires library name)
- > **Reference**: See `scripts/07-tools/frida-exploit-helper.py --help` for complete options and bundled script catalog.
- > **Reference**: bundled Frida scripts in `assets/frida-scripts/`. See `references/frida-scripts-index.md` for the canonical catalog.
- > **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.
- > **Script Maturity Levels**:
- > - **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.
- > - **BETA**: Functional but incomplete — use with caution
- ### JNI Trace (Native Library Tracing)
- For advanced JNI and native library analysis, use `jnitrace`:
- ```bash
- # Install jnitrace
- pip install jnitrace
- # Trace all JNI functions in a native library (spawn mode)
- jnitrace -l libnative-lib.so -m spawn com.target.app
- # Trace with attach mode (attach to already-running app)
- jnitrace -l libnative-lib.so -m attach com.target.app
- # Trace only JNI methods matching a regex (include filter)
- jnitrace -l libnative-lib.so -m spawn com.target.app \
- -i ".*decrypt.*|.*sign.*"
- # Exclude noisy JNI methods
- jnitrace -l libnative-lib.so -m spawn com.target.app \
- -e "GetStringUTFChars|ReleaseStringUTFChars"
- # Hide JNIEnv/JavaVM struct calls to reduce noise
- jnitrace -l libnative-lib.so -m spawn com.target.app \
- --ignore-env --ignore-vm
- # Output trace to JSON file for later analysis
- jnitrace -l libnative-lib.so -m spawn com.target.app \
- -o trace-output.json
- ```
- **Programmatic usage** (via npm package):
- ```bash
- npm install jnitrace-engine
- ```
- Use `jnitrace` when:
- - Analyzing custom JNI bindings
- - Understanding native library behavior
- - Debugging native crashes
- - Tracing crypto operations in native code
- > **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.
- ### Objection Commands
- ```bash
- # Modern syntax (preferred): objection -n <package> start
- objection -n com.example.app start
- # Legacy syntax (deprecated but still works): objection -g <package> explore
- objection -g com.example.app explore
- # Enumerate components
- android hooking list activities
- android hooking list services
- android hooking list receivers
- # Bypass protections
- android sslpinning disable
- # Enumerate Android Keystore entries
- android keystore list
- ```
- ### ADB Runtime Testing
- ```bash
- # Test exported activity
- adb shell am start -n com.example.app/.MainActivity -a android.intent.action.VIEW -d "scheme://host"
- # Test exported receiver
- adb shell am broadcast -a com.example.app.ACTION -e key "value"
- # Monitor logs
- adb logcat | grep com.example.app
- ```
- > **SSL Pinning bypass**: `references/dynamic-analysis-setup.md` + `assets/frida-scripts/ssl-pinning-bypass.js`
- > **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.
- > **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.
- > **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.
- > **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`).
- > **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.
- ---
- ## Phase 5 — Classification and Reporting
- ### Compliance Score (Optional)
- Generate a MASVS v2 compliance score alongside CVSS findings:
- ```bash
- # Generate MASVS compliance score
- python3 scripts/05-scoring/calculate-score.py findings.json --json-output > score.json
- # Generate full report with MASVS score
- python3 scripts/07-tools/generate-report.py --input findings.json --masvs --output report.html
- # Use custom MASVS mapping
- python3 scripts/07-tools/generate-report.py --input findings.json --masvs --masvs-mapping scripts/05-scoring/masvs-mapping.json --output report.html
- ```
- **Scoring methodology**:
- - 23 MASVS v2 controls assessed
- - Weighted deduction based on severity (Critical×10, High×5, Medium×2, Low×1)
- - Final score: 0–100 with letter grade (A/B/C/D/F)
- **Grade thresholds**:
- - A: 90–100 (Excellent)
- - B: 80–89 (Good)
- - C: 70–79 (Acceptable)
- - D: 60–69 (Poor)
- - F: 0–59 (Critical)
- > **References**: `scripts/05-scoring/README.md` and `references/masvs-scoring-model.md` for control definitions, mapping semantics, and not-tested handling.
- ### Executive Risk Score (Optional)
- 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:
- - CVSS = severity of individual vulnerabilities
- - MASVS = control coverage/compliance posture
- - Executive risk score = aggregate operational exposure and coverage gaps
- 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.
- ### OSINT Enrichment (Optional)
- If the engagement scope allows passive reconnaissance, enrich Phase 5 with `references/osint-apk-recon.md`:
- 1. Correlate package name, app label, first-party domains, endpoints, and redacted secret fingerprints.
- 2. Search passive public sources only unless active probing is explicitly authorized.
- 3. Classify domains as first-party, likely first-party, third-party SDK, or unknown before reporting.
- 4. Promote OSINT evidence only when it supports an in-scope app finding or public exposure claim.
- ### Confidence Levels
- | Level | Definition | Example Evidence |
- |-------|-----------|------------------|
- | **Confirmed** | Full source-to-sink trace validated | Direct call chain from IPC source to `Runtime.exec()` with no sanitization |
- | **Likely** | Strong evidence, minor gaps | Static trace clear but reflection obscures final sink |
- | **Needs Dynamic Confirmation** | Static analysis inconclusive | Obfuscated code or native boundary requiring runtime verification |
- ### Severity
- Use CVSS 4.0. See `references/cvss-scoring-guide.md` for complete methodology and severity mapping.
- ### Finding Template
- ```markdown
- ## [ID] - [Title]
- **Confidence**: [Confirmed/Likely/Needs Dynamic Confirmation]
- **Severity**: [Critical/High/Medium/Low] (CVSS: [X.X])
- **CWE**: [CWE-ID]
- **OWASP**: [OWASP Category]
- ### Description
- [1-2 sentences explaining what the vulnerability is]
- ### Affected Components
- - **File**: `path/to/file.java`
- - **Method**: `methodName()`
- - **Component**: `[Activity/Service/Receiver/Provider]` (if applicable)
- ### Attack Scenario
- 1. Attacker [action, e.g., sends malicious intent with crafted data]
- 2. App [processing step, e.g., extracts parameter without validation]
- 3. Data propagates through [call chain]
- 4. Reaches sink [dangerous operation]
- 5. Results in [impact, e.g., arbitrary command execution]
- ### Proof of Concept
- ```bash
- adb shell am start -n com.example.app/.MainActivity \
- -a android.intent.action.VIEW \
- -d 'exploit://host/path?payload=cmd%7Ccat%20/data/data/com.example.app/databases/db'
- ```
- Or provide Frida hook script for dynamic verification.
- ### Impact
- - **Confidentiality**: [High/Medium/Low/None] — [explanation]
- - **Integrity**: [High/Medium/Low/None] — [explanation]
- - **Availability**: [High/Medium/Low/None] — [explanation]
- ### Remediation
- ```java
- // Provide secure code example
- Intent intent = getIntent();
- if (intent != null && intent.getData() != null) {
- String input = intent.getData().getQueryParameter("path");
- if (isValidPath(input)) {
- loadUrl(input);
- } else {
- Log.w(TAG, "Invalid path detected");
- }
- }
- private boolean isValidPath(String path) {
- return path != null && !path.contains("..") &&
- path.matches("^/safe/\\w+\\.html$");
- }
- ```
- ### CVSS 4.0 Calculation
- [Show vector string and score breakdown]
- ```
- ### Coverage Statement
- End your report with:
- ```
- Coverage Analysis:
- - Static Analysis: Complete (all decompiled sources analyzed)
- - Dynamic Analysis: [Complete/Partial/Not Performed] (reason if partial)
- - Scope: [com.example.app.* namespace only]
- - Framework: [React Native/Flutter/Native/Standard]
- - Obfuscation: [ProGuard/R8/DexGuard/Custom/None]
- Limitations:
- - [List any limitations, e.g., "Native code analysis requires additional tools"]
- - [Any components that could not be analyzed]
- - [Any findings requiring additional verification]
- Total Findings: X (Critical: Y, High: Z, Medium: A, Low: B)
- ```
- > **Reference**: `references/reporting-templates.md` for executive summary format, remediation priority matrix, and presentation templates.
- ### Automated Report Generation
- Use the `generate-report.py` script to generate professional HTML or Markdown reports from findings JSON:
- ```bash
- # Generate HTML report
- python3 scripts/07-tools/generate-report.py \
- --input findings.json \
- --output report.html \
- --app-name "My App" \
- --package-name "com.example.app"
- # Generate Markdown report
- python3 scripts/07-tools/generate-report.py \
- --input findings.json \
- --output report.md \
- --app-name "My App" \
- --package-name "com.example.app"
- ```
- The script supports both JSON array format and JSONL (one finding per line) and automatically:
- - Sorts findings by severity (Critical first)
- - Calculates CVSS 4.0 severity scores
- - Generates executive summary with risk rating
- - Maps OWASP MASTG categories
- - Provides formatted proof of concept and remediation sections
- 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.
- ---
- ## APK Modification Workflow
- ### 1. Decode
- ```bash
- apktool d app.apk -o app-modified/
- ```
- ### 2. Modify — Smali Patching
- Edit smali files in `app-modified/smali/`:
- ```smali
- .method public checkSecurity()Z
- .locals 1
- # Original: iget-boolean v0, p0, Lcom/example/App;->securityEnabled:Z
- # Patched — always return true
- const/4 v0, 0x1
- return v0
- .end method
- ```
- #### Resource Modification
- Edit XML or resource files in `app-modified/res/`:
- ```xml
- <!-- Example: enable debug flag -->
- <bool name="debug_mode">true</bool>
- ```
- ### 3. Rebuild
- ```bash
- apktool b app-modified/ -o app-modified.apk
- ```
- ### 4. Sign
- ```bash
- # Generate keystore (first time only)
- keytool -genkeypair -v -keystore my-release-key.jks -alias androiddebugkey -keyalg RSA -keysize 2048 -validity 10000
- # Align first
- zipalign -v 4 app-modified.apk app-aligned.apk
- # Sign (apksigner supports v1, v2, v3, v3.1 signatures)
- # Verify keystore exists before signing
- if [ ! -f "my-release-key.jks" ]; then
- echo "Error: Keystore not found. Create it with keytool first."
- exit 1
- fi
- # --ks-key-alias is required when the keystore contains multiple keys; recommended in all cases
- apksigner sign \
- --ks my-release-key.jks \
- --ks-key-alias androiddebugkey \
- --ks-pass pass:myPassword \
- --key-pass pass:myPassword \
- --out app-signed.apk \
- app-aligned.apk
- # Verify signature
- apksigner verify --verbose app-signed.apk
- ```
- ### 5. Install and Verify
- Preferred (android-cli present — delta-install speeds up smali patch → test iteration):
- ```bash
- android install --apks=app-signed.apk --device=<serial>
- ```
- Fallback (no android-cli):
- ```bash
- adb install -r app-signed.apk
- ```
- Source `scripts/lib/android-cli-or-fallback.sh` and call `android_install app-signed.apk` to get the switch automatically.
- > **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.
- ---
- ## Troubleshooting
- ### APK Decoding Fails
- ```bash
- apktool d -f app.apk -o decoded/ # Force mode (re-decodes even if output dir exists)
- aapt2 dump badging app.apk # Verify APK integrity
- apkid app.apk # Detect packer/protector
- ```
- > Note: Apktool 3.0+ removed the `-api`/`--api-level` flag. The API level is now auto-detected from the APK.
- If packed → see `references/packing-unpacking.md` for unpacking techniques.
- ### JADX Shows Bad Code
- ```bash
- jadx --show-bad-code -v app.apk # Show code even with errors
- jadx --decompilation-mode fallback app.apk
- jadx-gui app.apk # GUI for manual inspection
- ```
- ### Frida Cannot Attach
- ```bash
- adb shell ps -A | grep frida
- adb shell getprop ro.product.cpu.abi
- adb shell "su -c 'killall frida-server'"
- adb shell "su -c '/data/local/tmp/frida-server -D &'"
- ```
- > Full setup: `references/dynamic-analysis-setup.md`
- ### Obfuscated Code Unreadable
- - Identify obfuscator: `apkid app.apk`
- - Enable JADX deobfuscation: `jadx --deobf app.apk`
- - See `references/static-analysis-patterns.md` → "Obfuscation Patterns"
- - Switch to Phase 4 for runtime behavior
- ### When to Escalate to Dynamic Analysis
- 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`.
- ---
- ## Examples
- ### Example 1: Quick Assessment
- `com.example.app.apk` → Decode → Framework detect → Manifest audit → Secrets grep → CVSS report
- ### Example 2: SSL Pinning Bypass
- `frida -U -f com.target.app -l ssl-pinning-bypass.js` → See `references/rasp-bypass.md` if fails
- ### Example 3: APK Repackaging
- Decode → Modify → Rebuild → Sign → Install (see `references/apk-modification-guide.md`)
- ---
- ## Agent Operating Contract
- This contract defines what every audit must produce, when to advance, when to stop, and how to report findings.
- ### Required Audit Artifacts
- For every APK audit, produce these artifacts:
- | Artifact | Phase | Description |
- |----------|-------|-------------|
- | `scope.json` | -1 | Package name, target scope, authorization confirmation |
- | `toolchain-report.json` | 0 | Tool versions, availability, preflight results |
- | `app-profile.json` | 0 | Framework, obfuscation, architecture |
- | `attack-surface.json` | 1 | Exported components, deep links, permissions |
- | `findings.json` | 2-4 | All findings in standard schema |
- | `evidence/` | 2-4 | Screenshots, logs, PoC commands |
- | `coverage-matrix.json` | 5 | MASVS control coverage status |
- | `final-report.html` | 5 | Executive summary + technical findings |
- ### Stop Conditions — STOP AND REPORT IMMEDIATELY
- | Condition | Action |
- |-----------|--------|
- | APK decode fails | Report `DECODE_FAILURE` with error log |
- | Package name cannot be determined | Report `SCOPE_UNCLEAR` and stop |
- | Target namespace cannot be isolated | Report `SCOPE_TOO_BROAD` |
- | Dynamic testing requested but no Frida/device | Mark findings `Needs Dynamic Confirmation` |
- | Encrypted/packed APK blocks analysis | Report `PACKED_APK` with partial coverage |
- ### Finding States
- | State | When to Use | CVSS Required |
- |-------|-------------|---------------|
- | **Confirmed** | Full source-to-sink trace validated | Yes |
- | **Likely** | Strong evidence, minor gaps in trace | Yes |
- | **Needs Dynamic Confirmation** | Static inconclusive (obfuscation, reflection, JNI) | TBD |
- | **Informational** | Best practice violation, low risk | Optional |
- | **Rejected** | Previously reported, confirmed false positive | N/A |
- ### APK Type Handling
- | Type | Analysis Approach |
- |------|------------------|
- | **Standard APK** | Full 6-phase workflow |
- | **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` |
- | **Packed/Protected** | Phase 0 → static baseline, runtime extraction/spawn-mode/embedded instrumentation fallback; if blocked → `PACKED_APK` report with coverage gap |
- | **React Native** | Phase 0 → extract Hermes bytecode, use `scripts/01-cross-platform/react-native-analysis.sh` |
- | **Flutter** | Phase 0 → Blutter analysis, native SSL hooks |
- | **Xamarin** | Phase 0 → identify Mono runtime, analyze bundled assemblies |
- | **Obfuscated** | Phase 2 → enhanced grep + Phase 4 dynamic if available |
- ### Evidence Standards
- Every finding must have:
- 1. **File + line reference** (or Frida trace for dynamic)
- 2. **Evidence snippet** (relevant code/data)
- 3. **Attack scenario** (how attacker exploits)
- 4. **CVSS 4.0 vector** (Confirmed/Likely) or `TBD` (Needs Dynamic)
- ### Coverage Declaration
- End every report with:
- ```json
- {
- "coverage": {
- "static_analysis": "complete | partial | not-performed",
- "dynamic_analysis": "complete | partial | not-performed",
- "framework": "react-native | flutter | cordova | xamarin | native",
- "obfuscation": "proguard | dexguard | custom | none",
- "native_code": "analyzed | not-analyzed | not-applicable",
- "rasp": "detected | not-detected | not-tested"
- },
- "total_findings": { "critical": 0, "high": 0, "medium": 0, "low": 0 }
- }
- ```
- ---
- ## References Index
- | Phase | Files | Phase | Files |
- |-------|-------|-------|-------|
- | 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` |
- | 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` |
- | 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) |
- | 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` |
- | 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` |
- | 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` |
- | 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` |
- **Scripts**:
- - `scripts/01-cross-platform/` — Framework-specific analysis (Cordova, Flutter, React Native, Unity)
- - `scripts/02-rasp/` — Runtime Defense Analysis (RDA)
- - `scripts/03-static-analysis/` — semgrep scan + merge-findings
- - `scripts/04-android-15-16/` — Android 15/16 specific APIs
- - `scripts/05-scoring/` — MASVS v2 compliance scoring
- - `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`).
- - `scripts/07-tools/` — Core tools (frida-exploit-helper, generate-report, correlate-findings, mobsf-api-scan, burp-findings-export, rop-helper)
- - `auto-audit-static.sh` — Main orchestrator
- - `audit-android-components.sh` — Component audit
- **Exploitation**: `exploitation-guide`, `heap-exploitation`, `exploitation-decisions`, `android-binder-cve-2023-20938`
- **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`.
- **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)
- > **Loading Strategy**: Load reference files only when encountering the specific technical challenge they cover. Do NOT load all references at once.
- > **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).
- ---
- ## Platform-Specific Notes
- > 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.
- ## Known Implementation Gaps (as of remediation pass, April 2026)
- The following gaps were identified and partially mitigated during a full code + claims audit:
- - **Semgrep integration** (Phase 2.5): Previously completely non-functional (no `--json` flag was passed). Now fixed in `semgrep-scan.py`.
- - **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.
- - **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.
- - **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.
- - **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.
- - **Committed artifacts**: Many `__pycache__/` and `*.pyc` files were present. `.gitignore` has been expanded.
- These are tracked in the remediation plan for this change. Always run the preflight + validators before trusting a full audit in a new environment.
- > **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.
- > 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.
- # Android Pentesting Skill
- [](LICENSE)
- [](https://github.com/DragonJAR/Android-Pentesting-Skill/blob/main/SKILL.md)
- [](https://github.com/DragonJAR/iOS-Pentesting-Skill)
- [](https://www.DragonJAR.org)
- [](README.es.md)
- > 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.
- ## 🎯 What This Skill Does
- This skill turns an AI agent into an Android APK security auditor. It can:
- - Decode and inspect APKs with APKTool, JADX, APKiD, Android SDK tools, and Frida.
- - Map attack surface: manifest, exported components, deep links, WebViews, storage, crypto, networking, native code, and framework-specific code.
- - Run static analysis with curated grep patterns and MASTG-aligned Semgrep rules, then merge and deduplicate findings.
- - Trace source-to-sink flows and separate confirmed issues from findings that need dynamic validation.
- - Detect runtime defenses and RASP/shielding SDKs, then build authorized Frida bypass stacks using reusable profiles instead of duplicated logic.
- - 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.
- - Score and report findings with CVSS 4.0, MASVS mapping, executive risk context, JSON schemas, and professional report templates.
- - Support APK modification workflows: smali/resource patching, repackaging, signing, and validation.
- - Ingest APKs from a read-only Gmail mailbox (optional OAuth adapter) and audit on-device `/data/data` storage on rooted lab devices.
- > **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.
- ## 📦 Installation
- ### Option 1: Clone into Agent Skills Directory
- ```bash
- # 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
- ```bash
- # Clone to any location
- git clone https://github.com/DragonJAR/Android-Pentesting-Skill.git
- # Add to your agent's skill path configuration
- ```
- ## ⚙️ Prerequisites
- The skill expects these tools to be installed:
- | Tool | Version | Purpose |
- |------|---------|---------|
- | APKTool | 3.0.1+ | APK decoding/rebuilding (aapt2-only mode) |
- | JADX | 1.5.5+ | Java/Kotlin decompilation |
- | Android SDK | Platform 36+, Build 36+ | adb, aapt2, zipalign, apksigner |
- | Frida | 17.9+ | Dynamic instrumentation |
- | Objection | 1.12.4+ | Mobile exploration (maintenance mode) |
- | APKiD | 3.0.0+ | Framework detection |
- ### Verification
- Run the Python preflight check to verify all dependencies:
- ```bash
- python3 scripts/06-setup/preflight-check.py
- ```
- Shell variant for Linux or macOS with Homebrew Bash 4+:
- ```bash
- /opt/homebrew/bin/bash scripts/06-setup/preflight-check.sh
- ```
- Or, on systems where `/usr/bin/env bash` is Bash 4+:
- ```bash
- ./scripts/06-setup/preflight-check.sh
- ```
- PowerShell variant for Windows environments:
- ```powershell
- ./scripts/06-setup/preflight-check.ps1
- ```
- ## 🛡️ RASP Detect → Bypass Workflow
- The RASP workflow is intentionally DRY:
- 1. **Detect** protections with RDA.
- 2. **Map** triggered detectors to bypass profiles.
- 3. **Reuse** existing Frida scripts from `assets/frida-scripts/`.
- 4. **Print first, run only when authorized** with `--run --authorized-lab`.
- ```bash
- # 1) Detect RASP/runtime defenses
- bash scripts/02-rasp/runtime-defense-analyzer.sh app.apk com.target.app --output findings-rda.json
- # 2) Review available bypass profiles
- bash scripts/02-rasp/rasp-bypass-runner.sh --list-profiles
- # 3) Generate a reviewed Frida command from findings
- bash scripts/02-rasp/rasp-bypass-runner.sh \
- --package com.target.app \
- --from-rda findings-rda.json \
- --print-command
- # 4) Execute only in an authorized lab
- bash scripts/02-rasp/rasp-bypass-runner.sh \
- --package com.target.app \
- --from-rda findings-rda.json \
- --run --authorized-lab
- ```
- 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.
- ## 🚀 Usage Examples
- ### Example 1: Basic APK Audit
- **User prompt:**
- ```
- Audit this APK: /path/to/app.apk
- ```
- **Agent response:**
- ```
- I'll analyze the APK for security vulnerabilities.
- [Phase 0] Decoding APK with APKTool...
- [Phase 1] Analyzing AndroidManifest.xml...
- [Phase 2] Running targeted security patterns...
- [Phase 3] Tracing data flows...
- [Phase 5] Generating findings report...
- Found 3 issues:
- 1. [HIGH] Exported Activity Without Permission (M8: Security Misconfiguration)
- 2. [MEDIUM] Hardcoded API Key (M1: Improper Credential Usage)
- 3. [LOW] Debug Logging Enabled (M8: Security Misconfiguration)
- ```
- ### Example 2: Full Audit with All Modules
- **User prompt:**
- ```
- Audit this APK with all modules: runtime defense, semgrep, and MASVS scoring.
- ```
- **Agent response:**
- ```
- [Phase 0] Decoding APK with APKTool + JADX...
- [Phase 0] Detected framework: Flutter
- [Phase 1] Mapping attack surface from AndroidManifest.xml...
- [Phase 2] Running targeted grep patterns...
- [Phase 2.5] Running Semgrep MASTG rules (70+ rules)...
- [Phase 3] Tracing source-to-sink data flows...
- [Phase 4] Running Runtime Defense Analysis (18 catalog entries, 14 executable detectors)...
- [Phase 5] Classifying findings and calculating MASVS compliance score...
- MASVS Score: 72.6/100 (Grade: C)
- - 16/23 controls passed
- - 7 controls failed (Critical: 1, High: 1, Medium: 1, Low: 4)
- Found 4 issues:
- 1. [CRITICAL] Hardcoded API Key (M1: Improper Credential Usage)
- 2. [HIGH] Exported Activity with Intent Redirection (M8: Security Misconfiguration)
- 3. [MEDIUM] Weak SSL Certificate Validation (M5: Insecure Communication)
- 4. [LOW] Debug Mode Enabled (M8: Security Misconfiguration)
- ```
- ### Example 3: SSL Pinning Bypass
- **User prompt:**
- ```
- The app has SSL pinning. Bypass it with Frida and intercept traffic.
- ```
- **Agent response:**
- ```
- I'll use the SSL pinning bypass script to intercept HTTPS traffic.
- [1] Identifying SSL pinning implementation...
- Found: OkHttp3 CertificatePinner
- [2] Loading Frida script: ssl-pinning-bypass.js
- [3] Hooking CertificatePinner.check()
- [4] SSL pinning bypassed. Traffic now decrypted.
- Intercepted request:
- POST /api/login
- {"email": "user@example.com", "password": "secret123"}
- ```
- ### Example 4: React Native Analysis
- **User prompt:**
- ```
- Analyze this React Native APK for hardcoded secrets in the JavaScript bundle.
- ```
- **Agent response:**
- ```
- [Phase 0] Detected React Native framework (libhermes.so found)
- [Phase 0] Extracting JavaScript bundle from assets/index.android.bundle
- [Phase 2] Scanning for secrets in JavaScript bundle...
- Found 2 hardcoded secrets:
- - API_KEY = "sk_live_abc123..." at bundle.js:4521 (M1: Improper Credential Usage)
- - AWS_SECRET = "wJalrXUtnFEMI/K7MDENG..." at bundle.js:8912 (M1: Improper Credential Usage)
- ```
- ### Example 5: Flutter Analysis
- **User prompt:**
- ```
- Analyze this Flutter APK. I need to intercept HTTPS traffic from the app.
- ```
- **Agent response:**
- ```
- [Phase 0] Detected Flutter framework (libflutter.so found)
- [Phase 0] Flutter uses BoringSSL natively - Java SSL hooks won't work
- [Phase 0] Using Blutter to extract Dart code: python3 blutter.py lib/arm64-v8a/
- [Phase 4] Loading Frida script: native-hook.js (BoringSSL targets)
- [Phase 4] Hooking SSL_CTX_set_custom_verify() for certificate bypass
- [Phase 4] Hooking SSL_read/SSL_write() for traffic interception
- Flutter traffic now intercepted and decrypted.
- ```
- ### Example 6: APK Modification
- **User prompt:**
- ```
- Disable the root detection in this APK and repackage it.
- ```
- **Agent response:**
- ```
- [1] Decoding APK with APKTool...
- [2] Locating root detection code...
- Found: com/app/security/RootDetector.checkRoot()
- [3] Patching smali to return false...
- const/4 v0, 0x0 # Always return false
- [4] Rebuilding with APKTool...
- [5] Aligning with zipalign...
- [6] Signing with apksigner...
- [7] Verifying signature...
- Modified APK ready: app_patched.apk
- SHA-256: abc123def456...
- ```
- ### Example 7: Runtime Defense Analysis
- **User prompt:**
- ```
- Run the runtime defense analysis to check what protections this app has.
- ```
- **Agent response:**
- ```
- [Phase 4] Loading Runtime Defense Analysis...
- Detector catalog: 18 entries (14 executable Frida detectors + 4 backend/cloud entries marked not applicable).
- Executable detectors include:
- - rootbeer, safetynet, emulator, debug, frida_detect
- - screenshot, screenrecorded, custom
- - talsec, approov, dexguard, appdome, doverunner, digitalai
- Running passive detection...
- Results: 3 protections detected:
- - [DETECTED] Root detection (RootBeer library)
- - [DETECTED] Emulator detection
- - [NOT DETECTED] Frida detection
- findings-rda.json generated with full detector report.
- ```
- ## 📖 Skill Capabilities
- ### Static Analysis (Phases 0-3)
- | Capability | Description |
- |------------|-------------|
- | APK Decompilation | JADX for Java/Kotlin, APKTool for smali/resources |
- | Framework Detection | React Native, Flutter, Cordova, Xamarin, Native |
- | Obfuscation Analysis | ProGuard/R8, DexGuard, custom patterns |
- | Manifest Analysis | 50+ security checks for exported components, permissions, deep links |
- | IPC / Intent Abuse | Intent injection, nested intent relays, PendingIntent, FileProvider, deep link pivot patterns |
- | Secrets Detection | API keys, passwords, tokens in code and resources |
- | Data Flow Tracing | Source-to-sink methodology with confidence levels |
- | **Semgrep SAST (Phase 2.5)** | 70+ MASTG-aligned rules for automated code scanning |
- ### Dynamic Analysis (Phase 4)
- | Capability | Description |
- |------------|-------------|
- | Frida Scripts | 37 scripts for hooking, bypass, interception, and native triage |
- | 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). |
- | Root Detection Bypass | 30+ root packages, 80+ paths, native hooks (fopen, access, stat) plus a focused native root detection probe |
- | **Runtime Defense Analysis (RDA)** | 18 catalog entries, 14 executable Frida detectors, and authorized bypass profile runner |
- | Crypto Interception | Monitor Cipher, MessageDigest, Mac, Signature operations |
- | Biometric Bypass | BiometricPrompt, FingerprintManager, crypto-object binding |
- | Keystore Inspection | List entries, extract metadata, check security flags |
- | Network Interception | OkHttp chains, HttpURLConnection, WebSocket monitoring |
- | Native Hooking | JNI_OnLoad, RegisterNatives, by-offset hooks, and library-load-aware native probes |
- ### Frida Exploit Helper
- ```bash
- # List available bundled scripts
- python3 scripts/07-tools/frida-exploit-helper.py --list-scripts
- # Hook memory functions
- python3 scripts/07-tools/frida-exploit-helper.py -p com.target.app --hook malloc,free
- # Use bundled SSL pinning bypass script
- python3 scripts/07-tools/frida-exploit-helper.py -p com.target.app --script ssl-pinning-bypass
- # Memory layout analysis
- python3 scripts/07-tools/frida-exploit-helper.py -p com.target.app --layout
- # Runtime Defense Analysis (RDA) — detect app protections
- python3 scripts/07-tools/frida-exploit-helper.py -p com.target.app --runtime-defense
- ```
- ### Full Workflow with All Modules
- ```bash
- # Run static audit with Semgrep enrichment
- bash scripts/auto-audit-static.sh app.apk --semgrep
- # Run runtime defenses and scoring as explicit modules
- bash scripts/02-rasp/runtime-defense-analyzer.sh app.apk com.target.app --active-mode --authorized-lab --output findings-rda.json
- python3 scripts/03-static-analysis/semgrep-scan.py decoded/ --output semgrep.json
- python3 scripts/05-scoring/calculate-score.py findings.json --json-output
- ```
- ### APK Modification
- | Capability | Description |
- |------------|-------------|
- | Smali Patching | Modify Dalvik bytecode directly |
- | Resource Editing | Change XML, strings, configurations |
- | Static Pinning Tampering | Override `network_security_config`, replace pins, bundled certs, or `BKS/JKS` truststores |
- | Repackaging | Rebuild, align, sign with correct flow: zipalign → apksigner |
- ### Reporting (Phase 5)
- | Capability | Description |
- |------------|-------------|
- | CVSS 4.0 Scoring | FIRST.org compliant severity ratings |
- | **MASVS Compliance Score** | OWASP MASVS v2 control coverage with explicit pass/fail/not-tested semantics |
- | Executive Risk Score | Optional aggregate 0-100/A-F business-risk summary, separate from CVSS and MASVS |
- | OSINT Enrichment | Optional passive correlation of package, domains, endpoints, public leaks, and archived URLs |
- | Audit Modes | Presets for quick, static, full, protected-app, OSINT, and reporting-only workflows |
- | OWASP MASTG Mapping | Test IDs and MASVS categories |
- | Professional Templates | Executive summary, findings, remediation |
- ## 🔧 Skill Structure
- ```
- Android-Pentesting-Skill/
- ├── SKILL.md # Skill definition (Phases 0-5)
- ├── references/ # 90 reference/support files
- │ ├── attack-patterns.md # OWASP M1-M10 patterns
- │ ├── intent-injection.md # Nested intent / confused deputy guide
- │ ├── pendingintent-security.md # PendingIntent abuse and hardening
- │ ├── dynamic-analysis-setup.md # Frida/Objection + SSL pinning playbook
- │ ├── frida-scripts-index.md # Canonical bundled script catalog
- │ ├── cvss-scoring-guide.md # CVSS 4.0 methodology
- │ ├── reporting-templates.md # Finding templates
- │ ├── flutter-security.md # Flutter security guide
- │ ├── react-native-security.md # React Native security guide
- │ ├── android-keystore2-testing.md # Keystore2 testing (Android 12+)
- │ ├── biometric-testing-comprehensive.md # BiometricPrompt testing
- │ ├── deep-link-exploitation.md # Deep link attacks
- │ ├── project-manifest.md # Ground-truth file inventory
- │ └── ... (77 more)
- ├── assets/frida-scripts/ # 38 files (37 Frida scripts + README)
- │ ├── ssl-pinning-bypass.js # SSL pinning bypass
- │ ├── root-detection-bypass.js # Root detection bypass
- │ ├── native-root-detection-probe.js # Focused native root/RASP triage
- │ ├── native-hook.js # Generic JNI / native helper
- │ ├── biometric-bypass.js # Biometric auth bypass
- │ ├── network-interceptor.js # HTTP/HTTPS interception
- │ ├── crypto-intercept.js # Crypto operations hooking
- │ └── ... (30 more)
- ├── scripts/ # Utility and validation scripts
- │ ├── 00-ingestion/ # Optional input adapters (Gmail APK fetch)
- │ │ └── fetch-apk-gmail.py # Read-only Gmail → APK attachment ingester
- │ ├── 01-cross-platform/ # Framework-specific analysis
- │ │ ├── cordova-analysis.sh
- │ │ ├── flutter-analysis.sh
- │ │ ├── react-native-analysis.sh
- │ │ ├── unity-analysis.sh
- │ │ └── dotnet-maui-analysis.sh # MAUI / Xamarin: managed DLL extraction + decompilation
- │ ├── 02-rasp/ # Runtime Defense Analysis (RDA)
- │ │ ├── detector-catalog.json # 18 detector registry
- │ │ ├── runtime-defense-analyzer.sh # Phase 4 RDA entry point
- │ │ ├── rasp-bypass-runner.sh # Authorized bypass stack runner
- │ │ ├── bypass-profiles.json # DRY detector-to-bypass profile map
- │ │ ├── findings-schema.json # Shared findings schema
- │ │ └── rasp-detectors/ # 14 Frida detector scripts + 4 not-applicable catalog entries
- │ │ ├── rootbeer.js
- │ │ ├── safetynet.js
- │ │ ├── emulator.js
- │ │ ├── debug.js
- │ │ ├── frida-detect.js
- │ │ ├── screenshot.js
- │ │ ├── screenrecorded.js
- │ │ └── custom.js
- │ ├── 03-static-analysis/ # Semgrep SAST + merge
- │ │ ├── semgrep-scan.py # semgrep wrapper
- │ │ ├── merge-findings.py # Deduplication
- │ │ ├── update-rules.sh # Upstream rule sync
- │ │ ├── advanced-static-checks.sh # Beyond-semgrep static hardening probes
- │ │ ├── version-diff-audit.sh # Cross-version regression diff
- │ │ └── semgrep-rules/ # 70+ MASTG rules
- │ ├── 04-android-15-16/ # Android 15/16 specific scripts
- │ │ ├── android15-apis.js
- │ │ ├── passkey-test.js
- │ │ └── privacy-sandbox-test.sh
- │ ├── 05-scoring/ # MASVS compliance scoring
- │ │ ├── calculate-score.py # Score engine (0-100 + A-F)
- │ │ ├── masvs-matrix.json # 23 MASVS v2 controls
- │ │ ├── masvs-mapping.json # Finding-to-control mapping
- │ │ └── update-coverage.py # Coverage table generator
- │ ├── 06-setup/ # Preflight checks & validation
- │ │ ├── preflight-check.sh
- │ │ ├── preflight-check.py
- │ │ ├── preflight-check.ps1
- │ │ ├── validate-frida-scripts.sh
- │ │ └── validate-shell-scripts.sh
- │ ├── 07-tools/ # Core analysis tools
- │ │ ├── frida-exploit-helper.py
- │ │ ├── generate-report.py
- │ │ ├── rop-helper.py
- │ │ ├── correlate-findings.py
- │ │ ├── mobsf-api-scan.py
- │ │ ├── burp-findings-export.py
- │ │ ├── adb-backup-extract.sh # Pull /data/data via adb backup (no root)
- │ │ ├── drozer-automated.sh # Drozer IPC automation
- │ │ ├── firebase-check.sh # Firebase misconfiguration sweep
- │ │ ├── inspect-app-sandbox.sh # /data/data audit (rooted device/emulator)
- │ │ └── live-logcat-analyzer.py # Streaming logcat leak detector (tokens/PII/stack traces)
- │ ├── lib/ # Shared library (DRY helpers, severity, paths, MASVS)
- │ ├── auto-audit-static.sh # Main workflow orchestrator
- │ ├── audit-android-components.sh # Component security audit
- │ └── test-findings.json # Sample report input
- ├── references/schemas/ # 2 JSON schemas for report/finding contracts
- └── references/ai-prompts/ # AI-powered analysis prompts
- ├── java-security-analyzer.md # Java code analysis prompts
- ├── native-binary-analyzer.md # Native binary analysis prompts
- ├── exploit-generator.md # Exploit PoC generation prompts
- └── report-enhancer.md # Report enhancement prompts
- ```
- ## 🎓 Trigger Phrases
- The skill activates when the user says:
- - "audit this APK"
- - "analyze android app"
- - "mobile pentest"
- - "APK security"
- - "decompile APK"
- - "android vulnerability assessment"
- - "reverse engineer android"
- - "modify APK"
- - "bypass SSL pinning"
- - "bypass root detection"
- - "intent injection"
- - "deep link abuse"
- ## ⚠️ Limitations
- 1. **Dynamic analysis requires a device or emulator** — Frida needs a running Android system
- 2. **Some packers require manual unpacking** — DexGuard 9+, Arxan may need interactive debugging
- 3. **Android 14+ restrictions** — Certain Intent behaviors require explicit `-n package/activity` flags
- 4. **Frida version matching** — frida-server on device must match frida-tools on host exactly
- 5. **Flutter uses BoringSSL natively** — Java SSL hooks don't work, need native hooks
- ## 📚 Standards Alignment
- This skill is aligned with:
- - **OWASP MASTG** — Mobile Application Security Testing Guide
- - **OWASP MASVS** — Mobile Application Security Verification Standard
- - **Passive OSINT enrichment** — Scope-controlled public evidence correlation for APK findings
- - **OWASP Mobile Top 10 2024** — Top 10 mobile risks
- - **CVSS 4.0** — Common Vulnerability Scoring System
- ## 🔐 OWASP Mobile Top 10 (2024)
- | ID | Category |
- |----|----------|
- | M1 | Improper Credential Usage |
- | M2 | Inadequate Supply Chain Security |
- | M3 | Insecure Authentication/Authorization |
- | M4 | Insufficient Input/Output Validation |
- | M5 | Insecure Communication |
- | M6 | Inadequate Privacy Controls |
- | M7 | Insufficient Binary Protections |
- | M8 | Security Misconfiguration |
- | M9 | Insecure Data Storage |
- | M10 | Insufficient Cryptography |
- ## 🤝 Contributing
- Contributions are welcome! Please see the [references/](references/) directory for areas that need expansion.
- ## 📄 License
- Apache License 2.0 — See [LICENSE](LICENSE) for details.
- ## 👨💻 Author
- **DragonJAR SAS** — [https://www.DragonJAR.org](https://www.DragonJAR.org)
- [Experts in IT security services, proactive validation, and offensive security.](https://www.dragonjar.org/servicios-de-seguridad-informatica)
- ---
- ## 🔄 Source of Truth
- 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:
- ```bash
- git -C /path/to/Android-Pentesting-Skill pull
- rsync -a --delete --exclude '.git' --exclude '__pycache__' --exclude '.pytest_cache' \
- /path/to/Android-Pentesting-Skill/ ~/.agents/skills/android-pentesting-skill/
- ```
- Unsynchronized copies will drift and silently serve outdated references.
- **⚠️ 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
- #!/usr/bin/env bash
- if [ "${1:-}" = "--help" ] || [ "${1:-}" = "-h" ]; then
- cat <<EOF
- Android APK Audit - Preflight Check
- USAGE:
- $0 [--help|-h]
- Checks required Android APK audit tools and prints install guidance for missing dependencies.
- Use scripts/06-setup/preflight-check.py for JSON, strict, quiet, or cross-platform modes.
- EOF
- exit 0
- fi
- # Check bash version for associative arrays
- if [ -z "${BASH_VERSINFO:-}" ] || [ "${BASH_VERSINFO[0]}" -lt 4 ]; then
- newer_bash=""
- if [ -x /opt/homebrew/bin/bash ]; then
- newer_bash="/opt/homebrew/bin/bash"
- elif [ -x /usr/local/bin/bash ]; then
- newer_bash="/usr/local/bin/bash"
- fi
- echo "ERROR: This script must be run with bash 4+ (macOS default is bash 3.2)."
- echo "zsh is not supported."
- echo "Fix: brew install bash"
- if [ -n "$newer_bash" ]; then
- echo "Then run: $newer_bash \"$0\""
- else
- echo "Then run it with your Homebrew bash path, e.g. /opt/homebrew/bin/bash \"$0\""
- fi
- exit 1
- fi
- set -euo pipefail
- SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
- source "$SCRIPT_DIR/../lib/colors.sh"
- # Track results
- declare -A tool_status
- declare -A tool_version
- critical_missing=0
- optional_missing=0
- # OS Detection
- detect_os() {
- case "$(uname -s)" in
- Darwin)
- echo "macOS"
- return
- ;;
- Linux)
- if [ -f /etc/os-release ]; then
- . /etc/os-release
- if echo "$ID" | grep -qE "ubuntu|debian"; then
- echo "linux-debian"
- elif echo "$ID" | grep -q "arch"; then
- echo "linux-arch"
- elif echo "$ID" | grep -qE "fedora|rhel|centos"; then
- echo "linux-fedora"
- else
- echo "linux-other"
- fi
- else
- echo "linux-other"
- fi
- return
- ;;
- MINGW*|MSYS*|CYGWIN*)
- echo "windows"
- return
- ;;
- *)
- echo "unknown"
- return
- ;;
- esac
- }
- OS=$(detect_os)
- # Get install command for current OS
- get_install_cmd() {
- local tool=$1
- local os=$2
- case "$os" in
- macOS)
- case "$tool" in
- jadx) echo "brew install jadx" ;;
- apktool) echo "brew install apktool" ;;
- adb) echo "brew install --cask android-platform-tools" ;;
- frida) echo "pip3 install frida-tools" ;;
- objection) echo "pip3 install objection" ;;
- apkid) echo "pip3 install apkid" ;;
- ilspycmd) echo "dotnet tool install -g ilspycmd" ;;
- java) echo "brew install openjdk" ;;
- zipalign) echo "brew install --cask android-commandlinetools" ;;
- python3) echo "brew install python@3" ;;
- sqlite3) echo "brew install sqlite" ;;
- 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
- *) echo "manual installation required" ;;
- esac
- ;;
- linux-debian)
- case "$tool" in
- jadx) echo "sudo apt install jadx" ;;
- apktool) echo "sudo apt install apktool" ;;
- adb) echo "sudo apt install android-tools-adb" ;;
- frida) echo "sudo apt install frida-tools" ;;
- objection) echo "pip3 install objection" ;;
- apkid) echo "pip3 install apkid" ;;
- java) echo "sudo apt install default-jdk" ;;
- zipalign) echo "Install via Android SDK build-tools (android-sdk-build-tools)" ;;
- python3) echo "sudo apt install python3" ;;
- sqlite3) echo "sudo apt install sqlite3" ;;
- *) echo "sudo apt install $tool" ;;
- esac
- ;;
- linux-arch)
- case "$tool" in
- jadx) echo "yay -S jadx" ;;
- apktool) echo "sudo pacman -S apktool" ;;
- adb) echo "sudo pacman -S android-tools" ;;
- frida) echo "pip3 install frida-tools" ;;
- objection) echo "pip3 install objection" ;;
- apkid) echo "pip3 install apkid" ;;
- java) echo "sudo pacman -S jdk-openjdk" ;;
- zipalign) echo "sudo pacman -S android-tools" ;;
- python3) echo "sudo pacman -S python" ;;
- sqlite3) echo "sudo pacman -S sqlite" ;;
- *) echo "sudo pacman -S $tool" ;;
- esac
- ;;
- linux-fedora)
- case "$tool" in
- jadx) echo "sudo dnf install jadx" ;;
- apktool) echo "sudo dnf install apktool" ;;
- adb) echo "sudo dnf install android-tools" ;;
- frida) echo "pip3 install frida-tools" ;;
- objection) echo "pip3 install objection" ;;
- apkid) echo "pip3 install apkid" ;;
- java) echo "sudo dnf install java-latest-openjdk-devel" ;;
- zipalign) echo "sudo dnf install android-tools" ;;
- python3) echo "sudo dnf install python3" ;;
- sqlite3) echo "sudo dnf install sqlite" ;;
- *) echo "sudo dnf install $tool" ;;
- esac
- ;;
- windows)
- case "$tool" in
- jadx) echo "choco install jadx or scoop install jadx" ;;
- apktool) echo "choco install apktool or scoop install apktool" ;;
- adb) echo "choco install adb or scoop install adb" ;;
- frida) echo "pip3 install frida-tools" ;;
- objection) echo "pip3 install objection" ;;
- apkid) echo "pip3 install apkid" ;;
- java) echo "choco install openjdk or scoop install openjdk" ;;
- zipalign) echo "choco install android-sdk or scoop install android-sdk" ;;
- python3) echo "choco install python or scoop install python" ;;
- sqlite3) echo "choco install sqlite or scoop install sqlite" ;;
- *) echo "manual installation required" ;;
- esac
- ;;
- *)
- echo "manual installation required"
- ;;
- esac
- }
- # Compare semantic versions: version_ge "1.2.3" "1.2.0" returns 0 (true)
- version_ge() {
- local required="$1"
- local installed="$2"
- # Handle cases where version extraction might fail
- if [ -z "$installed" ] || [ "$installed" = "unknown" ]; then
- return 1
- fi
- # Extract numeric part only (e.g., "1.4.0" from "jadx 1.4.0")
- required=$(echo "$required" | sed 's/[^0-9.]//g')
- installed=$(echo "$installed" | sed 's/[^0-9.]//g')
- # Compare using sort -V (version sort)
- if printf '%s\n%s\n' "$required" "$installed" | sort -V -C 2>/dev/null; then
- return 0
- else
- return 1
- fi
- }
- # Check if a tool is installed
- check_tool() {
- local tool=$1
- local critical=$2
- local cmd=$3
- local version_cmd=$4
- if command -v "$cmd" &>/dev/null; then
- local version=""
- if [ -n "$version_cmd" ]; then
- # Special handling for java -version (writes to stderr)
- if [ "$tool" = "java" ]; then
- version=$("$version_cmd" 2>&1 | head -1 || echo "unknown")
- else
- version=$("$version_cmd" 2>/dev/null | head -1 || echo "unknown")
- fi
- fi
- tool_status[$tool]="found"
- tool_version[$tool]="$version"
- echo "${GREEN}✅${RESET} $tool found ${BLUE}($version)${RESET}"
- else
- local install_cmd=$(get_install_cmd "$tool" "$OS")
- tool_status[$tool]="missing"
- tool_version[$tool]=""
- echo "${RED}❌${RESET} $tool missing - ${YELLOW}$install_cmd${RESET}"
- if [ "$critical" = "true" ]; then
- : $((critical_missing++))
- else
- : $((optional_missing++))
- fi
- fi
- }
- # Print header
- echo ""
- echo "${BLUE}========================================${RESET}"
- echo "${BLUE} Android APK Audit - Preflight Check ${RESET}"
- echo "${BLUE}========================================${RESET}"
- echo "${BLUE}OS: ${RESET}$OS"
- echo "${BLUE}========================================${RESET}"
- echo ""
- # Critical tools
- echo "${BLUE}Critical Tools:${RESET}"
- check_tool "jadx" "true" "jadx" "jadx --version"
- check_tool "apktool" "true" "apktool" "apktool --version"
- check_tool "java" "true" "java" "java -version"
- # Version-specific warnings for critical tools
- echo ""
- echo "${BLUE}Version Checks:${RESET}"
- # jadx: warn if < 1.4
- if command -v jadx &>/dev/null; then
- jadx_version=$(jadx --version 2>/dev/null | head -1 || echo "")
- if ! version_ge "1.4" "$jadx_version"; then
- echo "${YELLOW}⚠️${RESET} jadx version $jadx_version may be old — consider upgrading to 1.4+ for better decompilation"
- fi
- fi
- # apktool: warn if >= 3.0 (requires -f/--force to overwrite existing dirs)
- if command -v apktool &>/dev/null; then
- apktool_version=$(apktool --version 2>/dev/null | head -1 || echo "")
- if version_ge "3.0" "$apktool_version"; then
- echo "${YELLOW}⚠️${RESET} apktool $apktool_version detected — requires -f/--force when the output dir exists; scripts have been updated"
- fi
- fi
- echo ""
- # grep or ripgrep (at least one required)
- echo "${BLUE}Search Tools (grep or rg required):${RESET}"
- grep_found=false
- rg_found=false
- if command -v grep &>/dev/null; then
- grep --version &>/dev/null
- tool_status["grep"]="found"
- tool_version["grep"]="$(grep --version 2>/dev/null | head -1)"
- echo "${GREEN}✅${RESET} grep found ${BLUE}($(grep --version 2>/dev/null | head -1))${RESET}"
- grep_found=true
- else
- echo "${RED}❌${RESET} grep missing - ${YELLOW}$(get_install_cmd "grep" "$OS")${RESET}"
- fi
- if command -v rg &>/dev/null; then
- rg --version &>/dev/null
- tool_status["rg"]="found"
- tool_version["rg"]="$(rg --version 2>/dev/null | head -1)"
- echo "${GREEN}✅${RESET} ripgrep (rg) found ${BLUE}($(rg --version 2>/dev/null | head -1))${RESET}"
- rg_found=true
- else
- echo "${YELLOW}⚠️${RESET} ripgrep (rg) missing - ${YELLOW}$(get_install_cmd "ripgrep" "$OS")${RESET}"
- fi
- # Check for GNU grep on macOS (installed as ggrep via brew)
- if [ "$OS" = "macOS" ]; then
- if command -v ggrep &>/dev/null; then
- tool_status["ggrep"]="found"
- tool_version["ggrep"]="$(ggrep --version 2>/dev/null | head -1)"
- echo "${GREEN}✅${RESET} GNU grep (ggrep) found ${BLUE}($(ggrep --version 2>/dev/null | head -1))${RESET}"
- echo "${BLUE}ℹ️${RESET} Use 'ggrep -P' for PCRE patterns on macOS"
- else
- echo "${YELLOW}ℹ️${RESET} GNU grep not installed — PCRE patterns require: ${YELLOW}brew install grep${RESET}"
- fi
- fi
- if [ "$grep_found" = false ] && [ "$rg_found" = false ]; then
- : $((critical_missing++))
- fi
- echo ""
- # Check adb (critical for dynamic analysis)
- check_tool "adb" "true" "adb" "adb version"
- echo ""
- # Optional tools
- echo "${BLUE}Optional Tools:${RESET}"
- check_tool "frida" "false" "frida" "frida --version"
- check_tool "objection" "false" "objection" "objection --version"
- check_tool "apkid" "false" "apkid" "apkid --version"
- check_tool "ilspycmd" "false" "ilspycmd" "ilspycmd --version"
- check_tool "zipalign" "false" "zipalign" "zipalign -v"
- check_tool "keytool" "false" "keytool" "keytool -help"
- check_tool "jarsigner" "false" "jarsigner" "jarsigner -help"
- check_tool "apksigner" "false" "apksigner" "apksigner --version"
- check_tool "python3" "false" "python3" "python3 --version"
- check_tool "strings" "false" "strings" ""
- check_tool "sqlite3" "false" "sqlite3" "sqlite3 --version"
- check_tool "semgrep" "false" "semgrep" "semgrep --version"
- check_tool "android-cli" "false" "android" "android --version"
- echo ""
- # Version-specific warnings for optional tools
- echo "${BLUE}Optional Version Checks:${RESET}"
- # frida: warn if >= 16 (--no-pause deprecated in frida 16+)
- if command -v frida &>/dev/null; then
- frida_version=$(frida --version 2>/dev/null | head -1 || echo "")
- if version_ge "16" "$frida_version"; then
- echo "${YELLOW}⚠️${RESET} frida $frida_version — --no-pause flag is deprecated; scripts have been updated"
- fi
- fi
- # semgrep: warn if < 1.0 (older versions may have compatibility issues)
- if command -v semgrep &>/dev/null; then
- semgrep_version=$(semgrep --version 2>/dev/null | head -1 || echo "")
- if ! version_ge "1.0" "$semgrep_version"; then
- echo "${YELLOW}⚠️${RESET} semgrep version $semgrep_version may be old — consider upgrading to 1.0+"
- fi
- fi
- echo ""
- # Summary
- total_critical=5
- total_found_critical=$((total_critical - critical_missing))
- total_optional=11
- total_found_optional=$((total_optional - optional_missing))
- total_tools=$((total_critical + total_optional))
- total_found=$((total_found_critical + total_found_optional))
- echo "${BLUE}========================================${RESET}"
- echo "${BLUE}Summary:${RESET}"
- echo "${GREEN}✅${RESET} $total_found/$total_tools tools found"
- echo "${RED}❌${RESET} $critical_missing critical tools missing"
- echo "${YELLOW}⚠️${RESET} $optional_missing optional tools missing"
- if [ "$critical_missing" -gt 0 ]; then
- echo ""
- echo "${RED}Missing critical tools:${RESET}"
- for tool in "${!tool_status[@]}"; do
- if [ "${tool_status[$tool]}" = "missing" ]; then
- case "$tool" in
- jadx|apktool|java|adb|grep) echo " - $tool" ;;
- esac
- fi
- done
- echo ""
- echo "${RED}CRITICAL: Install missing tools to proceed with APK audit${RESET}"
- exit 1
- else
- echo ""
- echo "${GREEN}✅ All critical tools installed! Ready for APK audit.${RESET}"
- exit 0
- fi
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.