# Android

> **Skill Level**: Intermediate\
> **Prerequisites**: Java/Kotlin basics, Android architecture

## Tools

### Extract

```
# Jadx - decompiler gui
jadx-gui
# Jadx - decomp cli (with deobf)
jadx -d path/to/extract/ --deobf app_name.apk

# Apkx decompiler
apkx example.apk 

# Apktool
apktool d app_name.apk
```

### Get sensitive info

```
# Urls and secrets
# https://github.com/dwisiswant0/apkleaks
python apkleaks.py -f ~/path/to/file.apk

# Analyze URLs in apk:
# https://github.com/shivsahni/APKEnum
python APKEnum.py -p ~/Downloads/app-debug.apk

# Quick wins tool (go branch)
# https://github.com/mzfr/slicer
slicer -d path/to/extact/apk

# Unpack apk and find interesting strings
apktool d app_name.apk
cd apk_folder
grep -EHirn "accesskey|admin|aes|api_key|apikey|checkClientTrusted|crypt|http:|https:|password|pinning|secret|SHA256|SharedPreferences|superuser|token|X509TrustManager|insert into"
grep -Phro "(https?://)[\w\.-/]+[\"'\`]" | sed 's#"##g' | anew | grep -v "w3\|android\|github\|http://schemas.android\|google\|http://goo.gl"

# Apk analyzer
# https://github.com/Cyber-Buddy/APKHunt

# Regex FCM Server Keys for push notification services control
AAAA[A-Za-z0-9_-]{7}:[A-Za-z0-9_-]{140}
AIza[0-9A-Za-z_-]{35}

# FCM Google Server Keys Validation
# https://github.com/adarshshetty18/fcm_server_key
python3 fcmserverkey.py file.apk

# Facebook Static Analysis Tool
https://github.com/facebook/mariana-trench/

# Manifest.xml findings:
android:allowBackup = TRUE
android:debuggable = TRUE
andorid:exported= TRUE or not set (within <provider>-Tag) --> allows external app to access data
android.permission.WRITE_EXTERNAL_STORAGE / READ_EXTERNAL_STORAGE (ONLY IF sensitive data was stored/read externally)
Use of permissions
            e.g. the app opens website in external browser (not inApp), however requires "android.permission.INTERNET" --> false usage of permissions. (over-privileged)
            "android:protectionLevel" was not set properly (<permission android:name="my_custom_permission_name" android:protectionLevel="signature"/>)
            missing android:permission (permission tags limit exposure to other apps)
```

### Static analyzers

```
# Android Malware Analyzer
# https://github.com/quark-engine/quark-engine
pipenv shell
quark -a test.apk -r rules/ --detail

# Androtickler
https://github.com/ernw/AndroTickler
java -jar AndroTickler.jar

# androbugs.py
python androbugs.py -f /root/android.apk

# MobSF
# https://github.com/MobSF/Mobile-Security-Framework-MobSF

- Findings:
Cleartext credentials (includes base64 encoded or weak encrypted ones)
Credentials cracked (brute-force, guessing, decrypted with stored cryptographic-key, ...)
File permission MODE_WORLD_READABLE / MODE_WORLD_WRITEABLE (other apps/users are able to read/write)
If http is in use (no SSL)
Anything that shouldn't be there (debug info, comments wiht info disclosure, ...)
```

## Manual analysis (adb, frida, objection, etc...)

