Introduction: Securing Your Android with Partition Integrity Monitoring
In the evolving landscape of mobile security, ensuring the integrity of your Android device’s system partitions is paramount. Malicious actors, sophisticated malware, or even unintended system modifications can compromise your device by altering critical system files. While Android’s Verified Boot aims to prevent boot-time tampering, it often doesn’t protect against post-boot modifications or root-level malware that bypasses these checks. This tutorial provides a detailed, expert-level guide on how to build your own custom partition integrity scanner using shell scripting on a rooted Android device. This allows you to create a trustworthy baseline and regularly monitor your device for any unauthorized changes, adding a crucial layer to your Android system hardening and privacy strategy.
Note: This tutorial requires a rooted Android device. Proceed with caution and understand the implications of rooting your device.
Understanding Android Partitions and Their Importance
Android devices divide their storage into various partitions, each serving a specific purpose. For integrity monitoring, we primarily focus on:
- /system: Contains the core Android OS framework, libraries, and applications. This is a read-only partition under normal operation and is a prime target for attackers.
- /vendor: Houses device-specific hardware abstraction layers (HALs) and vendor-specific binaries. Like /system, it’s typically read-only.
- /product: (On some devices) Contains OEM-specific apps and resources.
- /boot: Contains the kernel and ramdisk. Its integrity is typically covered by Verified Boot, but post-boot modifications can still occur.
- /data: Stores user data, installed applications, and their private data. This partition is inherently dynamic and typically not suitable for file integrity checks of this nature, though specific sensitive files within it could be monitored.
Our custom scanner will focus on monitoring the `/system` and `/vendor` partitions, as these are the most critical for the operating system’s proper and secure functioning.
The Core Concept: Cryptographic Hashing
The foundation of integrity monitoring lies in cryptographic hashing. A hash function takes an input (e.g., a file) and produces a fixed-size string of bytes, known as a hash value or checksum. Even a minuscule change in the input file will result in a completely different hash value. By generating hashes of all files in a partition when it’s known to be in a ‘good’ state (the baseline) and then comparing these with hashes generated later, we can detect any unauthorized modifications.
We will use the SHA256 (Secure Hash Algorithm 256-bit) algorithm, which is widely available on Android systems and offers strong collision resistance.
Prerequisites
Before we begin, ensure you have the following:
- A rooted Android device.
- ADB (Android Debug Bridge) installed and configured on your computer (optional, but highly recommended for easier shell access).
- A terminal emulator app on your Android device (e.g., Termux) or direct ADB shell access.
- Sufficient storage space on your device (e.g., internal storage or external SD card) to store the hash baselines and logs.
- (Optional but recommended) BusyBox installed on your rooted device for additional command-line utilities.
Step-by-Step Tutorial: Building Your Scanner
Phase 1: Generating the Baseline Hashes (Initial Scan)
This is the most critical step. You must generate your baseline hashes when you are absolutely certain your system is clean and untampered. Ideally, this should be done immediately after a clean ROM flash or a verified OTA update.
- Access Your Device’s Shell:
adb shellOr open your terminal emulator app on the device.
- Gain Root Privileges:
suGrant root access when prompted by your Superuser management app.
- Mount Partitions Read-Only (Crucial):
Before generating baselines, it’s crucial to remount your system partitions as read-only. This prevents any background processes or potential malware from altering files while you’re creating the baseline, ensuring its integrity.
mount -o ro,remount /systemmount -o ro,remount /vendor# Optional, if /product exists and you want to monitor itmount -o ro,remount /product - Create a Directory for Baselines:
Choose a secure location. For this tutorial, we’ll use `/data/local/tmp`, but for production use, consider an encrypted external SD card or even an off-device storage (USB OTG, secure cloud) after generating.
mkdir -p /data/local/tmp/integrity_baselines - Generate SHA256 Hashes for System Files:
This command finds all regular files (`-type f`) within `/system` and pipes their paths to `xargs` to efficiently execute `sha256sum` on batches of files. This is more performant than `find -exec … {} ;`.
find /system -type f -print0 | xargs -0 sha256sum > /data/local/tmp/integrity_baselines/system_baseline.sha256 - Generate SHA256 Hashes for Vendor Files:
find /vendor -type f -print0 | xargs -0 sha256sum > /data/local/tmp/integrity_baselines/vendor_baseline.sha256Repeat for any other partitions you wish to monitor (e.g., `/product`).
- Verify Baseline Files:
Check if the baseline files were created and contain data:
ls -lh /data/local/tmp/integrity_baselinescat /data/local/tmp/integrity_baselines/system_baseline.sha256 | head - Store Baselines Securely (Off-Device):
This is paramount. Once generated, copy these baseline files to a secure, offline location (e.g., a USB drive, an encrypted cloud storage, or another computer) that is not accessible from your Android device under normal circumstances. This prevents an attacker who gains control of your device from also tampering with your baseline.
# From your computer, connected via ADBpull /data/local/tmp/integrity_baselines/system_baseline.sha256 ~/android_baselines/pull /data/local/tmp/integrity_baselines/vendor_baseline.sha256 ~/android_baselines/After pulling, you can delete them from the device’s temporary location (`rm -rf /data/local/tmp/integrity_baselines/*`) and only copy them back when performing a scan.
- Remount Partitions Read-Write (if needed for normal operation):
mount -o rw,remount /systemmount -o rw,remount /vendor
Phase 2: Creating the Integrity Verification Script
Now, let’s create a shell script that automates the process of comparing current system state with your securely stored baseline.
- Create the Script File:
Using ADB or your terminal emulator, create a new file, for example, `/data/local/tmp/integrity_scanner.sh`.
touch /data/local/tmp/integrity_scanner.sh - Edit the Script Content:
Paste the following script into the file. You can use a text editor in your terminal emulator (like `vi` or `nano` if installed via BusyBox/Termux) or push it via ADB.
#!/system/bin/sh# Custom Android Partition Integrity CheckerCONFIG_DIR="/data/local/tmp/integrity_scanner_config"CURRENT_HASHES_DIR="/data/local/tmp/integrity_scanner_current_hashes"LOG_FILE="/data/local/tmp/integrity_check_log.txt"# IMPORTANT: Place your baseline files (e.g., system_baseline.sha256) in this directory# BEFORE running the scanner. You should push them from your secure off-device storage.BASELINE_DIR="${CONFIG_DIR}/baselines"PARTITIONS="/system /vendor" # Add /product or other partitions if you generated their baselines# --- Functions ---log_message() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"}# --- Main Script ---log_message "Starting Android Partition Integrity Check."# Ensure directories existmkdir -p "$CONFIG_DIR"mkdir -p "$BASELINE_DIR"mkdir -p "$CURRENT_HASHES_DIR"# Mount partitions read-onlylog_message "Remounting partitions as read-only for reliable scanning."mount -o ro,remount /systemmount -o ro,remount /vendor# Check if baselines existfor part_path in $PARTITIONS; do part_name=$(basename "$part_path") if [ ! -f "${BASELINE_DIR}/${part_name}_baseline.sha256" ]; then log_message "ERROR: Baseline for ${part_name} not found at ${BASELINE_DIR}/${part_name}_baseline.sha256." log_message "Please ensure baselines are placed in ${BASELINE_DIR} and retry." exit 1 fidone# Perform integrity checkfor part_path in $PARTITIONS; do part_name=$(basename "$part_path") log_message "Scanning partition: ${part_path}" # Generate current hashes find "$part_path" -type f -print0 | xargs -0 sha256sum > "${CURRENT_HASHES_DIR}/${part_name}_current.sha256" # Compare with baseline using diff # diff will exit with 0 if no differences, 1 if differences, 2 if error diff_output=$(diff -u "${BASELINE_DIR}/${part_name}_baseline.sha256" "${CURRENT_HASHES_DIR}/${part_name}_current.sha256") if [ $? -eq 0 ]; then log_message " ${part_name}: NO INTEGRITY ISSUES DETECTED." else log_message " ${part_name}: !!! INTEGRITY ALERT !!! Differences found:" log_message "$diff_output" # Log the actual diff output # In a real-world scenario, you might send an email, push notification, etc. fidone# Remount partitions read-write (if desired for normal operation)log_message "Remounting partitions as read-write."mount -o rw,remount /systemmount -o rw,remount /vendorlog_message "Integrity check completed." - Make the Script Executable:
chmod +x /data/local/tmp/integrity_scanner.sh - Prepare for Running the Script:
Before running, you need to copy your securely stored baseline files back to the device into the `BASELINE_DIR` specified in the script (`/data/local/tmp/integrity_scanner_config/baselines`).
# From your computer, connected via ADB (after copying them from your secure storage)adb push ~/android_baselines/system_baseline.sha256 /data/local/tmp/integrity_scanner_config/baselines/adb push ~/android_baselines/vendor_baseline.sha256 /data/local/tmp/integrity_scanner_config/baselines/# Verify they are in placeadb shell ls -l /data/local/tmp/integrity_scanner_config/baselines/ - Run the Script:
su -c /data/local/tmp/integrity_scanner.shThe output will be printed to the console and also logged to `/data/local/tmp/integrity_check_log.txt`.
- Review the Log:
cat /data/local/tmp/integrity_check_log.txt
Phase 3: Automation and Advanced Considerations
Automating the Scan
Running the script manually is good for occasional checks, but for continuous monitoring, automation is key.
- Tasker: If you use Tasker, you can create a profile that runs the script periodically (e.g., daily, weekly). Use the
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 →