Skip to content

Android Dynamic Analysis - Watching Apps in Action

Overview - Runtime Testing and Monitoring

Dynamic analysis is where you actually run the app and watch what it does. While static analysis tells you what the code says it will do, dynamic analysis shows you what it actually does. This is where you find runtime vulnerabilities, behavior issues, and security problems that only appear when the app is executing.

Why Dynamic Analysis Matters:

Static analysis can't catch everything: - Runtime behavior that differs from code - Network communications and protocols - Dynamic code loading - Runtime protection mechanisms - Memory-related issues - real world user interactions

The Process:

  1. Install: Put the app on a test device
  2. Monitor: Watch logs, network, file system, memory
  3. Interact: Use the app normally, trigger all features
  4. Analyze: Review captured data, identify anomalies
  5. Test: Attempt exploitation, verify vulnerabilities
  6. Document: Record findings, evidence, exploitation steps

What You'll Find:

  • Runtime permissions misuse
  • Sensitive data in logs (logcat)
  • Network traffic issues
  • File system access patterns
  • Memory leaks and sensitive data
  • Crash and error handling
  • Behavior that differs from static analysis

Prerequisites: Understanding of Android Basics, ADB Usage, and Static Analysis. You need to know how to use ADB, read logcat, and understand Android's runtime behavior.

Table of Contents

  1. Logcat Monitoring
  2. Runtime Process Inspection
  3. Network Traffic Analysis
  4. File System Monitoring
  5. Memory Analysis
  6. UI Automation
  7. Crash Analysis
  8. Behavior Analysis

Logcat Monitoring

Overview

Logcat is Android's logging system. Every app generates logs, and many apps leak sensitive information through them. Monitoring logcat reveals: - API keys and tokens - User credentials - Personal information - Debug messages - Error details - Internal app state

Basic Logcat Usage

# View all logs
adb logcat

# Filter by app package
adb logcat | grep com.example.app

# Filter by log level (verbose, debug, info, warn, error)
adb logcat *:E                    # Errors only
adb logcat *:W                    # Warnings and above
adb logcat *:I                    # Info and above

# Filter by tag
adb logcat -s TagName             # Specific tag
adb logcat -s "Tag1" "Tag2"       # Multiple tags

# Clear logs
adb logcat -c

# Save logs to file
adb logcat > logcat_output.txt

# View logs with timestamps
adb logcat -v time

# View logs with thread IDs
adb logcat -v threadtime

Advanced Filtering

# Combine filters
adb logcat *:E | grep -i "password\|token\|key"

# Filter by app UID
adb logcat | grep $(adb shell dumpsys package com.example.app | grep userId | cut -d= -f2)

# Time-based filtering
adb logcat -t "$(date +%m-%d\ %H:%M:%S.000)"

# Continuous monitoring with highlighting
adb logcat -v color | grep --color=always -E "ERROR|password|token|key"

Finding Sensitive Data

# Search for common sensitive patterns
adb logcat | grep -iE "(password|token|api[_-]?key|secret|credential|auth)"

# Search for URLs
adb logcat | grep -E "https?://"

# Search for personal information
adb logcat | grep -iE "(email|phone|ssn|credit|card)"

# Search for JSON/XML responses
adb logcat | grep -E "\{.*\}|<.*>"

Logcat Automation Script

#!/usr/bin/env python3
import subprocess
import re
import time

SENSITIVE_PATTERNS = [
    r'password["\s:=]+([^"\s]+)',
    r'token["\s:=]+([^"\s]+)',
    r'api[_-]?key["\s:=]+([^"\s]+)',
    r'secret["\s:=]+([^"\s]+)',
]

def monitor_logcat(package_name):
    """Monitor logcat for sensitive information."""
    cmd = ['adb', 'logcat', '-v', 'time']
    process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

    print(f"[*] Monitoring logcat for {package_name}...")
    print("[*] Press Ctrl+C to stop\n")

    try:
        for line in process.stdout:
            if package_name.lower() in line.lower():
                # Check for sensitive data
                for pattern in SENSITIVE_PATTERNS:
                    match = re.search(pattern, line, re.IGNORECASE)
                    if match:
                        print(f"[!] POTENTIAL LEAK: {line.strip()}")
                        break
                else:
                    print(line.strip())
    except KeyboardInterrupt:
        print("\n[*] Stopping logcat monitoring...")
        process.terminate()

if __name__ == "__main__":
    import sys
    package = sys.argv[1] if len(sys.argv) > 1 else ""
    monitor_logcat(package)

Runtime Process Inspection

Overview

Understanding what processes are running, their permissions, memory usage, and behavior is crucial for dynamic analysis.

Process Inspection Commands

# List all processes
adb shell ps

# List processes for specific app
adb shell ps | grep com.example.app

# Get process details
adb shell ps -A | grep com.example.app

# View process tree
adb shell ps -e -o PID,PPID,NAME,CMD

# Get process memory info
adb shell dumpsys meminfo com.example.app

# Get process CPU usage
adb shell top -n 1 | grep com.example.app

Dumpsys Commands

# App information
adb shell dumpsys package com.example.app

# Activity information
adb shell dumpsys activity | grep -A 20 com.example.app

# Service information
adb shell dumpsys activity services com.example.app

# Broadcast receiver information
adb shell dumpsys activity broadcasts | grep com.example.app

# Memory information
adb shell dumpsys meminfo com.example.app

# Battery usage
adb shell dumpsys batterystats | grep com.example.app

# Network statistics
adb shell dumpsys netstats | grep com.example.app

Process Monitoring Script

#!/bin/bash
# Monitor app process behavior

PACKAGE="com.example.app"

