Android System Securing, Hardening, & Privacy

How to Customize AVB2: Signing Your Own Android Bootloader and System Images for Custom ROMs

Google AdSense Native Placement - Horizontal Top-Post banner

Introduction to Android Verified Boot 2.0 (AVB2)

What is AVB2?

Android Verified Boot 2.0 (AVB2) is a security mechanism designed to ensure the integrity of the software running on an Android device from the moment it boots up. It establishes a chain of trust starting from a hardware root of trust, typically fused into the device’s System-on-Chip (SoC), and extends this trust through the bootloader, kernel, and system partitions. Each stage verifies the cryptographic signature of the next stage before handing over control. If a signature mismatch or tampering is detected, AVB2 can prevent the device from booting or boot into a limited recovery mode, protecting against malicious modifications.

Why Customize AVB2?

For most users, AVB2 works behind the scenes, ensuring their device’s security. However, for advanced users, custom ROM developers, or enterprise environments, customizing AVB2 becomes essential. The primary reasons include:

  • Custom ROM Development: When creating or installing a custom ROM, the default Android images are replaced. These new images must be signed with a key known to the device’s bootloader to pass AVB2 verification, especially if the device is to be re-locked for security.
  • Enhanced Security: By generating your own private keys and signing your custom builds, you establish a unique chain of trust. This prevents anyone without your private keys from injecting unauthorized software onto your device, even if they gain physical access.
  • Maintaining Device Integrity: For specific use cases where the device’s software stack must remain immutable and verifiable (e.g., kiosks, secure enterprise devices), custom AVB2 keys ensure that only your authorized software runs.

Prerequisites and Setup

Development Environment Setup

To embark on AVB2 customization, you’ll need a robust development environment. This primarily involves setting up an AOSP (Android Open Source Project) build environment.

# Install necessary packages (Ubuntu/Debian example)sudo apt-get install git-core gnupg flex bison build-essential zip curl zlib1g-dev gcc-multilib g++-multilib libc6-dev-i386 libncurses5 lib32ncurses5-dev x11proto-core-dev libx11-dev lib32z1-dev libgl1-mesa-dev libxml2-utils xsltproc schedtool bc rsync# Initialize and sync AOSP repositorymkdir aospcd aosp# Replace 'master' with a specific branch/tag like 'android-13.0.0_r4' for stabilityrepo init -u https://android.googlesource.com/platform/manifest -b masterrepo sync -j$(nproc)

Ensure you have sufficient disk space (300GB+) and RAM (16GB+) for a full AOSP sync and build.

Understanding Key Concepts

Before proceeding, grasp these fundamental concepts:

  • AVB Key Hierarchy: AVB uses an RSA key pair (private and public). The private key signs the images, while the public key embedded in the device (or within other signed images) verifies them.
  • Rollback Protection: AVB incorporates rollback indexes to prevent an attacker from flashing an older, potentially vulnerable, signed image. When a device updates, its rollback index increments. An older image with a lower index will be rejected.
  • Device State: Android devices have boot states:
    • LOCKED: The device enforces AVB. Only officially signed images (or your custom signed images if keys are provisioned) will boot. This is the most secure state.
    • UNLOCKED: AVB is disabled or enforcement is relaxed. Custom images without proper signatures can boot, but security is compromised. Flashing an UNLOCKED device typically erases user data.
    • VERIFIED: The device is locked, and all loaded images are verified successfully.
    • ORANGE: The device is unlocked, signifying reduced security.
    • RED: Verification failed, and the device is in a potentially compromised state, often leading to a boot loop or recovery mode.

Generating Your Custom AVB2 Keys

The first crucial step is generating your unique cryptographic keys. These keys will be used to sign your custom bootloader and system images.

# 1. Generate a 4096-bit RSA private key (PEM format)openssl genrsa -out rsa4096_priv.pem 4096# 2. Convert to PKCS#8 format (required by AOSP build system)openssl pkcs8 -in rsa4096_priv.pem -topk8 -nocrypt -out rsa4096_pk8.pem# 3. Extract the public key for AVB footer generationavbtool extract_public_key --key rsa4096_priv.pem --output rsa4096_pub.bin# 4. Generate the public key in .pem format (useful for inspection)openssl rsa -in rsa4096_priv.pem -pubout -out rsa4096_pub.pem

Store `rsa4096_pk8.pem` and `rsa4096_pub.bin` securely. `rsa4096_pk8.pem` is your private signing key, and `rsa4096_pub.bin` is the public key blob embedded in images and potentially the device.

Integrating Custom Keys into AOSP Build System

Now, we’ll instruct the AOSP build system to use your newly generated keys for signing.

Modifying Device Configuration

Navigate to your device’s AOSP configuration files, typically located under `device///`. You’ll likely need to modify `device.mk` or a `BoardConfig.mk` file. Create a new directory for your custom keys, e.g., `device///security/` and place `rsa4096_pk8.pem` and `rsa4096_pub.bin` there.

Add or modify the following lines in your device’s `.mk` file:

