From 43afdf16a856b4c86ffb6684c95b8d286615d7b7 Mon Sep 17 00:00:00 2001 From: topjohnwu Date: Tue, 6 Oct 2026 23:36:12 +0000 Subject: [PATCH] Automatically re-sign ChromeOS images on repack Instead of requiring scripts to detect ChromeOS images and sign them after repacking, preallocate the vblock and append the kernel blob trailer while repacking, then generate the vblock after all other patching is done. The image is padded to its original size after signing, same as other boot images. The signer now only takes the kernel payload and returns the vblock, hashing the kernel blob incrementally. The sign-chromeos action streams its output to disk instead of building the whole signed image in memory. Since ChromeOS images no longer need special handling, unpack no longer returns 2 for them, and all ChromeOS logic is removed from the scripts. Assisted-by: Claude Opus 5.5 --- docs/tools.md | 4 +- native/src/boot/bootimg.cpp | 39 ++++++++++++++---- native/src/boot/cli.rs | 27 +++++++++---- native/src/boot/futility.rs | 81 ++++++++++++++++++++++++------------- native/src/boot/lib.rs | 6 +++ scripts/boot_patch.sh | 11 ----- scripts/uninstaller.sh | 11 ----- 7 files changed, 113 insertions(+), 66 deletions(-) diff --git a/docs/tools.md b/docs/tools.md index 15913301d..0afa0e1e4 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -37,7 +37,7 @@ Supported actions: dumped to the file 'header', which can be used to modify header configurations during repacking. Return values: - 0:valid 1:error 2:chromeos 3:vendor_boot + 0:valid 1:error 3:vendor_boot repack [-n] [outbootimg] Repack boot image components using files from the current directory @@ -52,6 +52,8 @@ Supported actions: If '-n' is provided, all compression operations will be skipped. If env variable PATCHVBMETAFLAG is set to true, all disable flags in the boot image's vbmeta header will be set. + ChromeOS boot images will be automatically re-signed with the + developer keys bundled in the executable. verify [x509.pem] Check whether the boot image is signed with AVB 1.0 signature. diff --git a/native/src/boot/bootimg.cpp b/native/src/boot/bootimg.cpp index 0db714620..1a55ddf31 100644 --- a/native/src/boot/bootimg.cpp +++ b/native/src/boot/bootimg.cpp @@ -17,7 +17,6 @@ using namespace std; #define RETURN_OK 0 #define RETURN_ERROR 1 -#define RETURN_CHROMEOS 2 #define RETURN_VENDOR 3 static FileFormat check_fmt(const void *buf, size_t len) { @@ -169,9 +168,9 @@ map(image), k_fmt(FileFormat::UNKNOWN), r_fmt(FileFormat::UNKNOWN), e_fmt(FileFo FileFormat fmt = check_fmt(addr, map.size()); switch (fmt) { case FileFormat::CHROMEOS: - // chromeos require external signing flags[CHROMEOS_FLAG] = true; - addr += 65535; + fprintf(stderr, "CHROMEOS\n"); + addr += chromeos_vblock_size() - 1; break; case FileFormat::DHTB: flags[DHTB_FLAG] = true; @@ -576,7 +575,6 @@ int unpack(Utf8CStr image, bool skip_decomp, bool hdr) { // Dump bootconfig dump(boot.bootconfig, boot.hdr->bootconfig_size(), BOOTCONFIG_FILE); - if (boot.flags[CHROMEOS_FLAG]) return RETURN_CHROMEOS; if (boot.hdr->is_vendor()) return RETURN_VENDOR; return RETURN_OK; } @@ -620,7 +618,10 @@ void repack(Utf8CStr src_img, Utf8CStr out_img, bool skip_comp) { int fd = open(out_img.c_str(), O_RDWR | O_CREAT | O_TRUNC, 0644); // Copy non-standard headers - if (boot.flags[DHTB_FLAG]) { + if (boot.flags[CHROMEOS_FLAG]) { + // Preallocate the vblock, which is generated after the image is fully patched + write_zero(fd, chromeos_vblock_size()); + } else if (boot.flags[DHTB_FLAG]) { xwrite(fd, boot.map.data(), sizeof(dhtb_hdr)); } else if (boot.flags[BLOB_FLAG]) { xwrite(fd, boot.map.data(), sizeof(blob_hdr)); @@ -811,8 +812,16 @@ void repack(Utf8CStr src_img, Utf8CStr out_img, bool skip_comp) { xwrite(fd, boot.vbmeta, vbmeta_size); } - // Pad image to original size if not chromeos (as it requires post processing) - if (!boot.flags[CHROMEOS_FLAG]) { + uint32_t chromeos_kernel_sz = 0; + if (boot.flags[CHROMEOS_FLAG]) { + // The whole repacked image is the kernel payload of the ChromeOS kernel blob. + // Padding to the original size is done after signing. + chromeos_kernel_sz = lseek(fd, 0, SEEK_CUR) - off.header; + file_align_with(4096); + auto trailer = chromeos_blob_trailer(); + xwrite(fd, trailer.data(), trailer.size()); + } else { + // Pad image to original size off_t current = lseek(fd, 0, SEEK_CUR); if (current < boot.map.size()) { write_zero(fd, boot.map.size() - current); @@ -927,6 +936,22 @@ void repack(Utf8CStr src_img, Utf8CStr out_img, bool skip_comp) { } } + if (boot.flags[CHROMEOS_FLAG]) { + // ChromeOS signature covers the whole image, so it has to be the very last step + auto vblock = sign_chromeos(byte_view(out.data() + off.header, chromeos_kernel_sz)); + if (vblock.empty()) { + fprintf(stderr, "Failed to sign ChromeOS boot image\n"); + exit(1); + } + memcpy(out.data(), vblock.data(), vblock.size()); + // Pad image to original size after signing. Data beyond the signed + // kernel blob is not covered by the signature and is ignored. + off_t current = lseek(fd, 0, SEEK_END); + if (current < boot.map.size()) { + write_zero(fd, boot.map.size() - current); + } + } + close(fd); } diff --git a/native/src/boot/cli.rs b/native/src/boot/cli.rs index 1b318131a..2b613a12b 100644 --- a/native/src/boot/cli.rs +++ b/native/src/boot/cli.rs @@ -2,7 +2,7 @@ use crate::compress::{compress_cmd, decompress_cmd}; use crate::cpio::{cpio_commands, print_cpio_usage}; use crate::dtb::{DtbAction, dtb_commands, print_dtb_usage}; use crate::ffi::{BootImage, FileFormat, cleanup, repack, split_image_dtb, unpack}; -use crate::futility::sign_chromeos_image; +use crate::futility::{CROS_ALIGN, align_up, chromeos_blob_trailer, sign_chromeos}; use crate::patch::hexpatch; use crate::payload::extract_boot_from_payload; use crate::sign::{sha1_hash, sign_boot_image}; @@ -11,7 +11,7 @@ use base::libc::umask; use base::nix::fcntl::OFlag; use base::{ CmdArgs, EarlyExitExt, LoggedResult, MappedFile, PositionalArgParser, ResultExt, Utf8CStr, - Utf8CString, WriteExt, argh, cmdline_logging, cstr, log_err, + Utf8CStrBuf, Utf8CString, WriteExt, argh, cmdline_logging, cstr, log_err, }; use std::ffi::c_char; use std::io::{Seek, SeekFrom, Write}; @@ -216,7 +216,7 @@ Supported actions: dumped to the file 'header', which can be used to modify header configurations during repacking. Return values: - 0:valid 1:error 2:chromeos 3:vendor_boot + 0:valid 1:error 3:vendor_boot repack [-n] [outbootimg] Repack boot image components using files from the current directory @@ -231,6 +231,8 @@ Supported actions: If '-n' is provided, all compression operations will be skipped. If env variable PATCHVBMETAFLAG is set to true, all disable flags in the boot image's vbmeta header will be set. + ChromeOS boot images will be automatically re-signed with the + developer keys bundled in the executable. verify [x509.pem] Check whether the boot image is signed with AVB 1.0 signature. @@ -343,11 +345,22 @@ fn sign_cmd( } fn sign_chromeos_cmd(image: &Utf8CStr, out: Option<&Utf8CStr>) -> LoggedResult<()> { - // Drop the mapped input before writing, as output can be the same file - let signed = sign_chromeos_image(MappedFile::open(image)?.as_ref())?; let out = out.unwrap_or(image); - let mut fd = out.create(OFlag::O_WRONLY | OFlag::O_TRUNC | OFlag::O_CLOEXEC, 0o644)?; - fd.write_all(&signed)?; + let kernel = MappedFile::open(image)?; + let kernel = kernel.as_ref(); + let vblock = sign_chromeos(kernel)?; + + // Write to a temporary file first, as the output can be the same file as the input + let mut tmp = cstr::buf::default(); + tmp.push_str(out); + tmp.push_str(".tmp"); + let mut fd = tmp.create(OFlag::O_WRONLY | OFlag::O_TRUNC | OFlag::O_CLOEXEC, 0o644)?; + fd.write_all(&vblock)?; + fd.write_all(kernel)?; + fd.write_zeros(align_up(kernel.len(), CROS_ALIGN) - kernel.len())?; + fd.write_all(&chromeos_blob_trailer())?; + drop(fd); + tmp.rename_to(out)?; Ok(()) } diff --git a/native/src/boot/futility.rs b/native/src/boot/futility.rs index f34c31431..016944ce0 100644 --- a/native/src/boot/futility.rs +++ b/native/src/boot/futility.rs @@ -1,28 +1,30 @@ // ChromeOS verified boot kernel signing, ported from vboot_reference futility. // -// The output is byte-for-byte identical to: +// The signed image is byte-for-byte identical to: // // echo > empty // futility vbutil_kernel --pack --keyblock kernel.keyblock \ -// --signprivate kernel_data_key.vbprivk --version 1 --vmlinuz \ +// --signprivate kernel_data_key.vbprivk --version 1 --vmlinuz \ // --config empty --arch arm --bootloader empty --flags 0x1 // -// Output layout: +// Signed image layout: // // +--------------------------------+ // | keyblock | \ -// +--------------------------------+ > vblock, padded to 64 KiB +// +--------------------------------+ > vblock (64 KiB), generated by sign_chromeos() // | kernel preamble + padding | / // +--------------------------------+ -// | kernel image, aligned to 4K | \ +// | kernel payload | \ +// | zero padding to 4K alignment | | +// +--------------------------------+ > kernel blob // | config (4K, empty) | | -// | params (4K, unused on ARM) | > kernel blob +// | params (4K, unused on ARM) | | <- chromeos_blob_trailer() // | bootloader stub (4K) | / // +--------------------------------+ -use crate::sign::sha256_hash; use base::{LoggedResult, log_err}; use bytemuck::{Pod, Zeroable, bytes_of}; +use digest::Digest; use rsa::RsaPrivateKey; use rsa::pkcs1::DecodeRsaPrivateKey; use rsa::pkcs1v15::{Signature, SigningKey}; @@ -39,7 +41,7 @@ const PRIVKEY_HDR_SIZE: usize = 8; const ALG_RSA2048_SHA256: u8 = 4; const RSA2048_SIG_SIZE: usize = 256; -const CROS_ALIGN: usize = 4096; +pub const CROS_ALIGN: usize = 4096; const CROS_CONFIG_SIZE: usize = 4096; const CROS_PARAMS_SIZE: usize = 4096; // --kloadaddr (default: CROS_32BIT_ENTRY_ADDR) @@ -52,6 +54,9 @@ const CROS_KERNEL_VERSION: u32 = 1; const CROS_KERNEL_FLAGS: u32 = 1; // --bootloader empty (created with `echo > empty`) const CROS_BOOTLOADER: &[u8] = b"\n"; +const CROS_BOOTLOADER_SIZE: usize = align_up(CROS_BOOTLOADER.len(), CROS_ALIGN); +const CROS_BOOTLOADER_OFF: usize = CROS_CONFIG_SIZE + CROS_PARAMS_SIZE; +const CROS_BLOB_TRAILER_SIZE: usize = CROS_BOOTLOADER_OFF + CROS_BOOTLOADER_SIZE; const PREAMBLE_HEADER_VERSION_MAJOR: u32 = 2; const PREAMBLE_HEADER_VERSION_MINOR: u32 = 2; @@ -101,14 +106,12 @@ struct VbKernelPreamble { flags: u32, } -fn align_up(val: usize, alignment: usize) -> usize { +pub const fn align_up(val: usize, alignment: usize) -> usize { val.div_ceil(alignment) * alignment } -fn sign_rsa2048_sha256(key: &SigningKey, data: &[u8]) -> LoggedResult> { - let mut hash = [0u8; 32]; - sha256_hash(data, &mut hash); - let sig: Signature = key.sign_prehash(&hash)?; +fn sign_digest(key: &SigningKey, hash: &[u8]) -> LoggedResult> { + let sig: Signature = key.sign_prehash(hash)?; let sig = sig.to_vec(); if sig.len() != RSA2048_SIG_SIZE { return log_err!("Invalid signature size"); @@ -116,7 +119,18 @@ fn sign_rsa2048_sha256(key: &SigningKey, data: &[u8]) -> LoggedResult LoggedResult> { +// The data following the 4K aligned kernel payload in the kernel blob: +// config (empty), params (unused on ARM), and the bootloader stub. +// It is the same regardless of the kernel payload. +pub fn chromeos_blob_trailer() -> Vec { + let mut trailer = vec![0u8; CROS_BLOB_TRAILER_SIZE]; + trailer[CROS_BOOTLOADER_OFF..][..CROS_BOOTLOADER.len()].copy_from_slice(CROS_BOOTLOADER); + trailer +} + +// Generate the vblock (keyblock + kernel preamble) for the kernel blob consisting of +// the kernel payload, zero padding to 4K alignment, and chromeos_blob_trailer(). +pub fn sign_chromeos(kernel: &[u8]) -> LoggedResult> { if kernel.is_empty() { return log_err!("Empty kernel image"); } @@ -125,23 +139,23 @@ pub fn sign_chromeos_image(kernel: &[u8]) -> LoggedResult> { let key = SigningKey::::new(key); // Kernel blob layout - let config_off = align_up(kernel.len(), CROS_ALIGN); - let bootloader_off = config_off + CROS_CONFIG_SIZE + CROS_PARAMS_SIZE; - let bootloader_size = align_up(CROS_BOOTLOADER.len(), CROS_ALIGN); - let blob_size = align_up(bootloader_off + bootloader_size, CROS_ALIGN); + let kernel_end = align_up(kernel.len(), CROS_ALIGN); + let bootloader_off = kernel_end + CROS_BOOTLOADER_OFF; + let blob_size = kernel_end + CROS_BLOB_TRAILER_SIZE; - let mut out = vec![0u8; KEYBLOCK.len() + PREAMBLE_SIZE + blob_size]; - let (keyblock, rest) = out.split_at_mut(KEYBLOCK.len()); - let (preamble, blob) = rest.split_at_mut(PREAMBLE_SIZE); + // Sign the kernel blob without materializing it in memory + let mut sha = Sha256::new(); + sha.update(kernel); + sha.update(&[0u8; CROS_ALIGN][..kernel_end - kernel.len()]); + sha.update(chromeos_blob_trailer()); + let body_sig = sign_digest(&key, sha.finalize().as_slice())?; + + let mut vblock = vec![0u8; CROS_VBLOCK_SIZE]; + let (keyblock, preamble) = vblock.split_at_mut(KEYBLOCK.len()); // Keyblock keyblock.copy_from_slice(KEYBLOCK); - // Kernel blob - blob[..kernel.len()].copy_from_slice(kernel); - blob[bootloader_off..][..CROS_BOOTLOADER.len()].copy_from_slice(CROS_BOOTLOADER); - let body_sig = sign_rsa2048_sha256(&key, blob)?; - // Kernel preamble let hdr = VbKernelPreamble { preamble_size: PREAMBLE_SIZE as u32, @@ -157,7 +171,7 @@ pub fn sign_chromeos_image(kernel: &[u8]) -> LoggedResult> { kernel_version: CROS_KERNEL_VERSION, body_load_address: CROS_BODY_LOAD_ADDR, bootloader_address: CROS_BODY_LOAD_ADDR + bootloader_off as u64, - bootloader_size: bootloader_size as u32, + bootloader_size: CROS_BOOTLOADER_SIZE as u32, body_signature: VbSignature { sig_offset: (PREAMBLE_HDR_SIZE - offset_of!(VbKernelPreamble, body_signature)) as u32, sig_size: RSA2048_SIG_SIZE as u32, @@ -169,8 +183,17 @@ pub fn sign_chromeos_image(kernel: &[u8]) -> LoggedResult> { }; preamble[..PREAMBLE_HDR_SIZE].copy_from_slice(bytes_of(&hdr)); preamble[PREAMBLE_HDR_SIZE..PREAMBLE_SIGNED_SIZE].copy_from_slice(&body_sig); - let preamble_sig = sign_rsa2048_sha256(&key, &preamble[..PREAMBLE_SIGNED_SIZE])?; + let preamble_hash = Sha256::digest(&preamble[..PREAMBLE_SIGNED_SIZE]); + let preamble_sig = sign_digest(&key, preamble_hash.as_slice())?; preamble[PREAMBLE_SIGNED_SIZE..][..RSA2048_SIG_SIZE].copy_from_slice(&preamble_sig); - Ok(out) + Ok(vblock) +} + +pub fn chromeos_vblock_size() -> usize { + CROS_VBLOCK_SIZE +} + +pub fn sign_chromeos_for_cxx(kernel: &[u8]) -> Vec { + sign_chromeos(kernel).unwrap_or_default() } diff --git a/native/src/boot/lib.rs b/native/src/boot/lib.rs index f30b69ff1..1723f1f78 100644 --- a/native/src/boot/lib.rs +++ b/native/src/boot/lib.rs @@ -5,6 +5,7 @@ pub use base; use compress::{compress_bytes, decompress_bytes}; use dtb::find_dtb_offset_for_cxx; use format::{check_fmt, fmt_compressed, fmt_compressed_any, fmt2name}; +use futility::{chromeos_blob_trailer, chromeos_vblock_size, sign_chromeos_for_cxx}; use sign::{SHA, get_sha, sha256_hash, sign_payload_for_cxx}; use std::env; @@ -90,6 +91,11 @@ pub mod ffi { #[cxx_name = "sign_payload"] fn sign_payload_for_cxx(payload: &[u8]) -> Vec; + fn chromeos_vblock_size() -> usize; + fn chromeos_blob_trailer() -> Vec; + #[cxx_name = "sign_chromeos"] + fn sign_chromeos_for_cxx(kernel: &[u8]) -> Vec; + #[cxx_name = "find_dtb_offset"] fn find_dtb_offset_for_cxx(buf: &[u8]) -> i32; diff --git a/scripts/boot_patch.sh b/scripts/boot_patch.sh index be740eaf8..86da7fb41 100644 --- a/scripts/boot_patch.sh +++ b/scripts/boot_patch.sh @@ -81,7 +81,6 @@ chmod -R 755 . # Unpack ######### -CHROMEOS=false VENDORBOOT=false ui_print "- Unpacking boot image" @@ -89,10 +88,6 @@ ui_print "- Unpacking boot image" case $? in 0 ) ;; - 2 ) - ui_print "- ChromeOS boot image detected" - CHROMEOS=true - ;; 3 ) ui_print "- Vendor boot image detected" VENDORBOOT=true @@ -255,12 +250,6 @@ fi ui_print "- Repacking boot image" ./magiskboot repack "$BOOTIMAGE" || abort "! Unable to repack boot image" -# Sign chromeos boot -if $CHROMEOS; then - ui_print "- Signing ChromeOS boot image" - ./magiskboot sign-chromeos new-boot.img || abort "! Unable to sign ChromeOS boot image" -fi - # Restore the original boot partition path [ -e "$BOOTNAND" ] && BOOTIMAGE="$BOOTNAND" diff --git a/scripts/uninstaller.sh b/scripts/uninstaller.sh index 0b0d50723..3ae9dfb03 100644 --- a/scripts/uninstaller.sh +++ b/scripts/uninstaller.sh @@ -61,8 +61,6 @@ chmod -R 755 $BINDIR cd $BINDIR -CHROMEOS=false - ui_print "- Unpacking boot image" # Dump image for MTD/NAND character device boot partitions if [ -c $BOOTIMAGE ]; then @@ -76,10 +74,6 @@ case $? in 1 ) abort "! Unsupported/Unknown image format" ;; - 2 ) - ui_print "- ChromeOS boot image detected" - CHROMEOS=true - ;; esac # Restore the original boot partition path @@ -127,11 +121,6 @@ case $((STATUS & 3)) in rm -f ramdisk.cpio fi ./magiskboot repack $BOOTIMAGE - # Sign chromeos boot - if $CHROMEOS; then - ui_print "- Signing ChromeOS boot image" - ./magiskboot sign-chromeos new-boot.img || abort "! Unable to sign ChromeOS boot image" - fi ui_print "- Flashing restored boot image" flash_image new-boot.img $BOOTIMAGE || abort "! Insufficient partition size" fi