while true; do
    echo "=== $(date) ==="
    adb shell ps | grep $PACKAGE
    adb shell dumpsys meminfo $PACKAGE | head -20
    echo ""
    sleep 5
done

Network Traffic Analysis

Overview

Monitoring network traffic during runtime reveals: - API endpoints called - Authentication mechanisms - Data transmitted - Response handling - Protocol usage

Basic Network Monitoring

# Monitor network connections
adb shell netstat -an | grep ESTABLISHED

# Monitor with tcpdump (requires root)
adb shell "tcpdump -i any -p -s 0 -w /sdcard/capture.pcap" &
adb pull /sdcard/capture.pcap

# View network statistics
adb shell dumpsys netstats | grep -A 10 com.example.app

Using Proxy Interception

See Network Testing for comprehensive network traffic interception and analysis techniques.


File System Monitoring

Overview

Monitoring file system changes reveals: - Files created/modified - Data storage locations - Temporary files - Cache contents

File System Monitoring

# Monitor file changes (requires root)
adb shell "watch -n 1 'find /data/data/com.example.app -type f -newer /tmp/marker'"

# List app files
adb shell run-as com.example.app ls -la

# Monitor specific directory
adb shell "watch -n 1 'ls -la /data/data/com.example.app/files'"

# Use strace for file operations (requires root)
adb shell "strace -e trace=open,openat,read,write -p $(pidof com.example.app)"

Storage Analysis

# View SharedPreferences
adb shell run-as com.example.app cat /data/data/com.example.app/shared_prefs/*.xml

# View databases
adb shell run-as com.example.app sqlite3 /data/data/com.example.app/databases/*.db ".dump"

# List all app files
adb shell run-as com.example.app find /data/data/com.example.app -type f

See Storage Testing for comprehensive storage security testing.


Memory Analysis

Overview

Memory analysis can reveal: - Sensitive data in memory - Encryption keys - Passwords/tokens - Application state

Basic Memory Dumping

# Dump process memory (requires root)
adb shell "cat /proc/$(pidof com.example.app)/maps"

# Use gdb for memory inspection (requires root and debug symbols)
adb shell gdb -p $(pidof com.example.app)

# Use Frida for memory analysis
frida -U -f com.example.app -l memory_dump.js

Frida Memory Dump Script

// memory_dump.js
Java.perform(function() {
    console.log("[*] Dumping memory...");

    // Hook toString methods to capture data
    var String = Java.use("java.lang.String");
    String.toString.implementation = function() {
        var result = this.toString();
        if (result.length > 10 && /[a-zA-Z0-9]{20,}/.test(result)) {
            console.log("[*] Potential sensitive data: " + result);
        }
        return result;
    };
});

UI Automation

Overview

Automating UI interactions allows comprehensive testing of app functionality without manual effort.

Basic UI Automation with ADB

# Tap at coordinates
adb shell input tap 500 1000

# Swipe
adb shell input swipe 300 500 300 100 200

# Text input
adb shell input text "test@example.com"

# Key events
adb shell input keyevent KEYCODE_BACK
adb shell input keyevent KEYCODE_HOME

Using UI Automator

# Get UI hierarchy
adb shell uiautomator dump /sdcard/ui.xml
adb pull /sdcard/ui.xml

# Interact with elements
adb shell uiautomator runtest UIAutomatorStub.jar -c com.example.TestClass

Using Appium

from appium import webdriver

desired_caps = {
    'platformName': 'Android',
    'deviceName': 'emulator-5554',
    'appPackage': 'com.example.app',
    'appActivity': '.MainActivity'
}

driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
# Perform UI interactions
element = driver.find_element_by_id("com.example.app:id/button")
element.click()

Crash Analysis

Overview

Analyzing crashes reveals: - Error handling weaknesses - Input validation issues - Memory corruption - Security vulnerabilities

Crash Log Collection

# View crash logs
adb logcat *:E | grep -i "crash\|exception\|error"

# Get ANR (Application Not Responding) reports
adb shell "ls -la /data/anr/"
adb pull /data/anr/*.txt

# Get tombstone files (native crashes)
adb shell "ls -la /data/tombstones/"
adb pull /data/tombstones/tombstone_*

Analyzing Crash Logs

# Filter for specific app crashes
adb logcat -d | grep -A 50 "FATAL EXCEPTION"

# Search for common crash patterns
adb logcat -d | grep -E "NullPointerException|IndexOutOfBoundsException|ClassCastException"

Behavior Analysis

Overview

Understanding app behavior helps identify: - Unexpected functionality - Hidden features - Security bypasses - Component interactions

Behavior Monitoring Checklist

  • App launch and initialization
  • Permission requests and usage
  • Network communication patterns
  • File system operations
  • Database operations
  • Inter-component communication
  • Background service behavior
  • Broadcast receiver triggers
  • Content provider access

Monitoring Workflow

# Comprehensive monitoring script
#!/bin/bash
PACKAGE="com.example.app"

echo "[*] Starting comprehensive monitoring for $PACKAGE"

# Start logcat monitoring
adb logcat -c
adb logcat | grep $PACKAGE > logcat_$PACKAGE.log &

# Monitor network
adb shell netstat -an | grep ESTABLISHED > network_$PACKAGE.log &

# Monitor processes
while true; do
    adb shell ps | grep $PACKAGE >> processes_$PACKAGE.log
    sleep 5
done &

Dynamic Analysis Checklist

  • App installed and launched successfully
  • Logcat monitored for sensitive data leaks
  • Network traffic intercepted and analyzed
  • File system changes monitored
  • Memory analyzed for sensitive data
  • All app features tested
  • Crash logs reviewed
  • Behavior documented
  • Findings correlated with static analysis