Android Mobile Forensics, Recovery, & Debugging

Forensic Toolkit: Building Custom ADB Shell Scripts for Automated Data Collection

Google AdSense Native Placement - Horizontal Top-Post banner

Introduction to ADB for Forensic Data Collection

Android Debug Bridge (ADB) is an indispensable command-line tool that facilitates communication between a computer and an Android device. While primarily designed for developers to debug applications, ADB’s robust capabilities make it a powerful asset in the realm of mobile forensics. Forensic investigators can leverage ADB to access and extract critical data from Android devices, often without needing physical disassembly or complex hardware tools, especially in scenarios where the device is live or in a state allowing USB debugging.

The manual execution of numerous ADB commands can be time-consuming, prone to error, and inefficient, particularly when dealing with multiple devices or complex data collection requirements. This article serves as an expert-level guide to building custom ADB shell scripts, enabling automated and systematic data collection, thereby streamlining forensic investigations and ensuring comprehensive data acquisition.

Setting Up Your Forensic Workstation

Prerequisites

  • A computer running Windows, macOS, or Linux.
  • An Android device with USB debugging enabled.
  • A USB cable to connect the device to the computer.
  • Sufficient storage space on the workstation for collected data.

Installing ADB

ADB is part of the Android SDK Platform-Tools package. You can download this standalone package from the official Android Developers website. After downloading, extract the contents to a readily accessible directory (e.g., C:platform-tools on Windows, or ~/platform-tools on Linux/macOS). For convenience, add this directory to your system’s PATH environment variable.

# For Linux/macOS, add to .bashrc or .zshrc:export PATH="$PATH:/path/to/platform-tools"# Then reload:source ~/.bashrc

Enabling USB Debugging

This is crucial. The process typically involves:

  1. Navigate to Settings > About phone.
  2. Tap on Build number seven times to enable Developer options.
  3. Go back to Settings > System > Developer options (or similar, depending on Android version).
  4. Toggle on USB debugging.
  5. When connecting the device to the computer, authorize the connection by accepting the RSA key fingerprint prompt on the device screen.

Essential ADB Commands for Mobile Forensics

Before scripting, understanding fundamental ADB commands is paramount. These commands form the building blocks of your automated scripts.

Device Identification and Status

adb devices          # Lists connected devices and their serial numbersadb get-state        # Reports device status (offline, device, bootloader)

Data Extraction with adb pull

The adb pull command is your primary tool for retrieving files and directories from the device. Note that accessing certain sensitive areas like /data often requires root privileges or specific permissions.

adb pull /sdcard/DCIM/Camera .    # Pulls all photos from the camera directory to current folderadb pull /data/local/tmp/important_log.txt /home/forensics/logs/device_A/ # Pulls a specific fileadb pull /data/data/com.example.app/databases/app.db # Attempts to pull app database (often requires root)

System Information and Logs

adb shell getprop      # Dumps all system properties and build informationadb logcat -d          # Dumps the entire log buffer and exits (good for snapshots)adb logcat -v time -f /sdcard/logcat.txt # Dumps logs to a file on device, with timestampsadb shell dumpsys      # Dumps system service data, extremely verbose. Use with specific services.adb shell dumpsys battery # Dumps battery informationadb shell dumpsys package com.example.app # Dumps information about a specific package

Examining Installed Applications

adb shell pm list packages          # Lists all installed packagesadb shell pm list packages -f       # Lists packages with their associated apk file pathsadb shell pm path com.example.app   # Shows the path to the APK for a specific package

Building Custom ADB Shell Scripts for Automation

Why Automate?

Automation via scripting offers several benefits in forensics:

  • Efficiency: Execute multiple commands in seconds.
  • Consistency: Ensure the same data is collected every time, reducing human error.
  • Completeness: Systematically collect all desired data points without missing steps.
  • Reproducibility: Scripts can be re-run, ensuring forensic soundness.

Scripting Fundamentals

Custom ADB scripts are typically written in Bash (for Linux/macOS) or batch scripts (for Windows). We’ll focus on Bash here, which is highly portable across forensic workstations.

Key considerations:

  • Shebang: #!/bin/bash at the top.
  • Variables: Store device IDs, output directories, etc.
  • Error Handling: Check command return codes ($?) to ensure successful execution.
  • Output Redirection: Direct command output to files for analysis.
  • Timestamping: Crucial for maintaining a clear chain of custody and chronological order.

Example: A Basic Forensic Data Collection Script

This script demonstrates how to collect basic device information, installed packages, and logs.