# Enable AVB2BOARD_AVB_ENABLE := true# Specify the signing algorithmBOARD_AVB_ALGORITHM := SHA256_RSA4096# Path to your private PKCS#8 keyBOARD_AVB_KEY_PATH := device/<manufacturer>/<device-codename>/security/rsa4096_pk8.pem# Path to your public key for footer generation (usually the .bin file)BOARD_AVB_ROLLBACK_INDEX_LOCATION := device/<manufacturer>/<device-codename>/security/rsa4096_pub.bin# Set initial rollback index (important for preventing downgrade attacks)BOARD_AVB_ROLLBACK_INDEX := 0

The `BOARD_AVB_ROLLBACK_INDEX_LOCATION` specifies the public key used to verify the images. This public key is embedded in the `AVB_FOOTER` of each image.

Specifying Partition Signing Keys

If you want to use different keys for different partitions (e.g., one key for boot, another for system), you can define them explicitly. However, for most custom ROM scenarios, using a single key for all relevant partitions is sufficient and simpler.

# Example for specifying per-partition keys (optional)BOARD_AVB_BOOT_KEY_PATH := device/<manufacturer>/<device-codename>/security/rsa4096_pk8.pemBOARD_AVB_SYSTEM_KEY_PATH := device/<manufacturer>/<device-codename>/security/rsa4096_pk8.pemBOARD_AVB_VENDOR_KEY_PATH := device/<manufacturer>/<device-codename>/security/rsa4096_pk8.pem# If not specified, BOARD_AVB_KEY_PATH will be used for all.

Building and Signing Custom Images

With the keys generated and build configuration updated, you can now build your custom Android images.

Full AOSP Build with Custom Keys

Execute the standard AOSP build commands. The build system will automatically use your specified keys to sign the images.

# Set up build environmentsource build/envsetup.sh# Select your target device and build type (e.g., aosp_arm64-userdebug)lunch <target_product>-<build_variant># Start the full build process (this will take a considerable amount of time)make -j$(nproc)

After a successful build, your signed images (`boot.img`, `system.img`, `vendor.img`, etc.) will be located in the `out/target/product//` directory.

Manually Signing Images (Advanced)

In some advanced scenarios, you might need to manually sign an image after it’s been built without the proper AVB configuration, or sign a third-party image. The `avbtool` is your utility for this.

# Example: Manually add an AVB footer to an existing boot.img (replace paths)avbtool add_hashtree_footer 	--image <path_to_unsigned_boot.img> 	--partition_name boot 	--partition_size $(stat -c %s <path_to_unsigned_boot.img>) 	--key <path_to_your_rsa4096_pk8.pem> 	--algorithm SHA256_RSA4096 	--rollback_index 0 	--output <path_to_signed_boot.img>

This command calculates a hash tree for the `boot` partition and signs its root hash, embedding the signature and your public key into a footer within the `boot.img` file.

Flashing and Verifying Your Custom Signed Images

Device State Considerations

Before flashing custom signed images and attempting to re-lock your device, ensure your device’s bootloader is UNLOCKED. Locking a device with custom keys provisioned will make it reject any images not signed with those exact keys. If you lose your keys, your device could be permanently unbootable in a locked state.

# Unlock the bootloader (this will wipe your device!)fastboot flashing unlock# If critical partitions are locked, you might also need:fastboot flashing unlock_critical

Warning: Once you flash your custom-signed images and re-lock your device using `fastboot flashing lock`, only images signed with your private key will boot. Losing your private key or flashing an incorrectly signed image will render your device unusable in a locked state, requiring significant effort (or impossibility depending on the device) to recover.

Flashing Process

With your device bootloader unlocked, you can flash your custom images:

fastboot flash boot out/target/product/<device-codename>/boot.imgfastboot flash system out/target/product/<device-codename>/system.imgfastboot flash vendor out/target/product/<device-codename>/vendor.img# Flash other necessary partitions (e.g., product, dtbo)fastboot reboot

Verification on Device

After rebooting, you can verify the AVB2 status on your device via ADB.

adb shell getprop ro.boot.verifiedbootstate

If AVB2 is working correctly with your custom images and the device is unlocked, this should return `orange` (indicating unlocked state with AVB potentially active but not fully enforced as a trust anchor). If you re-locked the device with your custom keys, it should report `green` or `verified`.

You can also use `avbctl` (Android Verified Boot Control Tool) to inspect the AVB state:

adb shell avbctl get_boot_stateadb shell avbctl get_current_slot

Conclusion and Best Practices

Customizing AVB2 provides powerful control over your Android device’s security, particularly for custom ROM development and specialized deployments. By generating and managing your own keys, you establish a unique trust anchor. Always handle your private keys with extreme care; a lost or compromised private key can lead to irreversible consequences for your device’s security and bootability.

Regularly back up your keys, consider hardware security modules (HSMs) for key storage in high-security environments, and meticulously follow the rollback index management to prevent downgrade attacks. This deep dive into AVB2 empowers you to build a truly secure and custom Android experience from the ground up.

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