```
# Good Checklist
https://mobexler.com/checklist.htm#android

# Adb
# https://developer.android.com/studio/command-line/adb?hl=es-419
adb connect IP:PORT/ID
adb devices
adb shell
adb push
adb install
adb shell pm list packages # List all installed packages
adb shell pm path xx.package.name


# DeviceId
adb shell
settings get secure android_id
adb shell sqlite3 /data/data/com.android.providers.settings/databases/settings.db "select value from secure where name = 'android_id'"

# Frida (rooted device method)
# https://github.com/frida/frida/releases
adb root
adb push /root/Downloads/frida-server-12.7.24-android-arm /data/local/tmp/. # Linux
adb push C:\Users\username\Downloads\frida-server-12.8.11-android-arm /data/local/tmp/. # Windows
adb root
adb shell "chmod 755 /data/local/tmp/frida-server && /data/local/tmp/frida-server &"
frida-ps -U # Check frida running correctly
# Run Frida script
frida -U -f com.vendor.app.version -l PATH\fridaScript.js --no-pause

# Easy way to load Frida Server in Rooted Device
https://github.com/dineshshetty/FridaLoader

# Frida (NON rooted device) a.k.a. patch the apk
# a) Lief injector method
# https://gitlab.com/jlajara/frida-gadget-lief-injector
# b) Objection and dalvik bytecode method
https://github.com/sensepost/objection/wiki/Patching-Android-Applications#patching---patching-an-apk

# Frida resources
https://codeshare.frida.re/
https://github.com/dweinstein/awesome-frida
https://rehex.ninja/posts/frida-cheatsheet/
https://github.com/androidmalware/android_frida_scripts

# Objection
# https://github.com/sensepost/objection
objection --gadget com.vendor.app.xx explore
android sslpinning disable

# Android Backup files (*.ab files)
( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) |  tar xfvz -

# Useful apps:
# Xposed Framework
# RootCloak
# SSLUnpinning

# Check Info Stored
find /data/app -type f -exec grep --color -Hsiran "FINDTHIS" {} \;
find /storage/sdcard0/Android/ -maxdepth 7 -exec ls -dl \{\} \;

/data/data/com.app/database/keyvalue.db
/data/data/com.app/database/sqlite
/data/app/
/data/user/0/
/storage/emulated/0/Android/data/
/storage/emulated/0/Android/obb/
/assets
/res/raw
/target/global/Constants.java

# Check logs during app usage
https://github.com/JakeWharton/pidcat

# Download apks
https://apkpure.com
https://apps.evozi.com/apk-downloader/
https://apkcombo.com/
```

### Burp Cert Installation > Android 7.0

```bash
#!/bin/bash
# Export only certificate in burp as DER format
openssl x509 -inform DER -in cacert.der -out cacert.pem
export CERT_HASH=$(openssl x509 -inform PEM -subject_hash_old -in cacert.pem | head -1)
adb root && adb remount
adb push cacert.pem "/sdcard/${CERT_HASH}.0"
adb shell su -c "mv /sdcard/${CERT_HASH}.0 /system/etc/security/cacerts"
adb shell su -c "chmod 644 /system/etc/security/cacerts/${CERT_HASH}.0"
rm -rf cacert.*
# Reboot device
```

## Tips