#!/bin/bash# Script for Automated Android Forensic Data Collection# Usage: ./collect_forensics.sh <device_serial>if [ -z "$1" ]; then  echo "Usage: $0 <device_serial>"  adb devices  exit 1fiDEVICE_SERIAL="$1"OUTPUT_DIR="forensic_data_$(date +%Y%m%d_%H%M%S)_${DEVICE_SERIAL}"echo "[*] Starting data collection for device: ${DEVICE_SERIAL}"echo "[*] Output directory: ${OUTPUT_DIR}"mkdir -p "${OUTPUT_DIR}" || { echo "[!] Failed to create output directory. Exiting."; exit 1; }# 1. Collect Device Propertiesecho "[*] Collecting device properties..."adb -s "${DEVICE_SERIAL}" shell getprop > "${OUTPUT_DIR}/device_properties.txt" 2>&1 || echo "[!] Failed to collect device properties."# 2. Collect Installed Packagesecho "[*] Collecting installed packages..."adb -s "${DEVICE_SERIAL}" shell pm list packages -f > "${OUTPUT_DIR}/installed_packages.txt" 2>&1 || echo "[!] Failed to collect installed packages."# 3. Collect System Logscur_log_file="${OUTPUT_DIR}/logcat_$(date +%Y%m%d_%H%M%S).txt"echo "[*] Collecting logcat logs to ${cur_log_file}..."adb -s "${DEVICE_SERIAL}" logcat -d > "${cur_log_file}" 2>&1 || echo "[!] Failed to collect logcat logs."# 4. Pull Photos from DCIM (example, may need permissions/root for /data)echo "[*] Attempting to pull DCIM/Camera..."mkdir -p "${OUTPUT_DIR}/DCIM_Camera"adb -s "${DEVICE_SERIAL}" pull /sdcard/DCIM/Camera "${OUTPUT_DIR}/DCIM_Camera" 2>&1 || echo "[!] Failed to pull DCIM/Camera. Check permissions/path."# 5. Dump Running Servicesecho "[*] Dumping running services..."adb -s "${DEVICE_SERIAL}" shell dumpsys activity services > "${OUTPUT_DIR}/running_services.txt" 2>&1 || echo "[!] Failed to dump running services."echo "[*] Data collection complete for ${DEVICE_SERIAL}."

Understanding the Script Components

  • #!/bin/bash: Specifies the interpreter.
  • if [ -z "$1" ]; then ... fi: Checks if a device serial is provided as an argument.
  • DEVICE_SERIAL="$1": Assigns the first command-line argument to DEVICE_SERIAL.
  • OUTPUT_DIR="forensic_data_$(date +%Y%m%d_%H%M%S)_${DEVICE_SERIAL}": Creates a unique, timestamped output directory.
  • mkdir -p "${OUTPUT_DIR}": Creates the output directory. The -p flag ensures parent directories are created if they don’t exist.
  • adb -s "${DEVICE_SERIAL}" ...: Targets a specific device using its serial number, essential when multiple devices are connected.
  • > "file.txt" 2>&1: Redirects standard output to file.txt and standard error (2) to the same location as standard output (&1), capturing all command output and errors.
  • || echo "[!] Failed...": This is basic error handling. If the preceding command fails (returns a non-zero exit code), the message is printed.

Advanced Scripting Techniques and Considerations

Error Handling and Robustness

For production-level forensic scripts, enhance error handling. Instead of simple `|| echo`, you might want to log errors to a separate file, send notifications, or implement retry mechanisms. Using functions can modularize your script.

collect_data() {  local device="$1"  local output_dir="$2"  local command_desc="$3"  local adb_command="$4"  local output_file="$5"  echo "[*] ${command_desc}..."  adb -s "${device}" ${adb_command} > "${output_dir}/${output_file}" 2>&1  if [ $? -ne 0 ]; then    echo "[!] Failed to ${command_desc}. See errors in ${output_dir}/${output_file}"    return 1  fi  return 0}# Usage in script:collect_data "${DEVICE_SERIAL}" "${OUTPUT_DIR}" "Collecting device properties" "shell getprop" "device_properties.txt"

Targeted Data Extraction

Beyond general collection, scripts can be tailored to specific investigations. For example, to pull all SQLite databases from a particular application:

APP_PACKAGE="com.instagram.android"DB_DIR="${OUTPUT_DIR}/${APP_PACKAGE}_databases"mkdir -p "${DB_DIR}"echo "[*] Pulling databases for ${APP_PACKAGE}..."adb -s "${DEVICE_SERIAL}" shell 'find /data/data/'"${APP_PACKAGE}"'/ -name "*.db"' | while read db_path; do  if [ -n "$db_path" ]; then    db_filename=$(basename "$db_path")    echo "    [*] Pulling ${db_path} to ${DB_DIR}/${db_filename}"    adb -s "${DEVICE_SERIAL}" pull "$db_path" "${DB_DIR}/${db_filename}" 2>&1  fi;done || echo "[!] Failed to find/pull databases for ${APP_PACKAGE}. (Root often required)"

Note that accessing /data/data/APP_PACKAGE directly often requires a rooted device due to Android’s stringent security model (SELinux, user separation).

Handling Rooted vs. Non-Rooted Devices

It’s crucial to acknowledge the limitations of non-rooted devices. While ADB provides significant access, much of the sensitive application data (e.g., WhatsApp databases, private app files) resides in /data/data/, which is typically inaccessible without root. Your scripts should account for this, perhaps by attempting pulls and gracefully handling permission denied errors, or by having separate script paths for rooted devices.

Ethical and Legal Implications

When performing forensic data collection, always adhere to legal and ethical guidelines. Ensure you have proper authorization, maintain a clear chain of custody, and document every step. Any modification to the device, even minor, should be noted. ADB operations inherently interact with the device; minimize potential impact by scripting non-destructive commands primarily.

Conclusion

Building custom ADB shell scripts transforms a powerful debugging tool into an indispensable asset for automated mobile forensic data collection. By understanding fundamental ADB commands, embracing scripting best practices, and considering the legal and ethical landscape, investigators can achieve more efficient, consistent, and comprehensive data acquisition from Android devices. This expertise enhances forensic capabilities, allowing for deeper insights and more robust evidence preservation.

Android Mobile Specs & Compare Directory

Are you researching mobile hardware properties, processor SoCs, GPU chipsets, or RAM configurations? Access our complete specs catalog to compare up to 5 devices side-by-side!

Compare Devices Specs →
Google AdSense Inline Placement - Content Footer banner