Android Mobile Forensics, Recovery, & Debugging

Beyond the Basics: Scripting ADB for Automated Android Forensic Image Collection

Google AdSense Native Placement - Horizontal Top-Post banner

Introduction to ADB in Android Forensics

The Android Debug Bridge (ADB) is an indispensable tool for developers and forensic investigators alike. While commonly used for debugging applications and pushing/pulling files, its true power in digital forensics lies in its ability to interact with the device’s shell, allowing for low-level data extraction. Manually issuing ADB commands for each partition can be tedious, error-prone, and time-consuming, especially when dealing with multiple devices or complex scenarios. This article delves into scripting ADB to automate the forensic imaging process, ensuring efficiency, consistency, and completeness in evidence collection.

Automating forensic image collection not only streamlines the workflow but also minimizes the risk of human error during critical data acquisition phases. By leveraging shell scripting, investigators can create robust, repeatable processes that reliably extract full partition images, crucial for in-depth analysis.

Prerequisites for Automated Imaging

Before embarking on automated forensic image collection, several critical prerequisites must be met to ensure a smooth and successful operation:

  • Rooted Android Device: Full partition imaging often requires root access to bypass Android’s security mechanisms and access raw block devices.
  • USB Debugging Enabled: This setting, usually found in Developer Options, is essential for ADB to communicate with the device.
  • ADB and Fastboot Tools: Ensure the latest version of ADB and Fastboot drivers are installed and correctly configured on your host system. Verify with adb devices.
  • Sufficient Host Storage: Raw forensic images can be very large. Ensure your host system has ample disk space, typically several times the size of the device’s internal storage.
  • su Binary and Permissions: The target Android device must have the su binary installed and configured to grant root privileges to ADB shell commands.

Understanding Android Storage Architecture

Android devices typically utilize a block-based storage architecture, where the internal storage is divided into various partitions. These partitions include boot, system, vendor, cache, data (or userdata), and others, each serving a specific purpose. Identifying these partitions correctly is the first step in targeted imaging.

You can list the available block devices and their mappings using ADB shell commands:

adb shell ls -l /dev/block/platform/*/by-name/

This command often provides symbolic links to the actual block devices, making them easier to identify. Alternatively, for a more raw view of partitions and their sizes, you can use:

adb shell cat /proc/partitions

Pay close attention to partitions like userdata, system, and potentially cache or boot, as these often contain valuable forensic artifacts.

Manual Forensic Imaging via ADB Shell

Before automating, it’s beneficial to understand the manual process. The core tool for imaging is the dd (data duplicator) command, which can read from an input file (if) and write to an output file (of). With root access, you can read directly from raw block devices.

Here’s how to manually image the userdata partition:

  1. Push dd (if not present or outdated): Some devices might not have a full-featured dd or may have an older version. It’s often safer to push a static ARM binary of dd to the device.
  2. Gain Root Shell:
    adb shell
    su
  3. Image the Partition to an accessible location on the device (e.g., /sdcard/):
    dd if=/dev/block/platform/ABCD.0/by-name/userdata of=/sdcard/userdata.img bs=4M

    The bs=4M (block size of 4 megabytes) optimizes transfer speed. Adjust as needed.

  4. Pull the Image to Host:
    exit // Exit su shell
    exit // Exit adb shell
    adb pull /sdcard/userdata.img /path/to/host/forensic_images/
  5. Clean up (optional): Remove the image from the device:
    adb shell su -c 'rm /sdcard/userdata.img'

This manual process, though effective, highlights the need for automation when dealing with multiple partitions or devices.

Scripting ADB for Automated Collection

Scripting provides the power to execute a sequence of commands, handle errors, and manage file transfers automatically. A robust script for forensic imaging should include:

  • Device Connectivity Check: Confirm the device is connected and authorized.
  • Partition Identification: Dynamically discover relevant partitions.
  • Iterative Imaging: Loop through identified partitions, using dd to create images.
  • Secure Transfer: Use adb pull to transfer images to the host.
  • Integrity Verification: Calculate hashes (MD5, SHA256) of pulled images.
  • Logging: Record all actions and errors for audit trails.

Example Script: Automated Partition Imaging (Bash)

This Bash script provides a framework for automating the collection of common forensic partitions (boot, system, userdata, cache). It assumes root access is pre-configured on the device.

#!/bin/bash

# --- Configuration ---
OUTPUT_DIR="forensic_images_$(date +%Y%m%d_%H%M%S)"
PARTITIONS=("boot" "system" "userdata" "cache") # Partitions to image
DEVICE_TEMP_PATH="/data/local/tmp" # Temporary path on device (requires write access)

# --- Functions ---
log_message() {
echo "[$(date +%Y-%m-%d %H:%M:%S)] $1"
}

check_adb_device() {
log_message "Checking for ADB devices..."
if ! adb get-state &> /dev/null; then
log_message "ERROR: No ADB device found or unauthorized. Ensure USB debugging is enabled and authorized."
exit 1
fi
log_message "ADB device connected and authorized." }

get_partition_path() {
local part_name=$1
# Attempt to find the partition path dynamically
adb shell "ls -l /dev/block/platform/*/by-name/$part_name 2>/dev/null || ls -l /dev/block/bootdevice/by-name/$part_name 2>/dev/null" | awk '{print $NF}'
}