```
Recon:
- AndroidManifest.xml (basically a blueprint for the application)
Find exported components, api keys, custom deep link schemas, schema endpoints etc.
- resources.arsc/strings.xml
Developers are encouraged to store strings in this file instead of hard coding in application.
- res/xml/file_paths.xml
Shows file save paths.
- Search source code recursively
Especially BuildConfig files.
- Look for firebase DB:
Decompiled apk: Resources/resources.arsc/res/values/strings.xml, search for "firebsae.io" and try to access:
https://*.firebase.io/.json

API Keys:
- String references in Android Classes
getString(R.string.cmVzb3VyY2VzX3lv)
cmVzb3VyY2VzX3lv is the string resource label.
- Find these string references in strings.xml
apikeyhere
- Piece together the domains and required params in source code

Exported components:
- Activities - Entry points for application interactions of components specified in AndroidManifest.xml.
    Has several states managed by callbacks such as onCreate().
   →  Access to protected intents via exported Activities
    One exported activity that accepts a user provided intent can expose protected intents.
   → Access to sensitive data via exported Activity
    Often combined with deep links to steal data via unvalidated parameters. Write session tokens to an
    external file.
   → Access to sensitive files, stealing files, replacing imported files via exported Activities
    external-files-path, external-path
    Public app directories
   → Look for "content://" in source code
- Service - Supplies additional functionality in the background.
   → Custom file upload service example that is vulnerable because android:exported="true". When exported by third party
  applications can send data to the service or steal sensitive data from applications depending on the services   function. Check if params and intent data can be set with proof of concept application.
- Broadcast receivers - Receives broadcasts from events of interest. Usually specified broadcasted intents in the broadcast receiver activity.
   → Vulnerable when receiver is exported and accepts user provided broadcasts.
   → Any application, including malicious ones, can send an intent to this broadcast receiver causing it to be triggered without any restrictions.
- Content providers - Helps applications manage access to stored data and ways to share data with other Android applications
   → Content providers that connect to sqlite can be exploited via SQL injection by third party apps.

Deep links
- In Android, a deep link is a link that takes you directly to a specific destination within an app.
- Think of deep links as Android urls to specific parts of the application.
- Usually mirrors web application except with a different schema that navigate directory to specific Android activities.
- Verified deep links can only use http and https schemas. Sometimes developers keep custom schemas for testing new
features.
- Type of vulnerabilities are based on how the scheme://, host://, and parameters are validated
   → CSRF - Test when autoVerify=”true” is not present in AndroidManifest.xml It’s easier.
   → Open redirect - Test when custom schemes do not verify endpoint parameters or hosts
   → XSS - Test when endpoint parameters or host not validated, addJavaScriptInterface and
   → setJavascriptEnabled(true); is used.
   → LFI - Test when deep link parameters aren’t validated. appschema://app/goto?file=
   
Database encryption
- Check database is encrypted under /data/data/<package_name>/
- Check in source code for database credentials

Allowed backup
- Lead to sensitive information disclosure
- adb backup com.vendor.app

Logging Enabled
- Check logcat when login and any action performed

Storing Sensitive Data in External Storage
- Check data stored after usage /sdcard/android/data/com.vendor.app/

Weak Hashing Algorithms 
- MD5 is a weak algorythm and have collisions

Predictable Random Number Generator (PRNG)
- The java.util.Random function is predictable

Hard-coded Data
- Hard-coded user authentication information (credentials, PINs, etc.)
- Hard-coded cryptographic keys.
- Hard-coded keys used for encrypted databases.
- Hard-coded API keys/private
- Hard-coded keys that have been encoded or encrypted (e.g. base64 encoded, XOR encrypted, etc.).
- Hard-coded server IP addresses.

Debug Mode enabled
- Start a shell on Android and gain an interactive shell with run-as command
- run-as com.vendor.app
- adb exec-out run-as com.vendor.app cat databases/appName > appNameDB-copy

If you get built-in WebView and try to access:
appscheme://webview?url=https://google.com
appscheme://webview?url=javascript:document.write(document.domain)

If install apk in Genymotion fails with "INSTALL_FAILED_NO_MATCHING_ABIS":
- Apk is compiled only for ARM
- Download zip for your Android version here https://github.com/m9rco/Genymotion_ARM_Translation
- Move zip to VM and flash
https://pentester.land/tips-n-tricks/2018/10/19/installing-arm-android-apps-on-genymotion-devices.html
```

## Mindmaps

![](/files/-M72_YwfAB8MOh1N4ExV)

![](/files/-MG338numhpA3hG_ZBw_)

## Flutter Applications

Flutter apps compile to native code, making traditional decompilation harder. Here's how to test them:

### Identifying Flutter Apps

```bash
# Check APK for Flutter markers
unzip -l app.apk | grep -E "libflutter|libapp"

# Flutter apps contain:
# - lib/arm64-v8a/libflutter.so
# - lib/arm64-v8a/libapp.so (compiled Dart code)

# Check for Flutter engine
strings libflutter.so | grep -i flutter
```

### Static Analysis

```bash
# Extract Dart snapshot
# Flutter compiles Dart to AOT snapshot in libapp.so

# reFlutter - Flutter reverse engineering
# https://github.com/nickcano/ReFlutter
reflutter app.apk

# Doldrums - Dart/Flutter snapshot parser
# https://github.com/nickcano/doldrums
doldrums libapp.so

# blutter - Flutter reverse engineering framework
# https://github.com/nickcano/blutter
blutter libapp.so
```

### Dynamic Analysis

```bash
# Frida with Flutter
# Flutter uses Dart runtime, need special hooks

# reFlutter automated patching
# Creates patched APK with traffic interception
reflutter app.apk -b burp

# SSL Pinning bypass for Flutter
# https://github.com/nickcano/reflutter
# Patches libflutter.so to disable certificate verification

# Manual Frida hook for Flutter HTTP
# Flutter uses BoringSSL, need to hook ssl_crypto_x509_session_verify_cert_chain
```

### Common Vulnerabilities

```
1. Hardcoded secrets in Dart code
   - API keys, credentials compiled into libapp.so
   - Use strings/reFlutter to extract

2. Insecure data storage
   - shared_preferences (plain text)
   - sqflite databases
   - Check /data/data/<package>/shared_prefs/

3. Insufficient transport security
   - Flutter ignores system CA store by default
   - Developers must explicitly add certificate validation

4. Deep link vulnerabilities
   - Same as native Android
   - Check pubspec.yaml for app_links configuration
```

