diff --git a/.gitattributes b/.gitattributes index df74eca36..d5189ff30 100644 --- a/.gitattributes +++ b/.gitattributes @@ -12,7 +12,6 @@ # Denote all files that are truly binary and should not be modified. /tools/keys/** binary -/tools/keys/futility binary *.jar binary *.exe binary *.apk binary diff --git a/app/build-logic/src/main/java/Setup.kt b/app/build-logic/src/main/java/Setup.kt index 0eb860a6c..e9f5de984 100644 --- a/app/build-logic/src/main/java/Setup.kt +++ b/app/build-logic/src/main/java/Setup.kt @@ -178,12 +178,6 @@ fun Project.setupCoreLib() { include("util_functions.sh", "boot_patch.sh", "addon.d.sh", "app_functions.sh", "uninstaller.sh", "module_installer.sh") } - into("chromeos") { - from(rootFile("tools/futility")) - from(rootFile("tools/keys")) { - include("kernel_data_key.vbprivk", "kernel.keyblock") - } - } from(stubTask) { include { it.name.endsWith(".apk") } rename { "stub.apk" } diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/MagiskInstaller.kt b/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/MagiskInstaller.kt index 0096781c6..50d30f14c 100644 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/MagiskInstaller.kt +++ b/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/MagiskInstaller.kt @@ -169,13 +169,6 @@ abstract class MagiskInstallImpl protected constructor( val dest = File(installDir, script) context.assets.open(script).writeTo(dest) } - // Extract chromeos tools - File(installDir, "chromeos").mkdir() - for (file in listOf("futility", "kernel_data_key.vbprivk", "kernel.keyblock")) { - val name = "chromeos/$file" - val dest = File(installDir, name) - context.assets.open(name).writeTo(dest) - } } catch (e: Exception) { console.add("! Unable to extract files") Timber.e(e) diff --git a/docs/tools.md b/docs/tools.md index c77dac89d..15913301d 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -60,13 +60,18 @@ Supported actions: Return value: 0:valid 1:error - sign [name] [x509.pem pk8] + sign-avb1 [name] [x509.pem pk8] Sign with AVB 1.0 signature. Optionally provide the name of the image (default: '/boot'). Optionally provide the certificate/private key pair for signing. If the certificate/private key pair is not provided, the AOSP verity key bundled in the executable will be used. + sign-chromeos [outbootimg] + Sign with ChromeOS verified boot kernel signature, using + the developer keys bundled in the executable. + Output to [outbootimg], or overwrite if not specified. + extract [partition] [outfile] Extract [partition] from to [outfile]. If [outfile] is not specified, then output to '[partition].img'. diff --git a/native/src/boot/cli.rs b/native/src/boot/cli.rs index bff9204f0..1b318131a 100644 --- a/native/src/boot/cli.rs +++ b/native/src/boot/cli.rs @@ -2,6 +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::patch::hexpatch; use crate::payload::extract_boot_from_payload; use crate::sign::{sha1_hash, sign_boot_image}; @@ -28,7 +29,8 @@ enum Action { Unpack(Unpack), Repack(Repack), Verify(Verify), - Sign(Sign), + SignAvb1(SignAvb1), + SignChromeOs(SignChromeOs), Extract(Extract), HexPatch(HexPatch), Cpio(Cpio), @@ -72,8 +74,8 @@ struct Verify { } #[derive(FromArgs)] -#[argh(subcommand, name = "sign")] -struct Sign { +#[argh(subcommand, name = "sign-avb1")] +struct SignAvb1 { #[argh(positional)] img: Utf8CString, #[argh(positional)] @@ -84,6 +86,15 @@ struct Sign { key: Option, } +#[derive(FromArgs)] +#[argh(subcommand, name = "sign-chromeos")] +struct SignChromeOs { + #[argh(positional)] + img: Utf8CString, + #[argh(positional)] + out: Option, +} + #[derive(FromArgs)] #[argh(subcommand, name = "extract")] struct Extract { @@ -228,13 +239,18 @@ Supported actions: Return value: 0:valid 1:error - sign [name] [x509.pem pk8] + sign-avb1 [name] [x509.pem pk8] Sign with AVB 1.0 signature. Optionally provide the name of the image (default: '/boot'). Optionally provide the certificate/private key pair for signing. If the certificate/private key pair is not provided, the AOSP verity key bundled in the executable will be used. + sign-chromeos [outbootimg] + Sign with ChromeOS verified boot kernel signature, using + the developer keys bundled in the executable. + Output to [outbootimg], or overwrite if not specified. + extract [partition] [outfile] Extract [partition] from to [outfile]. If [outfile] is not specified, then output to '[partition].img'. @@ -326,6 +342,15 @@ fn sign_cmd( Ok(()) } +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)?; + Ok(()) +} + fn boot_main(cmds: CmdArgs) -> LoggedResult { let mut cmds = cmds.0; if cmds.len() < 2 { @@ -375,7 +400,7 @@ fn boot_main(cmds: CmdArgs) -> LoggedResult { return log_err!(); } } - Action::Sign(Sign { + Action::SignAvb1(SignAvb1 { img, name, cert, @@ -383,6 +408,9 @@ fn boot_main(cmds: CmdArgs) -> LoggedResult { }) => { sign_cmd(&img, name.as_deref(), cert.as_deref(), key.as_deref())?; } + Action::SignChromeOs(SignChromeOs { img, out }) => { + sign_chromeos_cmd(&img, out.as_deref())?; + } Action::Extract(Extract { payload, partition, diff --git a/native/src/boot/futility.rs b/native/src/boot/futility.rs new file mode 100644 index 000000000..f34c31431 --- /dev/null +++ b/native/src/boot/futility.rs @@ -0,0 +1,176 @@ +// ChromeOS verified boot kernel signing, ported from vboot_reference futility. +// +// The output is byte-for-byte identical to: +// +// echo > empty +// futility vbutil_kernel --pack --keyblock kernel.keyblock \ +// --signprivate kernel_data_key.vbprivk --version 1 --vmlinuz \ +// --config empty --arch arm --bootloader empty --flags 0x1 +// +// Output layout: +// +// +--------------------------------+ +// | keyblock | \ +// +--------------------------------+ > vblock, padded to 64 KiB +// | kernel preamble + padding | / +// +--------------------------------+ +// | kernel image, aligned to 4K | \ +// | config (4K, empty) | | +// | params (4K, unused on ARM) | > kernel blob +// | bootloader stub (4K) | / +// +--------------------------------+ + +use crate::sign::sha256_hash; +use base::{LoggedResult, log_err}; +use bytemuck::{Pod, Zeroable, bytes_of}; +use rsa::RsaPrivateKey; +use rsa::pkcs1::DecodeRsaPrivateKey; +use rsa::pkcs1v15::{Signature, SigningKey}; +use rsa::signature::SignatureEncoding; +use rsa::signature::hazmat::PrehashSigner; +use sha2::Sha256; +use std::mem::{offset_of, size_of}; + +const KEYBLOCK: &[u8] = include_bytes!("../../../tools/keys/kernel.keyblock"); +// 8 bytes of algorithm ID, followed by a PKCS#1 DER encoded RSA private key +const PRIVKEY: &[u8] = include_bytes!("../../../tools/keys/kernel_data_key.vbprivk"); +const PRIVKEY_HDR_SIZE: usize = 8; +// vb2_crypto_algorithm: VB2_ALG_RSA2048_SHA256 +const ALG_RSA2048_SHA256: u8 = 4; +const RSA2048_SIG_SIZE: usize = 256; + +const CROS_ALIGN: usize = 4096; +const CROS_CONFIG_SIZE: usize = 4096; +const CROS_PARAMS_SIZE: usize = 4096; +// --kloadaddr (default: CROS_32BIT_ENTRY_ADDR) +const CROS_BODY_LOAD_ADDR: u64 = 0x100000; +// --pad (default) +const CROS_VBLOCK_SIZE: usize = 65536; +// --version 1 +const CROS_KERNEL_VERSION: u32 = 1; +// --flags 0x1 +const CROS_KERNEL_FLAGS: u32 = 1; +// --bootloader empty (created with `echo > empty`) +const CROS_BOOTLOADER: &[u8] = b"\n"; + +const PREAMBLE_HEADER_VERSION_MAJOR: u32 = 2; +const PREAMBLE_HEADER_VERSION_MINOR: u32 = 2; +const PREAMBLE_HDR_SIZE: usize = size_of::(); +// The preamble signature covers the header and the body signature +const PREAMBLE_SIGNED_SIZE: usize = PREAMBLE_HDR_SIZE + RSA2048_SIG_SIZE; +// Pad the preamble so that keyblock + preamble fills up the whole vblock +const PREAMBLE_SIZE: usize = CROS_VBLOCK_SIZE - KEYBLOCK.len(); + +const _: () = assert!(PRIVKEY[0] == ALG_RSA2048_SHA256); +const _: () = assert!(PREAMBLE_HDR_SIZE == 116); +const _: () = assert!(PREAMBLE_SIZE >= PREAMBLE_SIGNED_SIZE + RSA2048_SIG_SIZE); + +// struct vb2_signature +#[repr(C, packed)] +#[derive(Pod, Zeroable, Clone, Copy)] +struct VbSignature { + // Offset of signature data from the start of this struct + sig_offset: u32, + reserved0: u32, + sig_size: u32, + reserved1: u32, + // Size of the data block which was signed + data_size: u32, + reserved2: u32, +} + +// struct vb2_kernel_preamble +#[repr(C, packed)] +#[derive(Pod, Zeroable, Clone, Copy)] +struct VbKernelPreamble { + preamble_size: u32, + reserved0: u32, + preamble_signature: VbSignature, + header_version_major: u32, + header_version_minor: u32, + kernel_version: u32, + reserved1: u32, + body_load_address: u64, + bootloader_address: u64, + bootloader_size: u32, + reserved2: u32, + body_signature: VbSignature, + vmlinuz_header_address: u64, + vmlinuz_header_size: u32, + reserved3: u32, + flags: u32, +} + +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)?; + let sig = sig.to_vec(); + if sig.len() != RSA2048_SIG_SIZE { + return log_err!("Invalid signature size"); + } + Ok(sig) +} + +pub fn sign_chromeos_image(kernel: &[u8]) -> LoggedResult> { + if kernel.is_empty() { + return log_err!("Empty kernel image"); + } + + let key = RsaPrivateKey::from_pkcs1_der(&PRIVKEY[PRIVKEY_HDR_SIZE..])?; + 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 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); + + // 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, + preamble_signature: VbSignature { + sig_offset: (PREAMBLE_SIGNED_SIZE - offset_of!(VbKernelPreamble, preamble_signature)) + as u32, + sig_size: RSA2048_SIG_SIZE as u32, + data_size: PREAMBLE_SIGNED_SIZE as u32, + ..Zeroable::zeroed() + }, + header_version_major: PREAMBLE_HEADER_VERSION_MAJOR, + header_version_minor: PREAMBLE_HEADER_VERSION_MINOR, + 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, + body_signature: VbSignature { + sig_offset: (PREAMBLE_HDR_SIZE - offset_of!(VbKernelPreamble, body_signature)) as u32, + sig_size: RSA2048_SIG_SIZE as u32, + data_size: u32::try_from(blob_size)?, + ..Zeroable::zeroed() + }, + flags: CROS_KERNEL_FLAGS, + ..Zeroable::zeroed() + }; + 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])?; + preamble[PREAMBLE_SIGNED_SIZE..][..RSA2048_SIG_SIZE].copy_from_slice(&preamble_sig); + + Ok(out) +} diff --git a/native/src/boot/lib.rs b/native/src/boot/lib.rs index e696054a5..f30b69ff1 100644 --- a/native/src/boot/lib.rs +++ b/native/src/boot/lib.rs @@ -14,6 +14,7 @@ mod compress; mod cpio; mod dtb; mod format; +mod futility; mod patch; mod payload; // Suppress warnings in generated code diff --git a/scripts/boot_patch.sh b/scripts/boot_patch.sh index 672804685..be740eaf8 100644 --- a/scripts/boot_patch.sh +++ b/scripts/boot_patch.sh @@ -22,8 +22,6 @@ # magiskboot binary A tool to manipulate boot images. # init-ld binary The library that will be LD_PRELOAD of /init # stub.apk binary The stub Magisk app to embed into ramdisk. -# chromeos folder This folder includes the utility and keys to sign -# (optional) chromeos boot images. Only used for Pixel C. # ####################################################################################### @@ -258,7 +256,10 @@ ui_print "- Repacking boot image" ./magiskboot repack "$BOOTIMAGE" || abort "! Unable to repack boot image" # Sign chromeos boot -$CHROMEOS && sign_chromeos +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/flash_script.sh b/scripts/flash_script.sh index d5b29fd54..855cdffad 100644 --- a/scripts/flash_script.sh +++ b/scripts/flash_script.sh @@ -12,7 +12,6 @@ umask 022 OUTFD=$2 COMMONDIR=$INSTALLER/assets -CHROMEDIR=$INSTALLER/assets/chromeos if [ ! -f $COMMONDIR/util_functions.sh ]; then echo "! Unable to extract zip file!" diff --git a/scripts/uninstaller.sh b/scripts/uninstaller.sh index 5142ae4a7..0b0d50723 100644 --- a/scripts/uninstaller.sh +++ b/scripts/uninstaller.sh @@ -12,7 +12,6 @@ umask 022 OUTFD=$2 COMMONDIR=$INSTALLER/assets -CHROMEDIR=$INSTALLER/assets/chromeos if [ ! -f $COMMONDIR/util_functions.sh ]; then echo "! Unable to extract zip file!" @@ -54,7 +53,6 @@ BINDIR=$INSTALLER/lib/$ABI cd $BINDIR for file in lib*.so; do mv "$file" "${file:3:${#file}-6}"; done cd / -cp -af $CHROMEDIR/. $BINDIR/chromeos chmod -R 755 $BINDIR ############ @@ -130,7 +128,10 @@ case $((STATUS & 3)) in fi ./magiskboot repack $BOOTIMAGE # Sign chromeos boot - $CHROMEOS && sign_chromeos + 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 diff --git a/scripts/util_functions.sh b/scripts/util_functions.sh index dd91cd177..a9d7bfd1d 100644 --- a/scripts/util_functions.sh +++ b/scripts/util_functions.sh @@ -451,18 +451,6 @@ install_magisk() { run_migrations } -sign_chromeos() { - ui_print "- Signing ChromeOS boot image" - - echo > empty - ./chromeos/futility vbutil_kernel --pack new-boot.img.signed \ - --keyblock ./chromeos/kernel.keyblock --signprivate ./chromeos/kernel_data_key.vbprivk \ - --version 1 --vmlinuz new-boot.img --config empty --arch arm --bootloader empty --flags 0x1 - - rm -f empty new-boot.img - mv new-boot.img.signed new-boot.img -} - remove_system_su() { [ -d /postinstall/tmp ] && POSTINST=/postinstall cd $POSTINST/system diff --git a/tools/futility b/tools/futility deleted file mode 100644 index 28304a1bc..000000000 Binary files a/tools/futility and /dev/null differ