//! `boot prepare`, `decode-im4p` and hashed manifests over a synthetic restore //! archive; every byte here is generated by the test. use std::{ io::Write, path::Path, process::{Command, Output}, }; const PAGE: usize = 0x4000; const BASE: u64 = 0xfffffe0007004000; const LC_SEGMENT_64: u32 = 0x19; const LC_UNIXTHREAD: u32 = 0x5; const LC_FILESET_ENTRY: u32 = 0x8000_0035; const MH_EXECUTE: u32 = 2; const MH_FILESET: u32 = 12; fn cli(root: &Path, args: &[&str]) -> Output { Command::new(env!("CARGO_BIN_EXE_stela-dev")) .current_dir(root) .args(args) .output() .unwrap() } fn words(values: &[u32]) -> Vec { values.iter().flat_map(|v| v.to_le_bytes()).collect() } /// A Mach-O with one page per named segment and an entry `entry_page` pages in. fn macho(file_type: u32, segments: &[&str], entry_page: usize, fileset: bool) -> Vec { let mut commands = vec![]; for (index, name) in segments.iter().enumerate() { let mut command = words(&[LC_SEGMENT_64, 72]); let mut segname = [0u8; 16]; segname[..name.len()].copy_from_slice(name.as_bytes()); command.extend(segname); let offset = (index * PAGE) as u64; for value in [BASE + offset, PAGE as u64, offset, PAGE as u64] { command.extend(value.to_le_bytes()); } command.extend(words(&[5, 5, 0, 0])); commands.push(command); } if fileset { let mut command = words(&[LC_FILESET_ENTRY, 56]); command.extend(BASE.to_le_bytes()); command.extend(0u64.to_le_bytes()); command.extend(words(&[32, 0])); command.extend(b"com.apple.kernel\0"); command.resize(56, 0); commands.push(command); } let mut thread = words(&[LC_UNIXTHREAD, 288, 6, 68]); thread.extend([0u8; 256]); thread.extend((BASE + (entry_page * PAGE) as u64).to_le_bytes()); thread.extend([0u8; 8]); commands.push(thread); let body: Vec = commands.concat(); let mut out = words(&[ 0xfeed_facf, 0x0100_000c, 0xc000_0002, file_type, commands.len() as u32, body.len() as u32, 0, 0, ]); out.extend(body); out.resize(segments.len() * PAGE, 0xa5); out } fn property(name: &str, value: &[u8], placeholder: bool) -> Vec { let mut out = vec![0u8; 32]; out[..name.len()].copy_from_slice(name.as_bytes()); out.extend((value.len() as u32 | if placeholder { 1 << 31 } else { 0 }).to_le_bytes()); out.extend(value); out.resize(out.len().next_multiple_of(4), 0); out } fn node(properties: &[Vec], children: &[Vec]) -> Vec { let mut out = words(&[properties.len() as u32, children.len() as u32]); properties.iter().for_each(|p| out.extend(p)); children.iter().for_each(|c| out.extend(c)); out } fn device_tree() -> Vec { let memory_map = node( &[ property("name", b"memory-map\0", false), property("MemoryMapReserved-0", &[0; 16], false), ], &[], ); let manifest_properties = node( &[ property("name", b"manifest-properties\0", false), property("UnusedIntegerProperty0", &[0; 8], false), property("UnusedIntegerProperty1", &[0; 8], false), property("UnusedIntegerProperty2", &[0; 8], false), property("UnusedBooleanProperty0", &[0; 4], false), property("UnusedBooleanProperty1", &[0; 4], false), ], &[], ); // The template's empty AMCC lock-register nodes, which iBoot fills. let named = |name: &str| { node( &[property("name", format!("{name}\0").as_bytes(), false)], &[], ) }; let amcc = node( &[property("name", b"amcc\0", false)], &["amcc-ctrr-a", "amcc-ctrr-b", "amcc-ctrr-c", "amcc-ctrr-d"].map(named), ); let lock_regs = node(&[property("name", b"lock-regs\0", false)], &[amcc]); let chosen = node( &[ property("name", b"chosen\0", false), property("random-seed", &[0; 0x100], false), property("cl4-entropy", &[0; 0xc0], false), property("serial-number", b"syscfg/SrNm/0x20,zeroes/0x20\0", true), property("boot-manifest-hash", &[0; 48], false), property("effective-production-status-ap", &[0; 4], false), property("effective-security-mode-ap", &[0; 4], false), property("sepfw-load-at-boot", &[1, 0, 0, 0], false), property("cs-system-policy", b"default\0", false), property("osenvironment", &[0; 32], false), ], &[memory_map, manifest_properties, lock_regs], ); let cpu0 = node( &[ // Authored single-P diagnostic topology with complete schema-4 identity. property("name", b"cpu0\0", false), property("cluster-type", b"P\0", false), property("reg", &0u32.to_le_bytes(), false), property("state", b"waiting\0", false), ], &[], ); let cpus = node(&[property("name", b"cpus\0", false)], &[cpu0]); let vram = node( &[ property("name", b"vram\0", false), property("reg", &[0; 16], false), ], &[], ); node( &[property("name", b"device-tree\0", false)], &[chosen, cpus, vram], ) } fn trust_cache() -> Vec { let mut out = words(&[2]); out.extend([0x11; 16]); out.extend(words(&[1])); out.extend([0xcd; 24]); out } fn der(tag: u8, value: &[u8]) -> Vec { let mut out = vec![tag]; if value.len() < 128 { out.push(value.len() as u8); } else { let length = (value.len() as u32).to_be_bytes(); let skip = length.iter().take_while(|&&b| b == 0).count(); out.push(0x80 | (4 - skip) as u8); out.extend(&length[skip..]); } out.extend(value); out } /// Minimal DER INTEGER content for a non-negative value. fn unsigned(value: u32) -> Vec { let bytes = value.to_be_bytes(); let skip = bytes.iter().take_while(|&&b| b == 0).count().min(3); let mut out = bytes[skip..].to_vec(); if out[0] & 0x80 != 0 { out.insert(0, 0); } out } /// A plaintext IM4P; stored LZFSE (`bvx-`) when `compressed`. fn im4p(kind: &str, payload: &[u8], compressed: bool) -> Vec { let mut fields = [ der(0x16, b"IM4P"), der(0x16, kind.as_bytes()), der(0x16, b"synthetic"), ] .concat(); if compressed { let mut stream = b"bvx-".to_vec(); stream.extend((payload.len() as u32).to_le_bytes()); stream.extend(payload); stream.extend(b"bvx$"); fields.extend(der(0x04, &stream)); fields.extend(der( 0x30, &[der(0x02, &[1]), der(0x02, &unsigned(payload.len() as u32))].concat(), )); } else { fields.extend(der(0x04, payload)); } der(0x30, &fields) } /// A private-class DER entry named `name`: `[PRIVATE name] SEQUENCE { IA5 name, inner }`. fn private_entry(name: &str, inner: &[u8]) -> Vec { let mut number = u32::from_be_bytes(name.as_bytes().try_into().unwrap()); let mut groups = vec![]; while number > 0 { groups.push((number & 0x7f) as u8); number >>= 7; } let mut tag = vec![0xff]; for (index, group) in groups.iter().rev().enumerate() { tag.push(if index + 1 < groups.len() { group | 0x80 } else { *group }); } let body = der(0x30, &[der(0x16, name.as_bytes()), inner.to_vec()].concat()); let mut out = tag; out.extend(&der(0, &body)[1..]); out } /// A global boot manifest for the fixture board admitting `krnl` by digest. fn boot_manifest(kernel_digest: &[u8]) -> Vec { let manp = [ private_entry("BORD", &der(0x02, &[0x24])), private_entry("CHIP", &der(0x02, &unsigned(0x8112))), private_entry("CPRO", &der(0x01, &[0xff])), private_entry("CSEC", &der(0x01, &[0xff])), private_entry("SDOM", &der(0x02, &[1])), ] .concat(); let krnl = private_entry( "krnl", &der(0x31, &private_entry("DGST", &der(0x04, kernel_digest))), ); let manb = private_entry( "MANB", &der( 0x31, &[private_entry("MANP", &der(0x31, &manp)), krnl].concat(), ), ); der( 0x30, &[ der(0x16, b"IM4M"), der(0x02, &[0]), der(0x31, &manb), der(0x04, &[0xaa; 4]), der(0x30, &[]), ] .concat(), ) } const BOOT_MANIFEST_MEMBER: &str = "Firmware/Manifests/restore/macOS Customer/apticket.j473ap.im4m"; fn component(name: &str, path: &str) -> String { format!( "{name}DigestAAE=InfoPath{path}" ) } fn restore_manifest() -> String { let components = [ ("KernelCache", "kernelcache.release.test"), ("DeviceTree", "Firmware/DeviceTree.testap.im4p"), ("StaticTrustCache", "Firmware/os.dmg.trustcache"), ("Ap,SecurePageTableMonitor", "Firmware/sptm.test.im4p"), ("Ap,TrustedExecutionMonitor", "Firmware/txm.test.im4p"), ] .map(|(name, path)| component(name, path)) .concat(); format!( r#" ProductVersion27.0.1 ProductBuildVersion26A434 SupportedProductTypesMac14,3 BuildIdentities Ap,ProductTypeMac14,3 ApChipID0x8112 ApBoardID0x24 InfoDeviceClassj473apVariantmacOS CustomerRestoreBehaviorErase Manifest{components}"# ) } fn write_archive(path: &Path, kernel_digest: Option<&[u8]>) { let kernel = macho( MH_FILESET, &[ "__TEXT", "__DATA_SPTM", "__TEXT_EXEC", "__TEXT_BOOT_EXEC", "__PRELINK_INFO", "__DATA", "__LINKEDIT", ], 3, true, ); let sptm = macho( MH_EXECUTE, &["__TEXT", "__TEXT_EXEC", "__DATA", "__LINKEDIT"], 1, false, ); let txm = macho( MH_EXECUTE, &[ "__TEXT", "__TEXT_EXEC", "__TEXT_BOOT_EXEC", "__DATA", "__LINKEDIT", ], 2, false, ); let members = [ ("BuildManifest.plist", restore_manifest().into_bytes()), ("kernelcache.release.test", im4p("krnl", &kernel, true)), ( "Firmware/DeviceTree.testap.im4p", im4p("dtre", &device_tree(), true), ), ( "Firmware/os.dmg.trustcache", im4p("trst", &trust_cache(), false), ), ("Firmware/sptm.test.im4p", im4p("sptm", &sptm, false)), ("Firmware/txm.test.im4p", im4p("trxm", &txm, false)), ]; let manifest = kernel_digest.map(|digest| (BOOT_MANIFEST_MEMBER, boot_manifest(digest))); let mut zip = zip::ZipWriter::new(std::fs::File::create(path).unwrap()); let options = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); for (name, bytes) in members.into_iter().chain(manifest) { zip.start_file(name, options).unwrap(); zip.write_all(&bytes).unwrap(); } zip.finish().unwrap(); } fn success(output: &Output) { assert!( output.status.success(), "{}", String::from_utf8_lossy(&output.stderr) ); } fn json(path: &Path) -> serde_json::Value { serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap() } #[test] fn restore_member_identities() { let dir = tempfile::tempdir().unwrap(); write_archive(&dir.path().join("fixture.ipsw"), None); success(&cli( dir.path(), &[ "image-manifest", "fixture.ipsw", "--hash-members", "--output", "manifest.json", ], )); let manifest = json(&dir.path().join("manifest.json")); let identity = &manifest["identities"][0]; assert_eq!(identity["ap_chip_id"], "0x8112"); let kernel = &identity["components"]["KernelCache"]["member"]; assert_eq!(kernel["im4p_type"], "krnl"); let container = std::fs::read(dir.path().join("fixture.ipsw")).unwrap(); assert!(kernel["bytes"].as_u64().unwrap() < container.len() as u64); let extracted = cli( dir.path(), &[ "extract-image", "fixture.ipsw", "--member", "kernelcache.release.test", "--output", "kernel.im4p", ], ); success(&extracted); success(&cli( dir.path(), &["decode-im4p", "kernel.im4p", "--output", "kernel.macho"], )); let receipt = json(&dir.path().join("kernel.macho.json")); assert_eq!(receipt["im4p"]["compression"], "lzfse"); assert_eq!(receipt["im4p"]["container_sha256"], kernel["sha256"]); assert_eq!( std::fs::read(dir.path().join("kernel.macho")) .unwrap() .len(), 7 * PAGE ); // Existing outputs reject a second extraction. assert!( !cli( dir.path(), &["decode-im4p", "kernel.im4p", "--output", "kernel.macho"] ) .status .success() ); } #[test] fn boot_bundle_preparation() { let dir = tempfile::tempdir().unwrap(); // The BuildManifest declares every component's digest as 00 01. write_archive(&dir.path().join("fixture.ipsw"), Some(&[0, 1])); let args = [ "boot", "prepare", "--ipsw", "fixture.ipsw", "--model", "Mac14,3", "--output", "bundle", "--dram-size", "0x40000000", "--syscfg", "SrNm=4331", ]; success(&cli(dir.path(), &args)); let bundle = dir.path().join("bundle"); let manifest = json(&bundle.join("bundle.json")); assert_eq!(manifest["target"]["chip_id"], 0x8112); assert_eq!( manifest["archive"]["build_manifest_sha256"] .as_str() .unwrap() .len(), 64 ); let regions = manifest["regions"].as_array().unwrap(); assert_eq!(regions[0]["name"], "BootManifest"); assert_eq!(regions[1]["name"], "TXM-ro"); assert_eq!( regions[0]["guest_pa"].as_u64().unwrap() + regions[0]["memory_bytes"].as_u64().unwrap(), regions[1]["guest_pa"].as_u64().unwrap() ); assert_eq!(regions.last().unwrap()["name"], "BootArgs"); assert_eq!(manifest["entry"]["image"], "SPTM"); let sptm_rx = regions.iter().find(|r| r["name"] == "SPTM-rx").unwrap(); assert_eq!(manifest["entry"]["physical_address"], sptm_rx["guest_pa"]); assert_eq!(manifest["entry_x0"], regions.last().unwrap()["guest_pa"]); // Copying each region reproduces its recorded hash. for region in regions { let file = std::fs::read(bundle.join(region["file"].as_str().unwrap())).unwrap(); let start = region["file_offset"].as_u64().unwrap() as usize; let end = start + region["bytes"].as_u64().unwrap() as usize; assert_eq!( stela_formats::sha256(&file[start..end]), region["sha256"].as_str().unwrap() ); } let placeholders = manifest["placeholders"].as_array().unwrap(); assert_eq!(placeholders[0]["resolution"], "syscfg/SrNm/0x20: 32 bytes"); assert!( manifest["patches"] .as_array() .unwrap() .iter() .any(|p| p["field"] == "/chosen random-seed" && p["required"] == true) ); let security = manifest["security"].as_array().unwrap(); let ipsw = std::fs::File::open(dir.path().join("fixture.ipsw")).unwrap(); let mut archive = zip::ZipArchive::new(ipsw).unwrap(); let mut member = vec![]; std::io::Read::read_to_end( &mut archive.by_name(BOOT_MANIFEST_MEMBER).unwrap(), &mut member, ) .unwrap(); let hash = security .iter() .find(|d| d["property"] == "boot-manifest-hash") .unwrap(); assert_eq!( hash["value_hex"], hex::encode(stela_loader::im4m::sha384(&member)) ); assert!( security .iter() .any(|d| d["property"] == "lp-smb0" && d["value_hex"] == "01000000") ); assert!(!cli(dir.path(), &args).status.success()); // A manifest that admits a different kernel is refused. write_archive(&dir.path().join("other.ipsw"), Some(&[9, 9])); let mut other = args; other[3] = "other.ipsw"; other[7] = "other-bundle"; let refused = cli(dir.path(), &other); assert!(!refused.status.success()); assert!(String::from_utf8_lossy(&refused.stderr).contains("digest differs")); }