## React Native Applications

React Native apps use JavaScript, making analysis easier than Flutter.

### Identifying React Native Apps

```bash
# Check for React Native markers
unzip -l app.apk | grep -E "index.android.bundle|libreactnative"

# React Native apps contain:
# - assets/index.android.bundle (JavaScript code)
# - lib/*/libreactnativejni.so

# Check JavaScript bundle
strings assets/index.android.bundle | head -50
```

### Extracting JavaScript Code

```bash
# JavaScript is in index.android.bundle
unzip app.apk -d extracted/
cat extracted/assets/index.android.bundle

# If minified, use beautifier
# https://beautifier.io/
# Or js-beautify
js-beautify index.android.bundle > readable.js

# Search for sensitive data
grep -E "api[_-]?key|secret|password|token" readable.js
grep -E "https?://" readable.js | sort -u
```

### Hermes Bytecode

```bash
# Newer React Native apps may use Hermes engine
# Hermes compiles JS to bytecode

# Check if Hermes is used
file assets/index.android.bundle
# Output: "Hermes JavaScript bytecode" = Hermes enabled

# Decompile Hermes bytecode
# https://github.com/nickcano/hermes-dec
hermes-dec index.android.bundle -o decompiled.js

# hbctool - Hermes bytecode tool
# https://github.com/nickcano/pocs/tree/master/nickcano/nickcano/nickcano/nickcano/nickcano
hbctool disasm index.android.bundle
```

### Dynamic Analysis

```bash
# Frida works well with React Native
# Hook JavaScript bridge

# List all loaded classes
frida -U -f com.app.name -l rn_hooks.js

# SSL Pinning bypass (React Native)
# Usually uses OkHttp or fetch
frida -U -f com.app.name -l ssl_bypass.js

# React Native specific hooks
# https://github.com/nickcano/nickcano
```

### Common Vulnerabilities

```
1. Exposed JavaScript source code
   - All app logic visible in index.android.bundle
   - API endpoints, business logic exposed

2. AsyncStorage insecure storage
   - Stores data in plain text SQLite
   - Check /data/data/<package>/databases/RKStorage

3. Deep linking vulnerabilities
   - Check Linking.addEventListener handlers
   - URL parameter injection

4. JavaScript injection
   - WebView with evaluateJavascript
   - User input in JS execution context

5. Insecure native modules
   - Custom native code may have vulnerabilities
   - Review Java/Kotlin bridges
```

## Mobile API Security

### Common API Issues in Mobile Apps

```bash
# Traffic interception setup
# 1. Install Burp CA on device
# 2. Configure proxy
# 3. Bypass SSL pinning if needed

# Look for:
# - Hardcoded API keys
# - Insecure authentication (API key only, no user token)
# - Broken object-level authorization (BOLA)
# - Missing rate limiting
# - Excessive data exposure
# - Mass assignment vulnerabilities
```

### Authentication Testing

```bash
# Test token handling
# - JWT vulnerabilities (alg:none, weak secret)
# - Token expiration
# - Token storage (SharedPreferences vs Keystore)

# Test session management
# - Logout invalidation
# - Concurrent sessions
# - Session timeout
```

### API-Specific Tools

```bash
# Mobile API security testing
# https://github.com/nickcano/mitmproxy
mitmproxy --mode regular --ssl-insecure

# Postman/Insomnia for API testing
# Import requests from Burp

# Frida to extract API tokens
frida -U -f com.app.name -l extract_tokens.js
```

## OWASP MASTG Mapping

Key testing areas mapped to OWASP Mobile Application Security Testing Guide:

| MASTG Category   | What to Test                                      |
| ---------------- | ------------------------------------------------- |
| MASVS-STORAGE    | Data storage, logs, backups, clipboard            |
| MASVS-CRYPTO     | Crypto implementation, key storage                |
| MASVS-AUTH       | Authentication, session management                |
| MASVS-NETWORK    | TLS, certificate pinning, network security config |
| MASVS-PLATFORM   | WebViews, deep links, IPC                         |
| MASVS-CODE       | Code quality, reverse engineering                 |
| MASVS-RESILIENCE | Anti-tampering, obfuscation                       |