# --- Main Script ---
mkdir -p "$OUTPUT_DIR" || { log_message "ERROR: Could not create output directory."; exit 1; }
log_message "Output directory: $OUTPUT_DIR"
check_adb_device

for partition in "${PARTITIONS[@]}"; do
log_message "--- Processing partition: $partition ---"
PART_PATH=$(get_partition_path "$partition")

if [ -z "$PART_PATH" ]; then
log_message "WARNING: Partition '$partition' not found on device. Skipping." continue
fi

DEVICE_IMG="$DEVICE_TEMP_PATH/${partition}.img" HOST_IMG="$OUTPUT_DIR/${partition}.img"
log_message "Imaging '$partition' from '$PART_PATH' to device path '$DEVICE_IMG'..." # Use su -c to ensure dd runs with root privileges
adb shell "su -c 'dd if=$PART_PATH of=$DEVICE_IMG bs=4M'"
if [ $? -ne 0 ]; then
log_message "ERROR: Failed to image '$partition' on device. Check root access and device permissions." continue
fi
log_message "Successfully imaged '$partition' on device."
log_message "Pulling '$partition.img' to host..." adb pull "$DEVICE_IMG" "$HOST_IMG"
if [ $? -ne 0 ]; then
log_message "ERROR: Failed to pull '$partition.img' to host." continue
fi
log_message "Successfully pulled '$partition.img' to host: $HOST_IMG"
log_message "Calculating MD5 hash for $HOST_IMG..." md5sum "$HOST_IMG" > "$HOST_IMG.md5"
log_message "MD5: $(cat "$HOST_IMG.md5")"
log_message "Removing temporary image from device: $DEVICE_IMG" adb shell "su -c 'rm $DEVICE_IMG'"
if [ $? -ne 0 ]; then
log_message "WARNING: Failed to remove temporary image from device. Manual cleanup may be required." fi
done

log_message "Automated forensic imaging complete!"

Explanation of Key Script Elements:

  • OUTPUT_DIR: Creates a unique directory for each collection based on the timestamp.
  • PARTITIONS: An array of partition names to target. Customize this based on your needs.
  • DEVICE_TEMP_PATH: A writable location on the device for temporary images. /data/local/tmp is usually a good choice but requires root for writing.
  • log_message(): A simple function for consistent logging of script progress.
  • check_adb_device(): Verifies ADB connectivity.
  • get_partition_path(): Crucially, this function attempts to locate the full path to the block device for a given partition name, making the script more robust across different Android devices.
  • adb shell "su -c 'command'": This construct is vital. It executes the `command` within the ADB shell, using `su -c` to ensure the command runs with root privileges.
  • dd if=$PART_PATH of=$DEVICE_IMG bs=4M: The core imaging command. `bs=4M` is generally a good balance for speed and reliability.
  • adb pull: Transfers the created image from the device to the host.
  • md5sum: Calculates the MD5 hash of the pulled image, providing a basic integrity check. It’s advisable to also calculate a hash of the image *on the device* before pulling for a more robust chain of custody.

Best Practices and Considerations

  • Integrity Verification

    Hashing is paramount for forensic integrity. Always calculate cryptographic hashes (MD5, SHA1, SHA256) of the acquired images. Ideally, calculate the hash on the device *before* pulling and then again on the host *after* pulling, ensuring no data corruption occurred during transfer. Tools like busybox md5sum or sha256sum can be pushed to the device if not available.

  • Storage Management

    Raw images consume significant disk space. Plan for this by having dedicated external drives with ample storage. Monitor disk space during the acquisition process.

  • Speed and Efficiency

    USB 3.0 or higher connections are recommended for faster data transfer. Ensure your host’s storage device (e.g., SSD) can handle high write speeds. The `bs` parameter in `dd` can be tuned for optimal performance on different devices.

  • Device State and Forensics Impact

    Minimize changes to the device. Ideally, the device should be in airplane mode, with Wi-Fi/Bluetooth off, and minimal running processes. Power consumption should be monitored, and the device kept charged. Be aware that installing su and enabling USB debugging can alter the device state; these steps should be documented carefully.

  • Error Handling and Logging

    Robust scripts include comprehensive error checking and logging. Our example includes basic checks, but real-world forensic scripts might log every command, its output, and any errors to a separate log file for later review.

  • Chain of Custody

    Every step of the acquisition process, from device handling to image hashing, must be meticulously documented to maintain a proper chain of custody. This includes time, date, personnel, tools used, and unique identifiers for the device and images.

Conclusion

Scripting ADB for automated Android forensic image collection transforms a labor-intensive and error-prone process into an efficient, repeatable, and robust operation. By understanding the underlying Android storage architecture, leveraging powerful shell commands like dd, and employing thoughtful scripting techniques, forensic investigators can significantly enhance their capabilities. While this article provides a foundational script, remember to adapt and extend it to suit specific forensic requirements, always prioritizing data integrity and maintaining a clear chain of custody.

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