Reference: [OWASP MASTG](https://mas.owasp.org/MASTG/)

## Android 14-15 Security Changes

### Android 14 Security Enhancements

```bash
# 1. Credential Manager API
# Unified API for passwords, passkeys, and federated identity
# Apps should migrate from legacy auth
# Test credential storage and handling

# 2. Partial Media Access
# Users can grant access to specific photos/videos
# Test app behavior with limited media permissions
# Ensure app handles partial access gracefully

# 3. Runtime Registered Broadcast Receivers
# Must declare RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED
# Check for exported receivers in dynamic registration

# 4. Intent Sender Improvements
# Stronger package validation for PendingIntents
# Test intent handling with spoofed packages

# 5. Minimum Target SDK Requirements
# Apps targeting <SDK 23 can't be installed on Android 14+
# Older test apps may not install
```

### Testing on Android 14+

```bash
# Check target SDK
aapt dump badging app.apk | grep targetSdkVersion

# Review network security config
# /res/xml/network_security_config.xml
cat res/xml/network_security_config.xml

# Android 14 restricts cleartext traffic more strictly
# Ensure proper TLS handling

# Photo Picker
# Apps can no longer access all photos without permission
# Test with READ_MEDIA_IMAGES/READ_MEDIA_VIDEO/READ_MEDIA_VISUAL_USER_SELECTED

# Background Activity Restrictions
# Apps can't start activities from background on Android 14+
# Test notification-triggered activities
```

### Android 15 Security Features

```bash
# 1. Private Space
# Secondary user profile for sensitive apps
# Apps in private space are hidden
# Test app behavior across profiles

# 2. Enhanced Intent Security
# Stricter intent resolution
# Package name verification for implicit intents
# Test intent hijacking scenarios

# 3. Minimum Target SDK
# Apps must target SDK 24+ on Android 15
# Very old apps won't install

# 4. Hardware Security Module (HSM) Integration
# Enhanced key attestation
# Test secure key storage implementations

# 5. Screen Recording Detection
# Apps can detect when being recorded
# Test screen capture protection implementations
```

### Proxy Setup Changes

```bash
# Android 14+ Proxy Setup
# Certificate installation more restricted

# Method 1: Install as user certificate (limited trust)
# Settings → Security → Encryption & credentials → Install certificate

# Method 2: System certificate (requires root)
# Convert Burp cert to Android format
openssl x509 -inform DER -in cacert.der -out cacert.pem
HASH=$(openssl x509 -inform PEM -subject_hash_old -in cacert.pem | head -1)
mv cacert.pem $HASH.0
adb push $HASH.0 /sdcard/
adb shell su -c "mount -o rw,remount /"
adb shell su -c "cp /sdcard/$HASH.0 /system/etc/security/cacerts/"
adb shell su -c "chmod 644 /system/etc/security/cacerts/$HASH.0"

# Method 3: Network Security Config patch
# Add debug-overrides to allow user certificates
<network-security-config>
    <debug-overrides>
        <trust-anchors>
            <certificates src="user" />
        </trust-anchors>
    </debug-overrides>
</network-security-config>

# Method 4: Frida/Objection SSL bypass
objection --gadget com.app.name explore
android sslpinning disable

# Android 15 additional considerations
# May need to bypass certificate transparency
# Check for pinned public keys in addition to certificates
```

### Bypassing New Protections

```bash
# Root Detection on Android 14+
# More sophisticated detection methods
# Use Magisk Hide or Shamiko for hiding root

# SafetyNet → Play Integrity API Migration
# Apps moving from SafetyNet to Play Integrity
# Play Integrity is harder to bypass
# May need hardware attestation bypass

# Frida Detection Bypass
# Modern apps detect Frida more effectively
# Use Frida Stalker mode or custom gadget builds
# https://github.com/nickcano/Magisk-Frida-Service

# Testing Protected Apps
# Banking apps have strong protection
# Combine: Rooted device + Magisk + Shamiko + LSPosed + DisableFlagSecure
# Consider emulator detection bypass

# Background Process Restrictions
# Apps can't easily maintain background connections
# May affect persistent testing tools
```

## Related Topics

* [iOS Testing](/mobile/ios.md) - iOS mobile security
* [API Security](/enumeration/web/api-security.md) - API testing
* [WebAuthn](/others/webauthn-passkeys.md) - Passkey testing


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.pentest-book.com/mobile/android.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
