🆕 Restore macOS from an IPSW onto an arm64 VM's disk, offline

reims-restore installs macOS 14 to 27 from a UniversalMac IPSW onto an arm64
VM's disk the way a Virtualization.framework restore does, but writes the disk
itself. It reads the IPSW where it is, asks Apple's TSS for the VM's tickets,
and lays out the GPT, the three APFS containers, NVRAM and the auxiliary
storage as a fresh VZ restore leaves them. No VM runs and no Apple code runs:
no AVPBooter, iBoot, restore OS or ASR. That is the owner's rule for the
install (11-11), and it is what lets the same restore run on arm64 Linux and
on a Mac. A guest boots the result under QEMU's vmapple on Ambrosia.

It is its own Cargo workspace (like reims-ctl), with reims-apfs, its APFS
reader and writer, as a member:
- the IPSW's members, BuildManifest identities, UDIF, AEA (with Apple's key
  service) and the deflated images 14's IPSWs keep (ipsw, manifest, udif,
  aea, image);
- TSS requests and their checked answers, and Image4's DER (tss, img4);
- the install plan, which equals VZ's disks record for record (plan,
  xml_plist, mtree), and the three containers it writes, with the system
  volume sealed by our own seal and root hash (containers, reims-apfs);
- NVRAM, both banks, and the ean storage with the SFR manifest (aux);
- the LocalPolicies, signed by the project's chain, with the guest's trust
  anchors swapped for that chain by Ambrosia Kernel>Patch entries found in
  the IPSW's own kernel collection (policy, anchors, kernelcache);
- macOS 14's Data volume, which its first boot makes by EACS, and
  finish-eacs after it (pipeline);
- the current IPSW from Apple's catalog, downloaded and continued in place,
  never truncating a file (catalog, download, http).
docs/design.md says what each step writes and how each fact was found
(VZ's guests, the IPSWs, or measured). Nothing from an IPSW or a guest is
committed; the tests use inputs written from scratch.

docs/lessons.md records why a live download check must never hard-link the
owner's files: an earlier downloader truncated a hard-linked IPSW in place.

This is the lane's WIP history squashed. Its restore-OS route (route (a),
closed by Apple's per-VM activation attestation) is left out.
This commit is contained in:
Anees Iqbal committed 2026-11-16 02:03:39 -08:00
1 parent d707b8450b
commit ad3b37b8e8
66 files changed
+24244

No files matched your search

+1
View File
@@ -19,3 +19,4 @@ __pycache__/
# reims-ctl's, which is a workspace of its own.
/target*/
/crates/reims-ctl/target/
/crates/reims-restore/target/
+1836
View File
File diff suppressed because it is too large. Load diff
+70
View File
@@ -0,0 +1,70 @@
# reims-restore: restores an IPSW onto an arm64 VM's disk without Apple's tools (docs/design.md).
# Its own Cargo workspace, like reims-ctl, so it builds without the rest of the tree. reims-apfs
# (apfs/) is the disk side: GPT and APFS.
[package]
name = "reims-restore"
version = "0.1.0"
edition = "2024"
rust-version = "1.98.1"
publish = false
license = "GPL-2.0-or-later OR LGPL-3.0-or-later"
description = "Restore macOS from an IPSW onto an arm64 VM's disk, without Apple's tools"
[workspace]
resolver = "3"
members = ["apfs"]
[lib]
path = "src/lib.rs"
[[bin]]
name = "reims-restore"
path = "src/main.rs"
[dependencies]
# The disk side: APFS containers and the GPT (apfs/, lane R2).
reims-apfs = { path = "apfs" }
# Apple Encrypted Archive decryption, given the archive's key (aea.rs).
aea-tools = "0.1.1"
anyhow = "1.0.104"
# The base64 of an AEA's fcs-response (aea.rs).
base64 = "0.22.1"
# UDIF chunks compressed with bzip2 (udif.rs).
bzip2 = "0.6.1"
# The CRC-32 of each IPSW member it streams (ipsw.rs), and the ean storage's (aux.rs).
crc32fast = "1.5.5"
clap = { version = "4.6.7", features = ["derive", "wrap_help"] }
# UDIF chunks compressed with zlib, and the IPSW's deflated members (udif.rs, ipsw.rs).
flate2 = "1.1.11"
# Unwraps an AEA's key with the private key Apple's key service returns: HPKE, DHKEM(P-256), AES-GCM.
hpke = { version = "0.15.1", default-features = false, features = ["alloc", "aes", "nistp"] }
# UDIF chunks compressed with LZMA (xz), rare in IPSWs (udif.rs).
lzma-rs = "0.3.0"
# UDIF chunks compressed with LZFSE (udif.rs).
lzfse_rust = "0.2.1"
# The PEM private key Apple's key service returns for an AEA (aea.rs).
p256 = { version = "0.14.0", features = ["pkcs8", "pem"] }
# Signs the VM's LocalPolicies: ECDSA P-384 with SHA-384 (policy.rs).
p384 = { version = "0.14.0", features = ["ecdsa", "pkcs8", "pem"] }
# BuildManifest.plist, Restore.plist, the TSS request and response, UDIF's resource fork.
plist = "1.10.3"
getrandom = "0.4.3"
# statvfs, for the space free where the VM goes (pipeline.rs), and the CLI's signal handler.
libc = "0.2.191"
# The SHA-1 Apple's catalog gives for an IPSW, checked as it downloads (download.rs).
sha1 = "0.11.0"
# The JSON of an AEA's fcs-response (aea.rs).
serde_json = "1.0.154"
sha2 = "0.11.1"
# HTTPS to Apple's TSS, key service and CDN, with rustls.
ureq = "3.5.1"
uuid = { version = "1.29.2", features = ["v4"] }
# The IPSW is a zip (ipsw.rs).
zip = { version = "9.5.1", default-features = false, features = ["deflate-flate2"] }
[dev-dependencies]
# Writes the tests' synthetic IPSWs.
zip = { version = "9.5.1", default-features = false, features = ["deflate-flate2"] }
[profile.release]
debug = "line-tables-only"
+30
View File
@@ -0,0 +1,30 @@
# reims-apfs: reads files out of APFS containers (an IPSW's system image, a VM's disk), checking
# every object it reads.
[package]
name = "reims-apfs"
version = "0.1.0"
edition = "2024"
rust-version = "1.98.1"
publish = false
license = "GPL-2.0-or-later OR LGPL-3.0-or-later"
description = "A checked APFS reader: containers, volumes and files by path"
[dependencies]
# CRC-32C, the hash APFS keys directory entries by (names.rs).
crc = "3.4.0"
# LZVN and LZFSE, two of the encodings of compressed files (decmpfs.rs). BSD-3-Clause.
ferrosys-lzfse = "0.8.0"
# zlib, another (decmpfs.rs).
flate2 = "1.1.11"
# Unicode's decompositions, combining classes and case foldings, which APFS normalizes names with
# before hashing them (names.rs). Unicode-3.0.
ferrosys-ucd = "0.8.0"
# The GUID partition table (gpt.rs).
gptman = "3.1.1"
# The SHA-256 a sealed volume checks its file-system tree's nodes by (read.rs).
sha2 = "0.11.1"
thiserror = "2.0.21"
[dev-dependencies]
# An independent APFS writer: the tests read the containers it formats.
ferrosys = { version = "0.8.0", default-features = false, features = ["apfs"] }
@@ -0,0 +1,41 @@
//! Read one file out of an APFS container or a GPT disk image holding one, checking every object
//! on the way: `apfs-cat IMAGE PATH [OUT]`. Without OUT, it prints the file's size, how it is
//! stored and its extents; with OUT, it writes the file's content there. The System volume is
//! read, or the container's only volume.
use std::sync::Arc;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = std::env::args().skip(1).collect();
let [image, path, rest @ ..] = args.as_slice() else {
return Err("usage: apfs-cat IMAGE PATH [OUT]".into());
};
let c = reims_apfs::open(Arc::new(std::fs::File::open(image)?))?;
for v in c.volumes()? {
eprintln!("volume {}: {:?}, role {:#x}", v.index, v.name(), v.role());
}
let v = c.system_volume()?;
let e = v.lookup(path)?;
let data = v.read(&e)?;
eprintln!(
"{path}: inode {}, mode {:o}, {} bytes{}",
e.id,
e.inode.mode,
data.len(),
if e.is_compressed() {
", compressed"
} else {
""
}
);
for x in v.extents(&e)? {
eprintln!(
" extent at {}: {} bytes at {:?}",
x.logical, x.len, x.offset
);
}
if let [out] = rest {
std::fs::write(out, &data)?;
}
Ok(())
}
+153
View File
@@ -0,0 +1,153 @@
//! B-tree nodes: their table of contents, keys and values (Apple File System Reference,
//! "B-Trees").
use crate::le::{u16_at, u32_at};
use crate::ondisk::{BtreeInfo, btree};
use crate::{Result, corrupt};
/// The largest hash a hashed tree's index entry holds (`BTREE_NODE_HASH_SIZE_MAX`).
const MAX_HASH: usize = 64;
/// One node, parsed over its block.
#[derive(Clone, Debug)]
pub(crate) struct Node {
pub block: u64,
pub bytes: Vec<u8>,
pub flags: u16,
pub level: u16,
pub nkeys: u32,
key_start: usize,
val_end: usize,
toc_start: usize,
/// Key and value sizes, for a node whose entries are fixed-size.
fixed: Option<(usize, usize)>,
}
impl Node {
/// Parse `bytes`, read from `block`. A fixed-size node's entry sizes come from its tree's
/// info: `fixed` is the info's key and value sizes, where the tree has them (an index node
/// of a fixed tree holds 8-byte child identifiers, plus a hash in a hashed tree).
pub(crate) fn parse(block: u64, bytes: Vec<u8>, info: Option<&BtreeInfo>) -> Result<Self> {
let len = bytes.len();
let flags = u16_at(&bytes, btree::FLAGS);
let level = u16_at(&bytes, btree::LEVEL);
let nkeys = u32_at(&bytes, btree::NKEYS);
let toc_off = usize::from(u16_at(&bytes, btree::TABLE_SPACE));
let toc_len = usize::from(u16_at(&bytes, btree::TABLE_SPACE + 2));
let toc_start = btree::DATA + toc_off;
let key_start = toc_start + toc_len;
let val_end = if flags & btree::NODE_ROOT != 0 {
len - btree::INFO_SIZE
} else {
len
};
if key_start > val_end {
return Err(corrupt(
block,
"B-tree node's table of contents runs past its value area",
));
}
let leaf = flags & btree::NODE_LEAF != 0;
if leaf != (level == 0) {
return Err(corrupt(
block,
format!("B-tree node flags {flags:#x} disagree with level {level}"),
));
}
let fixed = if flags & btree::NODE_FIXED_KV_SIZE != 0 {
let root_info;
let info = if flags & btree::NODE_ROOT != 0 {
root_info = BtreeInfo::parse(&bytes[len - btree::INFO_SIZE..]);
&root_info
} else {
info.ok_or_else(|| {
corrupt(block, "fixed-size B-tree node without its tree's info")
})?
};
let vsize = if leaf {
info.val_size as usize
} else if info.flags & btree::HASHED != 0 {
8 + MAX_HASH
} else {
8
};
Some((info.key_size as usize, vsize))
} else {
None
};
let entry = if fixed.is_some() { 4 } else { 8 };
if (nkeys as usize) * entry > toc_len {
return Err(corrupt(
block,
format!("{nkeys} keys do not fit a {toc_len}-byte table of contents"),
));
}
Ok(Self {
block,
bytes,
flags,
level,
nkeys,
key_start,
val_end,
toc_start,
fixed,
})
}
pub(crate) fn is_leaf(&self) -> bool {
self.flags & btree::NODE_LEAF != 0
}
pub(crate) fn is_root(&self) -> bool {
self.flags & btree::NODE_ROOT != 0
}
/// The tree info a root node ends with.
pub(crate) fn info(&self) -> Option<BtreeInfo> {
self.is_root()
.then(|| BtreeInfo::parse(&self.bytes[self.bytes.len() - btree::INFO_SIZE..]))
}
/// Entry `i`'s key and value byte ranges; the value is `None` where its offset is invalid.
pub(crate) fn entry(&self, i: u32) -> Result<(&[u8], Option<&[u8]>)> {
let t = self.toc_start + i as usize * if self.fixed.is_some() { 4 } else { 8 };
let (koff, klen, voff, vlen) = match self.fixed {
Some((ks, vs)) => (
usize::from(u16_at(&self.bytes, t)),
ks,
u16_at(&self.bytes, t + 2),
vs,
),
None => (
usize::from(u16_at(&self.bytes, t)),
usize::from(u16_at(&self.bytes, t + 2)),
u16_at(&self.bytes, t + 4),
usize::from(u16_at(&self.bytes, t + 6)),
),
};
let ks = self.key_start + koff;
if ks + klen > self.val_end {
return Err(corrupt(
self.block,
format!("entry {i}'s key runs past the key area"),
));
}
let key = &self.bytes[ks..ks + klen];
if voff == btree::OFF_INVALID {
return Ok((key, None));
}
let voff = usize::from(voff);
if voff > self.val_end - self.key_start || vlen > voff {
return Err(corrupt(
self.block,
format!("entry {i}'s value is outside the value area"),
));
}
let vs = self.val_end - voff;
// A fixed tree's hashed index value is the child and a hash of the tree's hash size,
// shorter than the maximum this crate assumes; clamp to the node.
let ve = (vs + vlen).min(self.val_end);
Ok((key, Some(&self.bytes[vs..ve])))
}
}
+461
View File
@@ -0,0 +1,461 @@
//! Canonicalising an unsealed system volume's file-system records into the form the seal covers:
//! every timestamp set to the mtree time `T`, write generations and stream byte counters fixed,
//! file extents taken out of the tree (they move to the physical file-extent tree), and the
//! per-segment content hashes (`file_info`) added. Measured against Apple's sealed system volumes
//! of macOS 14 to 27: every inode time, every directory-entry `date_added`, and the data-stream
//! and attribute-stream byte counters become constants, and the tree holds no file extents.
use crate::fs::{self, INODE_FIXED, xf};
use crate::le::{u16_at, u64_at};
use crate::ondisk::rec;
use crate::seal::Record;
/// The data-stream and attribute-stream byte counters a sealed volume records: both one.
const STREAM_COUNTER: u64 = 1;
/// A sealed inode's write generation.
const WRITE_GEN: u32 = 1;
/// Set the little-endian `u64` at `off` in `v`, if it fits.
fn put_u64(v: &mut [u8], off: usize, x: u64) {
if off + 8 <= v.len() {
v[off..off + 8].copy_from_slice(&x.to_le_bytes());
}
}
fn put_u32(v: &mut [u8], off: usize, x: u32) {
if off + 4 <= v.len() {
v[off..off + 4].copy_from_slice(&x.to_le_bytes());
}
}
/// Canonicalise an inode value in place to time `t` (nanoseconds): its four timestamps, its
/// write generation, and the byte counters of its data-stream extended field.
fn canon_inode(v: &mut [u8], t: u64) {
if v.len() < INODE_FIXED {
return;
}
// create, modify, change, access times.
for off in [16, 24, 32, 40] {
put_u64(v, off, t);
}
// write_generation_counter.
put_u32(v, 64, WRITE_GEN);
// The data-stream extended field (xf kind DSTREAM) carries total_bytes_written at +24 and
// total_bytes_read at +32 within its 40-byte j_dstream_t; set both to one. Walk the xfields
// to find the field's byte range in the raw value.
let xf_blob = &v[INODE_FIXED..];
if xf_blob.len() < 4 {
return;
}
let n = usize::from(u16_at(xf_blob, 0));
let mut data = 4 + n * 4;
let mut found: Option<usize> = None;
for i in 0..n {
let h = 4 + i * 4;
if h + 4 > xf_blob.len() {
break;
}
let kind = xf_blob[h];
let size = usize::from(u16_at(xf_blob, h + 2));
if data + size > xf_blob.len() {
break;
}
if kind == xf::DSTREAM {
found = Some(INODE_FIXED + data);
}
data += size.div_ceil(8) * 8;
}
if let Some(ds) = found {
put_u64(v, ds + 24, STREAM_COUNTER);
put_u64(v, ds + 32, STREAM_COUNTER);
}
}
/// Canonicalise a directory-entry value in place: its `date_added` becomes `t`.
fn canon_dir_rec(v: &mut [u8], t: u64) {
put_u64(v, 8, t);
}
/// Canonicalise an attribute value in place: a stream attribute's data-stream byte counters
/// become one. The value is flags(2) + len(2) + data; a stream attribute's data is the stream
/// identifier (8) then a j_dstream_t whose total_bytes_written is at +24 and total_bytes_read at
/// +32, i.e. offsets 36 and 44 of the value.
fn canon_xattr(v: &mut [u8], block_size: u64) {
if v.len() < 4 {
return;
}
let flags = u16_at(v, 0);
if flags & fs::XATTR_DATA_STREAM == 0 {
return;
}
// j_dstream_t within the value: size at +12, allocated_size at +20. Sealing tightens the
// allocated size to the size rounded up to a block (an unsealed stream may over-allocate).
let size = u64_at(v, 12);
let alloced = size.div_ceil(block_size) * block_size;
put_u64(v, 20, alloced);
put_u64(v, 36, STREAM_COUNTER);
put_u64(v, 44, STREAM_COUNTER);
}
/// Canonicalise a key-ordered record stream: patch inode, directory-entry and stream-attribute
/// values to the sealed constants, and drop file-extent records (they move to the file-extent
/// tree). `t` is the mtree time in nanoseconds. The `file_info` content hashes are added
/// separately (they need the files' decoded content). The result stays in key order.
#[must_use]
pub fn canonicalize(records: &[Record], t: u64, block_size: u64) -> Vec<Record> {
let mut out = Vec::with_capacity(records.len());
for r in records {
let ty = fs::key_header(&r.key).1;
if ty == rec::FILE_EXTENT {
continue;
}
let mut val = r.val.clone();
match ty {
rec::INODE => canon_inode(&mut val, t),
rec::DIR_REC => canon_dir_rec(&mut val, t),
rec::XATTR => canon_xattr(&mut val, block_size),
_ => {}
}
out.push(Record {
key: r.key.clone(),
val,
});
}
out
}
/// A sealed volume hashes each data stream's content in 16 KiB segments.
pub const SEGMENT: usize = 16 * 1024;
/// The `file_info` records for a data stream of `content` bytes, keyed by `stream_id`: one per
/// 16 KiB segment, its value the SHA-256 of the segment zero-padded to whole `block_size` blocks,
/// after a 16-bit block count and the hash length (Apple File System Reference, "Sealed Volumes";
/// the segment and padding are measured against Apple's sealed system volumes).
#[must_use]
pub fn file_infos(stream_id: u64, content: &[u8], block_size: usize) -> Vec<Record> {
use sha2::{Digest, Sha256};
let mut out = Vec::new();
let mut off = 0usize;
while off < content.len() {
let end = (off + SEGMENT).min(content.len());
let seg = &content[off..end];
let blocks = seg.len().div_ceil(block_size);
let mut buf = vec![0u8; blocks * block_size];
buf[..seg.len()].copy_from_slice(seg);
let hash: [u8; 32] = Sha256::digest(&buf).into();
let mut key = Vec::with_capacity(16);
key.extend_from_slice(&fs::key_word(stream_id, rec::FILE_INFO).to_le_bytes());
key.extend_from_slice(&((1u64 << 56) | off as u64).to_le_bytes());
let mut val = Vec::with_capacity(35);
val.extend_from_slice(&(blocks as u16).to_le_bytes());
val.push(32);
val.extend_from_slice(&hash);
out.push(Record { key, val });
off = end;
}
out
}
/// The content stream a file's `file_info` hashes, and its stream identifier: an uncompressed
/// file's data stream (keyed by the inode id), or a resource-fork-compressed file's decoded
/// content (keyed by the resource fork's stream id). `None` for a directory, a symbolic link, an
/// empty file, or an inline-compressed file (whose content is in its attribute, already hashed as
/// part of the tree, not in a data stream). `read` returns a file's decoded content.
pub fn file_stream<E>(
oid: u64,
inode_val: &[u8],
xattrs: &[(Vec<u8>, Vec<u8>)],
read: impl FnOnce() -> Result<Vec<u8>, E>,
) -> Result<Option<(u64, Vec<u8>)>, E> {
let Some(inode) = fs::Inode::parse(inode_val) else {
return Ok(None);
};
if inode.mode & 0o170000 != 0o100000 {
return Ok(None);
}
let compressed = inode.bsd_flags & crate::decmpfs::UF_COMPRESSED != 0;
if !compressed {
let content = read()?;
return Ok((!content.is_empty()).then_some((oid, content)));
}
// A compressed file: its decmpfs header says whether its content is in the resource fork.
let header = xattrs
.iter()
.find(|(k, _)| fs::xattr_name(k) == crate::decmpfs::XATTR)
.and_then(|(_, v)| match fs::parse_xattr(v)?.1 {
fs::XattrData::Embedded(d) => crate::decmpfs::Header::parse(&d),
fs::XattrData::Stream(..) => None,
});
let Some(header) = header else {
return Ok(None);
};
if !header.in_resource_fork() {
return Ok(None);
}
let fork_id = xattrs
.iter()
.find(|(k, _)| fs::xattr_name(k) == crate::decmpfs::RESOURCE_FORK)
.and_then(|(_, v)| match fs::parse_xattr(v)?.1 {
fs::XattrData::Stream(id, _) => Some(id),
fs::XattrData::Embedded(_) => None,
});
let Some(fork_id) = fork_id else {
return Ok(None);
};
let content = read()?;
Ok((!content.is_empty()).then_some((fork_id, content)))
}
/// The extents a file-extent record names, for building the physical file-extent tree the seal
/// does not cover: (stream id, logical offset, length, flags, physical block).
#[must_use]
pub fn file_extent(key: &[u8], val: &[u8]) -> (u64, u64, u64, u8, u64) {
let stream = fs::key_header(key).0;
let logical = u64_at(key, 8);
let lf = u64_at(val, 0);
(
stream,
logical,
lf & 0x00ff_ffff_ffff_ffff,
(lf >> 56) as u8,
u64_at(val, 8),
)
}
/// One data stream of a sealed volume: its identifier (an inode's private identifier, or an
/// attribute stream's), the inode that owns it, the blocks it is given (its allocated size, as
/// the seal records it), its size in bytes, and where its bytes are in the source volume.
#[derive(Clone, Debug)]
pub struct SealedStream {
pub id: u64,
pub owner: u64,
pub blocks: u64,
pub size: u64,
/// The source's runs over the stream's `size` bytes, in order: `None` a hole.
pub runs: Vec<crate::write::copy::SourceRun>,
}
/// An unsealed system volume made ready to seal: its canonical records in key order, the
/// `file_info` hashes among them, its data streams in the order of their first block in the
/// source, and what its superblock records.
pub struct SealedSet {
pub records: Vec<Record>,
pub streams: Vec<SealedStream>,
pub counts: crate::write::volume::Counts,
pub next_obj_id: u64,
pub next_doc_id: u32,
/// How many inodes share another's data stream (clones); the stream is given once.
pub shared_streams: u64,
}
/// Read `vol`, an unsealed system volume, into the set its seal covers at mtree time `t`
/// (nanoseconds): every record canonicalised ([`canonicalize`]), each regular file's content
/// hashed into its `file_info` records ([`file_stream`], [`file_infos`]), and its data streams
/// gathered from the file extents the seal leaves out.
///
/// # Errors
///
/// The volume's records or a file's content fail their checks.
pub fn sealed_set(vol: &crate::Volume, t: u64) -> crate::Result<SealedSet> {
use std::collections::HashMap;
use crate::write::copy::SourceRun;
let c = vol.container();
let bs = u64::from(c.block_size());
let source = vol.fs_tree_records()?;
// Each stream's extents, each inode's value and attributes.
let mut extents: HashMap<u64, Vec<fs::FileExtent>> = HashMap::new();
let mut inodes: Vec<(u64, usize)> = Vec::new();
let mut xattrs: HashMap<u64, Vec<usize>> = HashMap::new();
for (i, (k, v)) in source.iter().enumerate() {
let (oid, ty) = fs::key_header(k);
match ty {
rec::FILE_EXTENT => extents
.entry(oid)
.or_default()
.push(fs::FileExtent::parse(k, v)),
rec::INODE => inodes.push((oid, i)),
rec::XATTR => xattrs.entry(oid).or_default().push(i),
_ => {}
}
}
for x in extents.values_mut() {
x.sort_by_key(|e| e.logical);
}
let runs_of = |id: u64, size: u64| -> Vec<SourceRun> {
let mut out = Vec::new();
let mut at = 0u64;
for e in extents.get(&id).map_or(&[][..], Vec::as_slice) {
if e.logical >= size {
break;
}
if e.logical > at {
out.push(SourceRun {
len: e.logical - at,
phys: None,
});
at = e.logical;
}
let len = e.len.min(size - at);
out.push(SourceRun {
len,
phys: (e.phys != 0).then_some(e.phys),
});
at += len;
}
if at < size {
out.push(SourceRun {
len: size - at,
phys: None,
});
}
out
};
let read_runs = |runs: &[SourceRun]| -> crate::Result<Vec<u8>> {
let total: u64 = runs.iter().map(|r| r.len).sum();
let mut out = vec![
0u8;
usize::try_from(total).map_err(|_| crate::Error::Unsupported(
format!("a stream of {total} bytes")
))?
];
let mut at = 0usize;
for r in runs {
let n = r.len as usize;
if let Some(p) = r.phys {
c.read_bytes(p, 0, &mut out[at..at + n])?;
}
at += n;
}
Ok(out)
};
// The streams: each inode's data stream and each attribute's, given once.
let mut streams: HashMap<u64, SealedStream> = HashMap::new();
let mut shared_streams = 0u64;
for &(oid, i) in &inodes {
let Some(inode) = fs::Inode::parse(&source[i].1) else {
continue;
};
if let Some(d) = inode.dstream() {
if streams.contains_key(&inode.private_id) {
shared_streams += 1;
continue;
}
streams.insert(
inode.private_id,
SealedStream {
id: inode.private_id,
owner: oid,
blocks: d.alloced_size.div_ceil(bs),
size: d.size,
runs: runs_of(inode.private_id, d.size),
},
);
}
for &x in xattrs.get(&oid).map_or(&[][..], Vec::as_slice) {
if let Some((_, fs::XattrData::Stream(id, d))) = fs::parse_xattr(&source[x].1) {
// The seal tightens an attribute stream's allocation to its size ([`canon_xattr`]).
streams.entry(id).or_insert_with(|| SealedStream {
id,
owner: oid,
blocks: d.size.div_ceil(bs),
size: d.size,
runs: runs_of(id, d.size),
});
}
}
}
let mut streams: Vec<SealedStream> = streams.into_values().collect();
let first = |s: &SealedStream| s.runs.iter().find_map(|r| r.phys).unwrap_or(u64::MAX);
streams.sort_by_key(|s| (first(s), s.id));
// The file_info hashes, files read in the order of their first block in the source.
let by_id: HashMap<u64, usize> = streams.iter().enumerate().map(|(n, s)| (s.id, n)).collect();
let mut files: Vec<(u64, u64, usize)> = Vec::new();
for &(oid, i) in &inodes {
let Some(inode) = fs::Inode::parse(&source[i].1) else {
continue;
};
if inode.mode & 0o170000 != 0o100000 {
continue;
}
let at = by_id
.get(&inode.private_id)
.map_or(u64::MAX, |&n| first(&streams[n]));
files.push((at, oid, i));
}
files.sort_unstable();
let mut infos: Vec<Record> = Vec::new();
let empty = Vec::new();
for &(_, oid, i) in &files {
let ival = &source[i].1;
let xs: Vec<(Vec<u8>, Vec<u8>)> = xattrs
.get(&oid)
.unwrap_or(&empty)
.iter()
.map(|&x| source[x].clone())
.collect();
let inode = fs::Inode::parse(ival).expect("parsed above");
let stream = file_stream(oid, ival, &xs, || -> crate::Result<Vec<u8>> {
if inode.bsd_flags & crate::decmpfs::UF_COMPRESSED == 0 {
let size = inode.dstream().map_or(0, |d| d.size);
return read_runs(&runs_of(inode.private_id, size));
}
let attr = |name: &[u8]| {
xs.iter()
.find(|(k, _)| fs::xattr_name(k) == name)
.and_then(|(_, v)| fs::parse_xattr(v))
.map(|x| x.1)
};
let Some(fs::XattrData::Embedded(header)) = attr(crate::decmpfs::XATTR) else {
return Err(crate::corrupt(
0,
format!("compressed file {oid} without its header"),
));
};
let fork = match attr(crate::decmpfs::RESOURCE_FORK) {
Some(fs::XattrData::Stream(id, d)) => Some(read_runs(&runs_of(id, d.size))?),
Some(fs::XattrData::Embedded(b)) => Some(b),
None => None,
};
crate::decmpfs::decode(&header, fork.as_deref())
})?;
if let Some((sid, content)) = stream {
infos.extend(file_infos(sid, &content, bs as usize));
}
}
// The canonical records, the hashes among them, in key order.
let mut records: Vec<Record> = Vec::with_capacity(source.len() + infos.len());
for (k, mut v) in source {
let ty = fs::key_header(&k).1;
match ty {
rec::FILE_EXTENT => continue,
rec::INODE => canon_inode(&mut v, t),
rec::DIR_REC => canon_dir_rec(&mut v, t),
rec::XATTR => canon_xattr(&mut v, bs),
_ => {}
}
records.push(Record { key: k, val: v });
}
records.extend(infos);
records.sort_by(|a, b| fs::compare_keys(&a.key, &b.key));
let sb = &vol.sb;
Ok(SealedSet {
records,
streams,
counts: crate::write::volume::Counts {
files: sb.num_files,
directories: sb.num_directories,
symlinks: sb.num_symlinks,
other: sb.num_other_fsobjects,
},
next_obj_id: sb.next_obj_id,
next_doc_id: sb.next_doc_id,
shared_streams,
})
}
+251
View File
@@ -0,0 +1,251 @@
//! Transparent file compression (decmpfs): a compressed file's content, decoded from its
//! `com.apple.decmpfs` attribute and, where the type keeps it there, its resource fork.
//!
//! The attribute starts with a 16-byte header: `fpmc`, the compression type (little-endian
//! 32-bit) and the content's size (little-endian 64-bit). The content is cut into 64 KiB chunks,
//! each one stream of the type's encoding. Types 3 (zlib), 7 (LZVN), 9 (stored) and 11 (LZFSE)
//! keep their one chunk after the header; types 4 (zlib), 8 (LZVN), 10 (stored) and 12 (LZFSE)
//! keep their chunks in the resource fork. Types 8, 10 and 12 open the fork with a little-endian
//! 32-bit offset per chunk and one for the end; type 4's fork is a classic resource fork whose
//! one resource is a chunk count and each chunk's offset and length. A zlib chunk opening with
//! 0xFF, an LZVN chunk opening with 0x06 and a stored chunk opening with 0xCC hold their content
//! raw after that byte. (The layouts as ferrosys, MIT OR Apache-2.0, records them.)
use crate::{Error, Result};
pub const MAGIC: &[u8; 4] = b"fpmc";
pub const HEADER_LEN: usize = 16;
pub const CHUNK: usize = 64 * 1024;
/// The attribute that holds a compressed file's header.
pub const XATTR: &[u8] = b"com.apple.decmpfs";
/// The attribute that holds a compressed file's resource fork.
pub const RESOURCE_FORK: &[u8] = b"com.apple.ResourceFork";
/// The BSD flag a compressed file carries.
pub const UF_COMPRESSED: u32 = 0x20;
/// A compression header.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Header {
pub kind: u32,
pub size: u64,
}
impl Header {
/// Parse the header at the start of a `com.apple.decmpfs` attribute.
#[must_use]
pub fn parse(attr: &[u8]) -> Option<Self> {
(attr.len() >= HEADER_LEN && &attr[..4] == MAGIC).then(|| Self {
kind: u32::from_le_bytes(attr[4..8].try_into().unwrap()),
size: u64::from_le_bytes(attr[8..16].try_into().unwrap()),
})
}
/// Whether the type keeps its content in the resource fork.
#[must_use]
pub const fn in_resource_fork(&self) -> bool {
matches!(self.kind, 4 | 8 | 10 | 12 | 14)
}
}
#[derive(Clone, Copy)]
enum Enc {
Zlib,
Lzvn,
Stored,
Lzfse,
}
fn encoding(kind: u32) -> Result<Enc> {
Ok(match kind {
3 | 4 => Enc::Zlib,
7 | 8 => Enc::Lzvn,
9 | 10 => Enc::Stored,
11 | 12 => Enc::Lzfse,
k => return Err(Error::Unsupported(format!("decmpfs compression type {k}"))),
})
}
fn bad(what: &str) -> Error {
Error::Invalid(format!("compressed file: {what}"))
}
/// Decode one chunk of `enc` into `out`, which is exactly the chunk's share of the content.
fn chunk(enc: Enc, input: &[u8], out: &mut [u8]) -> Result<()> {
let raw =
|marker: u8| -> Option<&[u8]> { (input.first() == Some(&marker)).then(|| &input[1..]) };
let n = match enc {
Enc::Stored => {
let r = raw(0xcc).ok_or_else(|| bad("stored chunk without its marker"))?;
let n = r.len().min(out.len());
out[..n].copy_from_slice(&r[..n]);
n
}
Enc::Zlib => {
if let Some(r) = raw(0xff) {
let n = r.len().min(out.len());
out[..n].copy_from_slice(&r[..n]);
n
} else {
use std::io::Read;
let mut d = flate2::read::ZlibDecoder::new(input);
let mut n = 0;
while n < out.len() {
let k = d
.read(&mut out[n..])
.map_err(|e| bad(&format!("zlib: {e}")))?;
if k == 0 {
break;
}
n += k;
}
n
}
}
Enc::Lzvn => {
if let Some(r) = raw(0x06) {
let n = r.len().min(out.len());
out[..n].copy_from_slice(&r[..n]);
n
} else {
ferrosys_lzfse::decompress_lzvn(input, out)
.map_err(|e| bad(&format!("LZVN: {e}")))?
}
}
Enc::Lzfse => {
ferrosys_lzfse::decompress_lzfse(input, out).map_err(|e| bad(&format!("LZFSE: {e}")))?
}
};
if n != out.len() {
return Err(bad(&format!(
"a chunk decoded to {n} bytes, {} expected",
out.len()
)));
}
Ok(())
}
/// The content of a compressed file, from its `com.apple.decmpfs` attribute and, for the types
/// that keep it there, its resource fork.
///
/// # Errors
///
/// The header is malformed, the type is not one this crate decodes, or a chunk does not decode
/// to its share of the content.
pub fn decode(attr: &[u8], fork: Option<&[u8]>) -> Result<Vec<u8>> {
let h = Header::parse(attr).ok_or_else(|| bad("no fpmc header"))?;
let enc = encoding(h.kind)?;
let size = usize::try_from(h.size).map_err(|_| bad("size"))?;
if !h.in_resource_fork() {
if size > CHUNK {
return Err(bad("an inline chunk of more than 64 KiB"));
}
let mut out = vec![0u8; size];
if size > 0 {
chunk(enc, &attr[HEADER_LEN..], &mut out)?;
}
return Ok(out);
}
let fork = fork.ok_or_else(|| bad("no resource fork"))?;
let chunks = size.div_ceil(CHUNK);
let ranges: Vec<(usize, usize)> = if h.kind == 4 {
// A classic resource fork: the data offset (big-endian) at 0; there a length, then the
// resource: a chunk count and (offset, length) pairs, little-endian, from its start.
let be = |o: usize| -> Result<usize> {
fork.get(o..o + 4)
.map(|b| u32::from_be_bytes(b.try_into().unwrap()) as usize)
.ok_or_else(|| bad("short resource fork"))
};
let le = |o: usize| -> Result<usize> {
fork.get(o..o + 4)
.map(|b| u32::from_le_bytes(b.try_into().unwrap()) as usize)
.ok_or_else(|| bad("short resource fork"))
};
let res = be(0)? + 4;
let n = le(res)?;
if n != chunks {
return Err(bad(&format!("{n} chunks for {size} bytes")));
}
(0..n)
.map(|i| Ok((res + le(res + 4 + i * 8)?, le(res + 8 + i * 8)?)))
.map(|r: Result<(usize, usize)>| r.map(|(o, l)| (o, o + l)))
.collect::<Result<_>>()?
} else {
let word = |i: usize| -> Result<usize> {
fork.get(i * 4..i * 4 + 4)
.map(|b| u32::from_le_bytes(b.try_into().unwrap()) as usize)
.ok_or_else(|| bad("short chunk table"))
};
(0..chunks)
.map(|i| Ok((word(i)?, word(i + 1)?)))
.collect::<Result<_>>()?
};
// Allocated once the fork is known to hold a range for every chunk, so a size no fork
// backs is refused before it is asked for.
let mut out = vec![0u8; size];
for (i, (s, e)) in ranges.into_iter().enumerate() {
let input = fork
.get(s..e)
.filter(|_| s <= e)
.ok_or_else(|| bad("a chunk outside the resource fork"))?;
let at = i * CHUNK;
chunk(enc, input, &mut out[at..(at + CHUNK).min(size)])?;
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
fn header(kind: u32, size: u64) -> Vec<u8> {
let mut h = MAGIC.to_vec();
h.extend_from_slice(&kind.to_le_bytes());
h.extend_from_slice(&size.to_le_bytes());
h
}
#[test]
fn stored_inline_and_in_the_fork_decode() {
let mut a = header(9, 5);
a.push(0xcc);
a.extend_from_slice(b"hello");
assert_eq!(decode(&a, None).unwrap(), b"hello");
// Two chunks in the fork, each stored.
let size = CHUNK + 3;
let c0: Vec<u8> = std::iter::once(0xcc)
.chain((0..CHUNK).map(|i| i as u8))
.collect();
let c1 = vec![0xcc, 7, 8, 9];
let table = 12u32;
let mut fork = Vec::new();
for o in [
table,
table + c0.len() as u32,
table + (c0.len() + c1.len()) as u32,
] {
fork.extend_from_slice(&o.to_le_bytes());
}
fork.extend_from_slice(&c0);
fork.extend_from_slice(&c1);
let out = decode(&header(10, size as u64), Some(&fork)).unwrap();
assert_eq!(out.len(), size);
assert_eq!(&out[CHUNK..], &[7, 8, 9]);
assert_eq!(out[1], 1);
}
#[test]
fn zlib_and_raw_lzvn_chunks_decode() {
use std::io::Write;
let content = b"the quick brown fox jumps over the lazy dog".repeat(20);
let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
z.write_all(&content).unwrap();
let mut a = header(3, content.len() as u64);
a.extend_from_slice(&z.finish().unwrap());
assert_eq!(decode(&a, None).unwrap(), content);
let mut b = header(7, 3);
b.extend_from_slice(&[0x06, 1, 2, 3]);
assert_eq!(decode(&b, None).unwrap(), [1, 2, 3]);
assert!(decode(&header(99, 1), None).is_err());
}
}
+161
View File
@@ -0,0 +1,161 @@
//! Where a container's bytes come from: a [`Source`] read at offsets (a file, or a disk image
//! decoded on the fly), and the [`Partition`] of it a container occupies.
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use std::os::unix::fs::FileExt;
use std::sync::Arc;
use crate::Result;
/// Bytes read at offsets, from any thread.
pub trait Source: Send + Sync {
/// Fill `buf` from `off`.
///
/// # Errors
///
/// The range is past the end, or the read fails.
fn read_at(&self, off: u64, buf: &mut [u8]) -> std::io::Result<()>;
/// The source's length in bytes.
fn len(&self) -> u64;
/// Whether the source is empty.
fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl Source for File {
fn read_at(&self, off: u64, buf: &mut [u8]) -> std::io::Result<()> {
self.read_exact_at(buf, off)
}
fn len(&self) -> u64 {
self.metadata().map_or(0, |m| m.len())
}
}
impl Source for Vec<u8> {
fn read_at(&self, off: u64, buf: &mut [u8]) -> std::io::Result<()> {
let s = usize::try_from(off)
.ok()
.filter(|s| s.checked_add(buf.len()).is_some_and(|e| e <= self.len()));
let s = s.ok_or_else(|| {
std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "read past the end")
})?;
buf.copy_from_slice(&self[s..s + buf.len()]);
Ok(())
}
fn len(&self) -> u64 {
self.len() as u64
}
}
/// `len` bytes of a source from `base`: a container's partition.
#[derive(Clone)]
pub struct Partition {
src: Arc<dyn Source>,
base: u64,
len: u64,
}
impl std::fmt::Debug for Partition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Partition")
.field("base", &self.base)
.field("len", &self.len)
.finish_non_exhaustive()
}
}
impl Partition {
#[must_use]
pub fn new(src: Arc<dyn Source>, base: u64, len: u64) -> Self {
Self { src, base, len }
}
/// The whole of `src`.
#[must_use]
pub fn whole(src: Arc<dyn Source>) -> Self {
let len = src.len();
Self::new(src, 0, len)
}
#[must_use]
pub const fn len(&self) -> u64 {
self.len
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.len == 0
}
#[must_use]
pub const fn base(&self) -> u64 {
self.base
}
/// Read `buf.len()` bytes at `off`, relative to the partition.
///
/// # Errors
///
/// The range is past the partition, or the read fails.
pub fn read_at(&self, off: u64, buf: &mut [u8]) -> Result<()> {
if off
.checked_add(buf.len() as u64)
.is_none_or(|end| end > self.len)
{
return Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
format!(
"bytes {off}..+{} are past the partition's {} bytes",
buf.len(),
self.len
),
)
.into());
}
self.src.read_at(self.base + off, buf)?;
Ok(())
}
}
/// A [`Source`] as `Read + Seek`, for readers that want a stream (the GPT's).
pub struct Cursor<'a> {
src: &'a dyn Source,
pos: u64,
}
impl<'a> Cursor<'a> {
#[must_use]
pub fn new(src: &'a dyn Source) -> Self {
Self { src, pos: 0 }
}
}
impl Read for Cursor<'_> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let n = (self.src.len().saturating_sub(self.pos)).min(buf.len() as u64) as usize;
self.src.read_at(self.pos, &mut buf[..n])?;
self.pos += n as u64;
Ok(n)
}
}
impl Seek for Cursor<'_> {
fn seek(&mut self, to: SeekFrom) -> std::io::Result<u64> {
let end = i128::from(self.src.len());
let at = match to {
SeekFrom::Start(x) => i128::from(x),
SeekFrom::End(x) => end + i128::from(x),
SeekFrom::Current(x) => i128::from(self.pos) + i128::from(x),
};
self.pos = u64::try_from(at).map_err(|_| {
std::io::Error::new(std::io::ErrorKind::InvalidInput, "seek before the start")
})?;
Ok(self.pos)
}
}
+415
View File
@@ -0,0 +1,415 @@
//! Files by path: opening a disk or container, resolving a path in a volume, and reading a
//! file's content, decoded where it is compressed.
use std::sync::Arc;
use crate::dev::{Partition, Source};
use crate::fs::{self, DirEntry, Inode, XattrData};
use crate::le::u64_at;
use crate::ondisk::{NX_MAGIC, apfs, ino, part, rec};
use crate::read::{Container, Volume};
use crate::{Error, Result, corrupt, decmpfs, gpt, names};
/// The attribute a symbolic link's target is held in.
const SYMLINK_XATTR: &[u8] = b"com.apple.fs.symlink";
/// The most symbolic links one path resolution follows.
const MAX_SYMLINKS: usize = 32;
const S_IFMT: u16 = 0o170_000;
const S_IFLNK: u16 = 0o120_000;
const S_IFREG: u16 = 0o100_000;
/// Open the APFS container in `src`: `src` itself where it starts with a container
/// superblock, or else the first APFS partition of its GUID partition table.
///
/// # Errors
///
/// `src` is neither a container nor a disk with an APFS partition, or the container fails its
/// checks.
pub fn open(src: Arc<dyn Source>) -> Result<Container> {
let mut head = [0u8; 36];
src.read_at(0, &mut head)?;
if u32::from_le_bytes(head[32..36].try_into().unwrap()) == NX_MAGIC {
return Container::open(Partition::whole(src));
}
let table = gpt::read(src.as_ref())
.map_err(|e| Error::Invalid(format!("neither an APFS container nor a GPT disk ({e})")))?;
let p = table
.partitions
.iter()
.find(|p| p.type_guid == part::APFS)
.ok_or_else(|| Error::Invalid("the disk's partition table has no APFS partition".into()))?;
let (base, len) = p.byte_range(table.sector_size);
if base.checked_add(len).is_none_or(|end| end > src.len()) {
return Err(Error::Gpt(format!(
"partition {} runs past the disk",
p.index
)));
}
Container::open(Partition::new(src, base, len))
}
/// A file-system object found by path: its inode number and inode.
#[derive(Clone, Debug)]
pub struct Entry {
pub id: u64,
pub inode: Inode,
}
impl Entry {
#[must_use]
pub const fn is_dir(&self) -> bool {
self.inode.is_dir()
}
#[must_use]
pub const fn is_file(&self) -> bool {
self.inode.mode & S_IFMT == S_IFREG
}
#[must_use]
pub const fn is_symlink(&self) -> bool {
self.inode.mode & S_IFMT == S_IFLNK
}
/// Whether the file's content is held compressed (`UF_COMPRESSED`).
#[must_use]
pub const fn is_compressed(&self) -> bool {
self.inode.bsd_flags & decmpfs::UF_COMPRESSED != 0
}
}
/// A run of a data stream's bytes on the container.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Extent {
/// Where in the stream the run starts.
pub logical: u64,
/// The run's length in bytes.
pub len: u64,
/// Where the run starts, in bytes from the start of the source the container was opened
/// on; `None` for a hole, which reads as zeros.
pub offset: Option<u64>,
}
impl Volume<'_> {
/// The object at `path`, following symbolic links. `path` is from the volume's root; `.`
/// and `..` are taken as they come, and names compare as the volume compares them.
///
/// # Errors
///
/// A component is missing or is not a directory, links loop, or a record fails its
/// checks.
pub fn lookup(&self, path: &str) -> Result<Entry> {
self.check_names()?;
let root = self.inode(ino::ROOT_DIR)?;
let mut dirs = vec![root.clone()];
let mut cur = root;
let mut todo: Vec<String> = path
.split('/')
.rev()
.filter(|c| !c.is_empty())
.map(str::to_owned)
.collect();
let mut links = 0;
while let Some(name) = todo.pop() {
if !cur.is_dir() {
return Err(Error::Invalid(format!(
"{path}: a component before {name:?} is not a directory"
)));
}
match name.as_str() {
"." => continue,
".." => {
if dirs.len() > 1 {
dirs.pop();
}
cur = dirs.last().unwrap().clone();
continue;
}
_ => {}
}
let id = self
.dir_lookup(cur.id, &name)?
.ok_or_else(|| Error::Invalid(format!("{path}: no {name:?} in its directory")))?;
let e = self.inode(id)?;
if e.is_symlink() {
links += 1;
if links > MAX_SYMLINKS {
return Err(Error::Invalid(format!(
"{path}: more than {MAX_SYMLINKS} symbolic links"
)));
}
let target = self
.xattr(&e, SYMLINK_XATTR)?
.ok_or_else(|| corrupt(0, format!("symbolic link {id} without its target")))?;
let target = target.strip_suffix(&[0]).unwrap_or(&target);
let target = std::str::from_utf8(target).map_err(|_| {
Error::Invalid(format!("{path}: a link target that is not UTF-8"))
})?;
if target.starts_with('/') {
dirs.truncate(1);
cur = dirs[0].clone();
}
todo.extend(
target
.split('/')
.rev()
.filter(|c| !c.is_empty())
.map(str::to_owned),
);
continue;
}
if e.is_dir() {
dirs.push(e.clone());
}
cur = e;
}
Ok(cur)
}
/// The content of the file at `path`, following symbolic links, decoded where it is
/// compressed.
///
/// # Errors
///
/// The path does not resolve to a regular file, its content is compressed in a way this
/// crate does not decode, or a record or block fails its checks.
pub fn read_file(&self, path: &str) -> Result<Vec<u8>> {
let e = self.lookup(path)?;
if !e.is_file() {
return Err(Error::Invalid(format!(
"{path} is not a regular file (mode {:o})",
e.inode.mode
)));
}
self.read(&e)
}
/// The content of regular file `e`, decoded where it is compressed.
///
/// # Errors
///
/// As [`read_file`](Self::read_file).
pub fn read(&self, e: &Entry) -> Result<Vec<u8>> {
if !e.is_compressed() {
let size = e.inode.dstream().map_or(0, |d| d.size);
return self.read_stream(e.inode.private_id, size);
}
let attr = self
.xattr(e, decmpfs::XATTR)?
.ok_or_else(|| corrupt(0, format!("compressed file {} without its header", e.id)))?;
let h = decmpfs::Header::parse(&attr)
.ok_or_else(|| corrupt(0, format!("compressed file {}: no fpmc header", e.id)))?;
let fork = if h.in_resource_fork() {
Some(self.xattr(e, decmpfs::RESOURCE_FORK)?.ok_or_else(|| {
corrupt(
0,
format!("compressed file {} without its resource fork", e.id),
)
})?)
} else {
None
};
decmpfs::decode(&attr, fork.as_deref())
}
/// The runs of `e`'s data stream on the container, in order; for an uncompressed file,
/// where its content is. Runs past the stream's size are cut to it.
///
/// # Errors
///
/// The extent records fail their checks.
pub fn extents(&self, e: &Entry) -> Result<Vec<Extent>> {
let size = e.inode.dstream().map_or(0, |d| d.size);
let (base, bs) = (self.c.base(), u64::from(self.c.block_size()));
Ok(self
.stream_extents(e.inode.private_id, size)?
.into_iter()
.map(|r| Extent {
logical: r.logical,
len: r.len,
offset: (r.phys != 0).then(|| base + r.phys * bs),
})
.collect())
}
/// Attribute `name` of `e`, read whole: held in its record, or in a data stream.
///
/// # Errors
///
/// The record or its stream fail their checks.
pub fn xattr(&self, e: &Entry, name: &[u8]) -> Result<Option<Vec<u8>>> {
let mut start = vec![0u8; 10];
start[..8].copy_from_slice(&fs::key_word(e.id, rec::XATTR).to_le_bytes());
let mut found = None;
self.fs_tree()?.scan(&start, &mut |k, v| {
if fs::key_header(k) != (e.id, rec::XATTR) {
return Ok(false);
}
if fs::xattr_name(k) == name {
found = Some(
fs::parse_xattr(v)
.ok_or_else(|| {
corrupt(0, format!("attribute of {} with a malformed value", e.id))
})?
.1,
);
return Ok(false);
}
Ok(true)
})?;
match found {
None => Ok(None),
Some(XattrData::Embedded(d)) => Ok(Some(d)),
Some(XattrData::Stream(id, d)) => self.read_stream(id, d.size).map(Some),
}
}
fn check_names(&self) -> Result<()> {
if self.sb.incompat
& (apfs::INCOMPAT_CASE_INSENSITIVE | apfs::INCOMPAT_NORMALIZATION_INSENSITIVE)
== 0
{
return Err(Error::Unsupported(
"a volume whose directory entries are not keyed by a hash of their names".into(),
));
}
if self.sb.fs_flags & apfs::FS_UNENCRYPTED == 0 {
return Err(Error::Unsupported("an encrypted volume".into()));
}
Ok(())
}
/// The inode numbered `id`.
fn inode(&self, id: u64) -> Result<Entry> {
let start = fs::key_word(id, rec::INODE).to_le_bytes();
let mut found = None;
self.fs_tree()?.scan(&start, &mut |k, v| {
if fs::key_header(k) == (id, rec::INODE) {
found = Some(
Inode::parse(v)
.ok_or_else(|| corrupt(0, format!("inode {id} with a short value")))?,
);
}
Ok(false)
})?;
let inode = found.ok_or_else(|| corrupt(0, format!("no inode {id}")))?;
Ok(Entry { id, inode })
}
/// The inode number directory `dir`'s entry `name` names.
fn dir_lookup(&self, dir: u64, name: &str) -> Result<Option<u64>> {
let fold = self.sb.case_insensitive();
let hash = names::hash(name.as_bytes(), fold);
let mut start = vec![0u8; 12];
start[..8].copy_from_slice(&fs::key_word(dir, rec::DIR_REC).to_le_bytes());
start[8..12].copy_from_slice(&(hash << 10).to_le_bytes());
let mut found = None;
self.fs_tree()?.scan(&start, &mut |k, v| {
if k.len() < 12 || fs::key_header(k) != (dir, rec::DIR_REC) || fs::drec_hash(k) != hash
{
return Ok(false);
}
if names::same(fs::drec_name(k), name.as_bytes(), fold) {
found = Some(
DirEntry::parse(v)
.ok_or_else(|| {
corrupt(0, format!("directory entry in {dir} with a short value"))
})?
.file_id,
);
return Ok(false);
}
Ok(true)
})?;
Ok(found)
}
/// The runs of data stream `id` of `size` bytes: from a sealed volume's file extent tree, or
/// else from the file-system tree's extent records.
fn stream_extents(&self, id: u64, size: u64) -> Result<Vec<Run>> {
let blocks = self.c.superblock().block_count;
let bs = u64::from(self.c.block_size());
let mut out: Vec<Run> = Vec::new();
let mut push = |logical: u64, len: u64, phys: u64| -> Result<bool> {
let end = out.last().map_or(0, |x| x.logical + x.len);
if logical < end {
return Err(corrupt(
phys,
format!("extent of stream {id} at {logical} overlaps the one before it"),
));
}
if logical >= size {
return Ok(false);
}
let len = len.min(size - logical);
if phys != 0
&& phys
.checked_add(len.div_ceil(bs))
.is_none_or(|e| e > blocks)
{
return Err(corrupt(
phys,
format!("extent of stream {id} runs past the container"),
));
}
out.push(Run { logical, len, phys });
Ok(true)
};
if let Some(t) = self.fext_tree()? {
let mut start = [0u8; 16];
start[..8].copy_from_slice(&id.to_le_bytes());
t.scan(&start, &mut |k, v| {
if u64_at(k, 0) != id {
return Ok(false);
}
if k.len() < 16 || v.len() < 16 {
return Err(corrupt(0, "short file extent tree record"));
}
let r = fs::FextRecord::parse(k, v);
push(r.logical, r.len, r.phys)
})?;
} else {
let mut start = [0u8; 16];
start[..8].copy_from_slice(&fs::key_word(id, rec::FILE_EXTENT).to_le_bytes());
self.fs_tree()?.scan(&start, &mut |k, v| {
if fs::key_header(k) != (id, rec::FILE_EXTENT) {
return Ok(false);
}
if k.len() < 16 || v.len() < 24 {
return Err(corrupt(0, "short file extent record"));
}
let r = fs::FileExtent::parse(k, v);
push(r.logical, r.len, r.phys)
})?;
}
Ok(out)
}
/// Data stream `id`'s `size` bytes; holes and anything past the last extent read as zeros.
fn read_stream(&self, id: u64, size: u64) -> Result<Vec<u8>> {
let extents = self.stream_extents(id, size)?;
let n = usize::try_from(size)
.map_err(|_| Error::Unsupported(format!("a stream of {size} bytes")))?;
let mut out = Vec::new();
out.try_reserve_exact(n)
.map_err(|_| Error::Unsupported(format!("a stream of {size} bytes")))?;
out.resize(n, 0);
for x in extents {
if x.phys != 0 {
let at = x.logical as usize;
self.c
.read_bytes(x.phys, 0, &mut out[at..at + x.len as usize])?;
}
}
Ok(out)
}
}
/// A run of a data stream: where in the stream, how many bytes, and its first block (0 for a
/// hole).
struct Run {
logical: u64,
len: u64,
phys: u64,
}
+71
View File
@@ -0,0 +1,71 @@
//! The Fletcher-64 checksum every APFS object header carries in its first eight bytes.
//!
//! The sum runs over the object's 32-bit little-endian words after the checksum field, modulo
//! 2^32 - 1, and the stored value is the pair of check words that make the whole object's sum
//! zero (Apple File System Reference, "Objects").
const MOD: u64 = 0xffff_ffff;
/// The checksum of `block`, whose first eight bytes are the checksum field and are skipped.
#[must_use]
pub fn checksum(block: &[u8]) -> u64 {
debug_assert!(block.len() % 4 == 0 && block.len() >= 8);
let (mut a, mut b) = (0u64, 0u64);
// 2^14 words (a 64 KiB block) keep both sums under 2^60 before the reduction.
for chunk in block[8..].chunks(1 << 16) {
for w in chunk.as_chunks::<4>().0 {
a += u64::from(u32::from_le_bytes(*w));
b += a;
}
a %= MOD;
b %= MOD;
}
let c1 = MOD - ((a + b) % MOD);
let c2 = MOD - ((a + c1) % MOD);
(c2 << 32) | c1
}
/// The checksum stored in `block`'s header.
#[must_use]
pub fn stored(block: &[u8]) -> u64 {
u64::from_le_bytes(block[..8].try_into().unwrap())
}
/// Whether `block`'s stored checksum is right.
#[must_use]
pub fn verify(block: &[u8]) -> bool {
stored(block) == checksum(block)
}
/// Write `block`'s checksum into its header.
pub fn seal(block: &mut [u8]) {
let c = checksum(block);
block[..8].copy_from_slice(&c.to_le_bytes());
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sealed_block_verifies_and_a_flipped_bit_does_not() {
let mut block = vec![0u8; 4096];
for (i, b) in block.iter_mut().enumerate() {
*b = (i * 7 + 3) as u8;
}
seal(&mut block);
assert!(verify(&block));
block[100] ^= 1;
assert!(!verify(&block));
}
#[test]
fn all_ones_words_reduce_to_zero_sums() {
// 0xffffffff is 0 modulo 2^32 - 1, so the sums are zero and both check words are the
// modulus itself.
let mut block = vec![0xffu8; 64];
seal(&mut block);
assert_eq!(stored(&block), 0xffff_ffff_ffff_ffff);
assert!(verify(&block));
}
}
+353
View File
@@ -0,0 +1,353 @@
//! File-system records: keys and values of a volume's file-system tree and of a sealed volume's
//! file extent tree (Apple File System Reference, "File-System Objects", "Sealed Volumes").
use std::cmp::Ordering;
use crate::le::{u16_at, u32_at, u64_at};
use crate::ondisk::rec;
// A key's fields, read as zero where the key is too short to hold them, so comparing a
// malformed key orders it rather than panics.
fn key_u16(k: &[u8], off: usize) -> u16 {
k.get(off..off + 2)
.map_or(0, |b| u16::from_le_bytes(b.try_into().unwrap()))
}
fn key_u32(k: &[u8], off: usize) -> u32 {
k.get(off..off + 4)
.map_or(0, |b| u32::from_le_bytes(b.try_into().unwrap()))
}
fn key_u64(k: &[u8], off: usize) -> u64 {
k.get(off..off + 8)
.map_or(0, |b| u64::from_le_bytes(b.try_into().unwrap()))
}
/// A record key's object identifier and type.
#[must_use]
pub fn key_header(key: &[u8]) -> (u64, u8) {
let w = key_u64(key, 0);
(w & rec::OBJ_ID_MASK, (w >> rec::TYPE_SHIFT) as u8)
}
/// A key's first word for `oid` and record type `t`.
#[must_use]
pub const fn key_word(oid: u64, t: u8) -> u64 {
(oid & rec::OBJ_ID_MASK) | ((t as u64) << rec::TYPE_SHIFT)
}
/// The order of two file-system tree keys: by identifier, then type, then what the type keys
/// by (a directory entry by hash then name, an attribute by name, a file extent by offset, a
/// sibling link by sibling, a file info by its address word, a snapshot name by name).
#[must_use]
pub fn compare_keys(a: &[u8], b: &[u8]) -> Ordering {
let (ia, ta) = key_header(a);
let (ib, tb) = key_header(b);
(ia, ta).cmp(&(ib, tb)).then_with(|| match ta {
rec::FILE_EXTENT | rec::SIBLING_LINK | rec::FILE_INFO => key_u64(a, 8).cmp(&key_u64(b, 8)),
rec::DIR_REC => {
let (ha, hb) = (drec_hash(a), drec_hash(b));
ha.cmp(&hb).then_with(|| drec_name(a).cmp(drec_name(b)))
}
rec::XATTR | rec::SNAP_NAME => name16(a).cmp(name16(b)),
_ => Ordering::Equal,
})
}
/// A name after a 16-bit length at byte 8 (an attribute's or a snapshot name's key), without its
/// terminating NUL.
fn name16(key: &[u8]) -> &[u8] {
let n = usize::from(key_u16(key, 8));
let name = key.get(10..(10 + n).min(key.len())).unwrap_or_default();
name.strip_suffix(&[0]).unwrap_or(name)
}
/// A hashed directory entry key's name, without its NUL.
#[must_use]
pub fn drec_name(key: &[u8]) -> &[u8] {
let n = (key_u32(key, 8) & 0x3ff) as usize;
let name = key.get(12..(12 + n).min(key.len())).unwrap_or_default();
name.strip_suffix(&[0]).unwrap_or(name)
}
/// A hashed directory entry key's 22-bit name hash.
#[must_use]
pub fn drec_hash(key: &[u8]) -> u32 {
key_u32(key, 8) >> 10
}
/// The order of two keys of the file extent tree, or of the object map: two 64-bit words.
#[must_use]
pub fn compare_u64_pairs(a: &[u8], b: &[u8]) -> Ordering {
(key_u64(a, 0), key_u64(a, 8)).cmp(&(key_u64(b, 0), key_u64(b, 8)))
}
/// An extended field of an inode or directory entry.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct XField {
pub kind: u8,
pub flags: u8,
pub data: Vec<u8>,
}
/// Parse an `xf_blob_t`.
#[must_use]
pub fn parse_xfields(b: &[u8]) -> Vec<XField> {
if b.len() < 4 {
return Vec::new();
}
let n = usize::from(u16_at(b, 0));
let mut out = Vec::with_capacity(n);
let mut data = 4 + n * 4;
for i in 0..n {
let h = 4 + i * 4;
if h + 4 > b.len() {
break;
}
let size = usize::from(u16_at(b, h + 2));
if data + size > b.len() {
break;
}
out.push(XField {
kind: b[h],
flags: b[h + 1],
data: b[data..data + size].to_vec(),
});
data += size.div_ceil(8) * 8;
}
out
}
pub mod xf {
pub const SNAP_XID: u8 = 1;
pub const DELTA_TREE_OID: u8 = 2;
pub const DOCUMENT_ID: u8 = 3;
pub const NAME: u8 = 4;
pub const PREV_FSIZE: u8 = 5;
pub const FINDER_INFO: u8 = 7;
pub const DSTREAM: u8 = 8;
pub const DIR_STATS_KEY: u8 = 10;
pub const FS_UUID: u8 = 11;
pub const SPARSE_BYTES: u8 = 13;
pub const RDEV: u8 = 14;
pub const PURGEABLE_FLAGS: u8 = 15;
pub const ORIG_SYNC_ROOT_ID: u8 = 16;
/// A directory entry's sibling identifier.
pub const DREC_SIBLING_ID: u8 = 1;
pub const FLAG_DATA_DEPENDENT: u8 = 0x1;
pub const FLAG_DO_NOT_COPY: u8 = 0x2;
pub const FLAG_CHILDREN_INHERIT: u8 = 0x8;
pub const FLAG_USER_FIELD: u8 = 0x10;
pub const FLAG_SYSTEM_FIELD: u8 = 0x20;
}
/// An inode record's value.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Inode {
pub parent_id: u64,
pub private_id: u64,
pub create_time: u64,
pub mod_time: u64,
pub change_time: u64,
pub access_time: u64,
pub internal_flags: u64,
/// Children of a directory, links of anything else.
pub nchildren_or_nlink: i32,
pub default_protection_class: u32,
pub write_generation_counter: u32,
pub bsd_flags: u32,
pub owner: u32,
pub group: u32,
pub mode: u16,
pub pad1: u16,
pub uncompressed_size: u64,
pub xfields: Vec<XField>,
}
/// The fixed part of `j_inode_val_t`.
pub const INODE_FIXED: usize = 92;
impl Inode {
#[must_use]
pub fn parse(v: &[u8]) -> Option<Self> {
if v.len() < INODE_FIXED {
return None;
}
Some(Self {
parent_id: u64_at(v, 0),
private_id: u64_at(v, 8),
create_time: u64_at(v, 16),
mod_time: u64_at(v, 24),
change_time: u64_at(v, 32),
access_time: u64_at(v, 40),
internal_flags: u64_at(v, 48),
nchildren_or_nlink: u32_at(v, 56) as i32,
default_protection_class: u32_at(v, 60),
write_generation_counter: u32_at(v, 64),
bsd_flags: u32_at(v, 68),
owner: u32_at(v, 72),
group: u32_at(v, 76),
mode: u16_at(v, 80),
pad1: u16_at(v, 82),
uncompressed_size: u64_at(v, 84),
xfields: parse_xfields(&v[INODE_FIXED..]),
})
}
/// The data stream extended field: size, allocated size, crypto, bytes written and read.
#[must_use]
pub fn dstream(&self) -> Option<Dstream> {
self.xfields
.iter()
.find(|x| x.kind == xf::DSTREAM)
.and_then(|x| Dstream::parse(&x.data))
}
/// The name extended field (a hard-linked inode's name), without its NUL.
#[must_use]
pub fn name(&self) -> Option<&[u8]> {
self.xfields
.iter()
.find(|x| x.kind == xf::NAME)
.map(|x| x.data.strip_suffix(&[0]).unwrap_or(&x.data))
}
#[must_use]
pub const fn is_dir(&self) -> bool {
self.mode & 0o170000 == 0o040000
}
}
/// `j_dstream_t`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub struct Dstream {
pub size: u64,
pub alloced_size: u64,
pub default_crypto_id: u64,
pub total_bytes_written: u64,
pub total_bytes_read: u64,
}
impl Dstream {
#[must_use]
pub fn parse(b: &[u8]) -> Option<Self> {
(b.len() >= 40).then(|| Self {
size: u64_at(b, 0),
alloced_size: u64_at(b, 8),
default_crypto_id: u64_at(b, 16),
total_bytes_written: u64_at(b, 24),
total_bytes_read: u64_at(b, 32),
})
}
}
/// A directory entry record's value.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DirEntry {
pub file_id: u64,
pub date_added: u64,
/// The low four bits are the entry's `DT_*` type.
pub flags: u16,
pub xfields: Vec<XField>,
}
impl DirEntry {
#[must_use]
pub fn parse(v: &[u8]) -> Option<Self> {
(v.len() >= 18).then(|| Self {
file_id: u64_at(v, 0),
date_added: u64_at(v, 8),
flags: u16_at(v, 16),
xfields: parse_xfields(&v[18..]),
})
}
}
/// An extended attribute record's value.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum XattrData {
Embedded(Vec<u8>),
/// A data stream's identifier and its `j_dstream_t`.
Stream(u64, Dstream),
}
pub const XATTR_DATA_STREAM: u16 = 0x1;
pub const XATTR_DATA_EMBEDDED: u16 = 0x2;
pub const XATTR_FILE_SYSTEM_OWNED: u16 = 0x4;
/// Parse an extended attribute value: its flags and data.
#[must_use]
pub fn parse_xattr(v: &[u8]) -> Option<(u16, XattrData)> {
if v.len() < 4 {
return None;
}
let flags = u16_at(v, 0);
let len = usize::from(u16_at(v, 2));
let data = v.get(4..4 + len)?;
if flags & XATTR_DATA_STREAM != 0 {
if data.len() < 48 {
return None;
}
Some((
flags,
XattrData::Stream(u64_at(data, 0), Dstream::parse(&data[8..])?),
))
} else {
Some((flags, XattrData::Embedded(data.to_vec())))
}
}
/// An attribute key's name, without its NUL.
#[must_use]
pub fn xattr_name(key: &[u8]) -> &[u8] {
name16(key)
}
/// A file extent record: its length in bytes, flags, first physical block and crypto id.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FileExtent {
pub logical: u64,
pub len: u64,
pub flags: u8,
pub phys: u64,
pub crypto_id: u64,
}
impl FileExtent {
#[must_use]
pub fn parse(key: &[u8], v: &[u8]) -> Self {
let lf = u64_at(v, 0);
Self {
logical: u64_at(key, 8),
len: lf & 0x00ff_ffff_ffff_ffff,
flags: (lf >> 56) as u8,
phys: u64_at(v, 8),
crypto_id: u64_at(v, 16),
}
}
}
/// A sealed volume's file extent tree record.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FextRecord {
pub private_id: u64,
pub logical: u64,
pub len: u64,
pub flags: u8,
pub phys: u64,
}
impl FextRecord {
#[must_use]
pub fn parse(key: &[u8], v: &[u8]) -> Self {
let lf = u64_at(v, 0);
Self {
private_id: u64_at(key, 0),
logical: u64_at(key, 8),
len: lf & 0x00ff_ffff_ffff_ffff,
flags: (lf >> 56) as u8,
phys: u64_at(v, 8),
}
}
}
+105
View File
@@ -0,0 +1,105 @@
//! A disk's GUID partition table, read through gptman, which checks its headers' and entry
//! array's CRC-32s.
//!
//! GUIDs here are in their usual string order; on disk, a GPT stores the first three groups
//! little-endian, which [`guid_from_disk`] converts.
use crate::dev::{Cursor, Source};
use crate::{Error, Result};
/// A partition, as the table records it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Partition {
/// The partition's slot, from 1.
pub index: u32,
pub type_guid: String,
pub unique_guid: String,
pub name: String,
pub first_lba: u64,
pub last_lba: u64,
}
impl Partition {
/// The partition's first byte and its length in bytes, for `sector_size`-byte sectors.
#[must_use]
pub const fn byte_range(&self, sector_size: u64) -> (u64, u64) {
(
self.first_lba * sector_size,
(self.last_lba + 1 - self.first_lba) * sector_size,
)
}
}
/// A read partition table.
#[derive(Clone, Debug)]
pub struct Table {
pub sector_size: u64,
pub disk_guid: String,
pub partitions: Vec<Partition>,
}
/// A GUID's usual string form, from its on-disk byte order.
#[must_use]
pub fn guid_from_disk(d: &[u8; 16]) -> String {
let mut b = *d;
b[0..4].reverse();
b[4..6].reverse();
b[6..8].reverse();
let h: Vec<String> = b.iter().map(|x| format!("{x:02X}")).collect();
format!(
"{}-{}-{}-{}-{}",
h[0..4].concat(),
h[4..6].concat(),
h[6..8].concat(),
h[8..10].concat(),
h[10..16].concat()
)
}
/// Read the partition table of `src`, trying 512- and then 4096-byte sectors.
///
/// # Errors
///
/// Neither sector size finds a valid table.
pub fn read(src: &dyn Source) -> Result<Table> {
let mut last = String::new();
for ss in [512u64, 4096] {
match gptman::GPT::read_from(&mut Cursor::new(src), ss) {
Ok(g) => {
let partitions = g
.iter()
.filter(|(_, p)| p.is_used())
.map(|(i, p)| Partition {
index: i,
type_guid: guid_from_disk(&p.partition_type_guid),
unique_guid: guid_from_disk(&p.unique_partition_guid),
name: p.partition_name.as_str().to_string(),
first_lba: p.starting_lba,
last_lba: p.ending_lba,
})
.collect();
return Ok(Table {
sector_size: ss,
disk_guid: guid_from_disk(&g.header.disk_guid),
partitions,
});
}
Err(e) => last = e.to_string(),
}
}
Err(Error::Gpt(last))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn guids_read_in_their_string_order() {
let d = [
0xef, 0x57, 0x34, 0x7c, 0, 0, 0xaa, 0x11, 0xaa, 0x11, 0x00, 0x30, 0x65, 0x43, 0xec,
0xac,
];
assert_eq!(guid_from_disk(&d), crate::ondisk::part::APFS);
}
}
+21
View File
@@ -0,0 +1,21 @@
//! Little-endian field access over byte slices.
#[inline]
pub(crate) fn u16_at(b: &[u8], off: usize) -> u16 {
u16::from_le_bytes(b[off..off + 2].try_into().unwrap())
}
#[inline]
pub(crate) fn u32_at(b: &[u8], off: usize) -> u32 {
u32::from_le_bytes(b[off..off + 4].try_into().unwrap())
}
#[inline]
pub(crate) fn u64_at(b: &[u8], off: usize) -> u64 {
u64::from_le_bytes(b[off..off + 8].try_into().unwrap())
}
#[inline]
pub(crate) fn uuid_at(b: &[u8], off: usize) -> [u8; 16] {
b[off..off + 16].try_into().unwrap()
}
+70
View File
@@ -0,0 +1,70 @@
//! Reading APFS: a container (bare, or the APFS partition of a GPT disk), its volumes, and a
//! file's content by path, compressed files decoded.
//!
//! reims-restore reads files out of an IPSW's system image with it, the image decoded by its own
//! readers into a [`dev::Source`]. A path is resolved by searching the volume's trees from their
//! roots, so a read touches only the nodes on its way. Everything read is checked: each object's
//! Fletcher-64 checksum, and its identifier, type and transaction against what led to it; each
//! node's keys ascend, and sit under its parent's key for it.
//!
//! ```no_run
//! # fn main() -> reims_apfs::Result<()> {
//! let image = std::sync::Arc::new(std::fs::File::open("os.raw")?);
//! let c = reims_apfs::open(image)?;
//! let v = c.system_volume()?;
//! let booter = v.read_file("/System/Library/Frameworks/Virtualization.framework/Resources/AVPBooter.vmapple2.bin")?;
//! # let _ = booter; Ok(()) }
//! ```
pub mod canon;
pub mod decmpfs;
pub mod dev;
pub mod file;
pub mod fletcher;
pub mod fs;
pub mod gpt;
pub mod names;
pub mod ondisk;
pub mod read;
pub mod seal;
pub mod write;
mod btree;
mod le;
pub use file::{Entry, Extent, open};
pub use read::{Container, NodeShape, SealFacts, Volume};
/// What goes wrong reading a disk.
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("{0}")]
Io(#[from] std::io::Error),
/// An object whose checksum does not match its bytes.
#[error("block {block}: checksum mismatch (stored {stored:#018x}, computed {computed:#018x})")]
Checksum {
block: u64,
stored: u64,
computed: u64,
},
/// A structure that breaks the format.
#[error("block {block}: {what}")]
Corrupt { block: u64, what: String },
/// Something the format allows that this crate does not handle.
#[error("unsupported: {0}")]
Unsupported(String),
/// A request that cannot be met: a path that is not there, a file of the wrong kind.
#[error("{0}")]
Invalid(String),
#[error("GPT: {0}")]
Gpt(String),
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
pub(crate) fn corrupt(block: u64, what: impl Into<String>) -> Error {
Error::Corrupt {
block,
what: what.into(),
}
}
+125
View File
@@ -0,0 +1,125 @@
//! The hash a directory entry is keyed by: 22 bits of a CRC-32C over the name's normalized code
//! points.
//!
//! A name is normalized to its canonical decomposition, canonically ordered; on a volume that
//! folds case, it is then case-folded (full folding, statuses C and F of Unicode's
//! `CaseFolding.txt`) and decomposed again. The hash is the CRC-32C of those code points as
//! little-endian 32-bit words, with no terminator, complemented, in its low 22 bits. These are
//! the rules ferrosys (MIT OR Apache-2.0) records as observed on volumes macOS 15, 26 and 27
//! wrote; the Apple File System Reference's description hashes the terminator, which macOS does
//! not. The tables are Unicode's, from ferrosys-ucd.
use ferrosys_ucd::{CASE_FOLDING, COMBINING_CLASS, DECOMPOSITION};
const CRC32C: crc::Crc<u32> = crc::Crc::<u32>::new(&crc::CRC_32_ISCSI);
/// The bits a directory entry's hash takes.
pub const HASH_MASK: u32 = 0x3f_ffff;
const S_BASE: u32 = 0xAC00;
const L_BASE: u32 = 0x1100;
const V_BASE: u32 = 0x1161;
const T_BASE: u32 = 0x11A7;
const T_COUNT: u32 = 28;
const N_COUNT: u32 = 21 * T_COUNT;
const S_COUNT: u32 = 19 * N_COUNT;
/// The normalized form of `name`, or `None` where it is not UTF-8.
#[must_use]
pub fn normalize(name: &[u8], fold: bool) -> Option<Vec<u32>> {
let text = std::str::from_utf8(name).ok()?;
let d = decompose(text.chars().map(u32::from));
if !fold {
return Some(d);
}
let folded = d.into_iter().flat_map(|cp| {
CASE_FOLDING
.binary_search_by_key(&cp, |(c, _)| *c)
.map_or_else(|_| vec![cp], |i| CASE_FOLDING[i].1.to_vec())
});
Some(decompose(folded))
}
/// The 22-bit hash a directory entry for `name` is keyed by, on a volume that folds case
/// (`fold`) or keeps it. A name that is not UTF-8 hashes its bytes as they are.
#[must_use]
pub fn hash(name: &[u8], fold: bool) -> u32 {
let bytes: Vec<u8> = match normalize(name, fold) {
Some(form) => form.iter().flat_map(|cp| cp.to_le_bytes()).collect(),
None => name.to_vec(),
};
!CRC32C.checksum(&bytes) & HASH_MASK
}
/// Whether two names are one name on a volume that folds case (`fold`) or keeps it.
#[must_use]
pub fn same(a: &[u8], b: &[u8], fold: bool) -> bool {
match (normalize(a, fold), normalize(b, fold)) {
(Some(x), Some(y)) => x == y,
_ => a == b,
}
}
fn decompose(code_points: impl Iterator<Item = u32>) -> Vec<u32> {
let mut out = Vec::new();
for cp in code_points {
if (S_BASE..S_BASE + S_COUNT).contains(&cp) {
let s = cp - S_BASE;
out.push(L_BASE + s / N_COUNT);
out.push(V_BASE + (s % N_COUNT) / T_COUNT);
if !s.is_multiple_of(T_COUNT) {
out.push(T_BASE + s % T_COUNT);
}
} else if let Ok(i) = DECOMPOSITION.binary_search_by_key(&cp, |(c, _)| *c) {
out.extend_from_slice(DECOMPOSITION[i].1);
} else {
out.push(cp);
}
}
// Canonical ordering: each run of nonzero combining classes, stably sorted by class.
let mut i = 0;
while i < out.len() {
if class(out[i]) == 0 {
i += 1;
continue;
}
let start = i;
while i < out.len() && class(out[i]) != 0 {
i += 1;
}
out[start..i].sort_by_key(|cp| class(*cp));
}
out
}
fn class(cp: u32) -> u8 {
COMBINING_CLASS
.binary_search_by_key(&cp, |(c, _)| *c)
.map_or(0, |i| COMBINING_CLASS[i].1)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn composed_and_decomposed_names_are_one_and_hash_alike() {
for fold in [false, true] {
assert!(same("caf\u{e9}".as_bytes(), "cafe\u{301}".as_bytes(), fold));
assert_eq!(
hash("caf\u{e9}".as_bytes(), fold),
hash("cafe\u{301}".as_bytes(), fold)
);
assert!(same(
"\u{d55c}".as_bytes(),
"\u{1112}\u{1161}\u{11ab}".as_bytes(),
fold
));
}
assert!(same(b"System", b"SYSTEM", true));
assert!(!same(b"System", b"SYSTEM", false));
assert_eq!(hash(b"Library", true), hash(b"LIBRARY", true));
assert_ne!(hash(b"Library", false), hash(b"LIBRARY", false));
assert!(hash(b"x", true) <= HASH_MASK);
}
}
+622
View File
@@ -0,0 +1,622 @@
//! APFS's on-disk constants and the offsets of the fields this crate reads, as the
//! Apple File System Reference (2020-06-22) defines them.
use crate::le::{u16_at, u32_at, u64_at, uuid_at};
/// The object header every non-headerless object starts with.
pub const OBJ_HEADER_SIZE: usize = 32;
pub mod obj {
pub const TYPE_MASK: u32 = 0x0000_ffff;
pub const VIRTUAL: u32 = 0;
pub const EPHEMERAL: u32 = 0x8000_0000;
pub const PHYSICAL: u32 = 0x4000_0000;
pub const NOHEADER: u32 = 0x2000_0000;
pub const ENCRYPTED: u32 = 0x1000_0000;
pub const NONPERSISTENT: u32 = 0x0800_0000;
pub const STORAGE_MASK: u32 = 0xc000_0000;
pub const NX_SUPERBLOCK: u32 = 0x01;
pub const BTREE: u32 = 0x02;
pub const BTREE_NODE: u32 = 0x03;
pub const SPACEMAN: u32 = 0x05;
pub const SPACEMAN_CAB: u32 = 0x06;
pub const SPACEMAN_CIB: u32 = 0x07;
pub const SPACEMAN_BITMAP: u32 = 0x08;
pub const SPACEMAN_FREE_QUEUE: u32 = 0x09;
pub const EXTENT_LIST_TREE: u32 = 0x0a;
pub const OMAP: u32 = 0x0b;
pub const CHECKPOINT_MAP: u32 = 0x0c;
pub const FS: u32 = 0x0d;
pub const FSTREE: u32 = 0x0e;
pub const BLOCKREFTREE: u32 = 0x0f;
pub const SNAPMETATREE: u32 = 0x10;
pub const NX_REAPER: u32 = 0x11;
pub const NX_REAP_LIST: u32 = 0x12;
pub const OMAP_SNAPSHOT: u32 = 0x13;
pub const EFI_JUMPSTART: u32 = 0x14;
pub const ER_STATE: u32 = 0x18;
pub const SNAP_META_EXT: u32 = 0x1d;
pub const INTEGRITY_META: u32 = 0x1e;
pub const FEXT_TREE: u32 = 0x1f;
/// 'keys', the container keybag.
pub const CONTAINER_KEYBAG: u32 = 0x7379_656b;
/// 'recs', a volume keybag.
pub const VOLUME_KEYBAG: u32 = 0x7363_6572;
/// 'mkey', the media keybag.
pub const MEDIA_KEYBAG: u32 = 0x7965_6b6d;
}
/// An object header.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ObjHeader {
pub cksum: u64,
pub oid: u64,
pub xid: u64,
pub type_and_flags: u32,
pub subtype: u32,
}
impl ObjHeader {
#[must_use]
pub fn parse(b: &[u8]) -> Self {
Self {
cksum: u64_at(b, 0),
oid: u64_at(b, 8),
xid: u64_at(b, 16),
type_and_flags: u32_at(b, 24),
subtype: u32_at(b, 28),
}
}
#[must_use]
pub const fn kind(&self) -> u32 {
self.type_and_flags & obj::TYPE_MASK
}
#[must_use]
pub const fn storage(&self) -> u32 {
self.type_and_flags & obj::STORAGE_MASK
}
}
pub const NX_MAGIC: u32 = 0x4253_584e;
pub const APFS_MAGIC: u32 = 0x4253_5041;
pub const NX_MAX_FILE_SYSTEMS: usize = 100;
pub const NX_NUM_COUNTERS: usize = 32;
/// Container superblock field offsets.
pub mod nx {
pub const MAGIC: usize = 32;
pub const BLOCK_SIZE: usize = 36;
pub const BLOCK_COUNT: usize = 40;
pub const FEATURES: usize = 48;
pub const RO_COMPAT: usize = 56;
pub const INCOMPAT: usize = 64;
pub const UUID: usize = 72;
pub const NEXT_OID: usize = 88;
pub const NEXT_XID: usize = 96;
pub const XP_DESC_BLOCKS: usize = 104;
pub const XP_DATA_BLOCKS: usize = 108;
pub const XP_DESC_BASE: usize = 112;
pub const XP_DATA_BASE: usize = 120;
pub const XP_DESC_NEXT: usize = 128;
pub const XP_DATA_NEXT: usize = 132;
pub const XP_DESC_INDEX: usize = 136;
pub const XP_DESC_LEN: usize = 140;
pub const XP_DATA_INDEX: usize = 144;
pub const XP_DATA_LEN: usize = 148;
pub const SPACEMAN_OID: usize = 152;
pub const OMAP_OID: usize = 160;
pub const REAPER_OID: usize = 168;
pub const TEST_TYPE: usize = 176;
pub const MAX_FILE_SYSTEMS: usize = 180;
pub const FS_OID: usize = 184;
pub const COUNTERS: usize = 984;
pub const BLOCKED_OUT: usize = 1240;
pub const EVICT_MAPPING_TREE_OID: usize = 1256;
pub const FLAGS: usize = 1264;
pub const EFI_JUMPSTART: usize = 1272;
pub const FUSION_UUID: usize = 1280;
pub const KEYLOCKER: usize = 1296;
pub const EPHEMERAL_INFO: usize = 1312;
pub const TEST_OID: usize = 1344;
pub const FUSION_MT_OID: usize = 1352;
pub const FUSION_WBC_OID: usize = 1360;
pub const FUSION_WBC: usize = 1368;
pub const NEWEST_MOUNTED_VERSION: usize = 1384;
pub const MKB_LOCKER: usize = 1392;
pub const END: usize = 1408;
pub const INCOMPAT_VERSION2: u64 = 0x2;
pub const INCOMPAT_FUSION: u64 = 0x100;
pub const FLAG_CRYPTO_SW: u64 = 0x4;
}
/// A container superblock, as the fields this crate uses.
#[derive(Clone, Debug)]
pub struct NxSuperblock {
pub hdr: ObjHeader,
pub block_size: u32,
pub block_count: u64,
pub features: u64,
pub ro_compat: u64,
pub incompat: u64,
pub uuid: [u8; 16],
pub next_oid: u64,
pub next_xid: u64,
pub xp_desc_blocks: u32,
pub xp_data_blocks: u32,
pub xp_desc_base: u64,
pub xp_data_base: u64,
pub xp_desc_next: u32,
pub xp_data_next: u32,
pub xp_desc_index: u32,
pub xp_desc_len: u32,
pub xp_data_index: u32,
pub xp_data_len: u32,
pub spaceman_oid: u64,
pub omap_oid: u64,
pub reaper_oid: u64,
pub max_file_systems: u32,
pub fs_oid: Vec<u64>,
pub flags: u64,
pub efi_jumpstart: u64,
pub keylocker: (u64, u64),
pub mkb_locker: (u64, u64),
pub ephemeral_info: [u64; 4],
pub newest_mounted_version: u64,
pub blocked_out: (u64, u64),
pub evict_mapping_tree_oid: u64,
}
impl NxSuperblock {
#[must_use]
pub fn parse(b: &[u8]) -> Self {
Self {
hdr: ObjHeader::parse(b),
block_size: u32_at(b, nx::BLOCK_SIZE),
block_count: u64_at(b, nx::BLOCK_COUNT),
features: u64_at(b, nx::FEATURES),
ro_compat: u64_at(b, nx::RO_COMPAT),
incompat: u64_at(b, nx::INCOMPAT),
uuid: uuid_at(b, nx::UUID),
next_oid: u64_at(b, nx::NEXT_OID),
next_xid: u64_at(b, nx::NEXT_XID),
xp_desc_blocks: u32_at(b, nx::XP_DESC_BLOCKS),
xp_data_blocks: u32_at(b, nx::XP_DATA_BLOCKS),
xp_desc_base: u64_at(b, nx::XP_DESC_BASE),
xp_data_base: u64_at(b, nx::XP_DATA_BASE),
xp_desc_next: u32_at(b, nx::XP_DESC_NEXT),
xp_data_next: u32_at(b, nx::XP_DATA_NEXT),
xp_desc_index: u32_at(b, nx::XP_DESC_INDEX),
xp_desc_len: u32_at(b, nx::XP_DESC_LEN),
xp_data_index: u32_at(b, nx::XP_DATA_INDEX),
xp_data_len: u32_at(b, nx::XP_DATA_LEN),
spaceman_oid: u64_at(b, nx::SPACEMAN_OID),
omap_oid: u64_at(b, nx::OMAP_OID),
reaper_oid: u64_at(b, nx::REAPER_OID),
max_file_systems: u32_at(b, nx::MAX_FILE_SYSTEMS),
fs_oid: (0..NX_MAX_FILE_SYSTEMS)
.map(|i| u64_at(b, nx::FS_OID + 8 * i))
.collect(),
flags: u64_at(b, nx::FLAGS),
efi_jumpstart: u64_at(b, nx::EFI_JUMPSTART),
keylocker: (u64_at(b, nx::KEYLOCKER), u64_at(b, nx::KEYLOCKER + 8)),
mkb_locker: (u64_at(b, nx::MKB_LOCKER), u64_at(b, nx::MKB_LOCKER + 8)),
ephemeral_info: std::array::from_fn(|i| u64_at(b, nx::EPHEMERAL_INFO + 8 * i)),
newest_mounted_version: u64_at(b, nx::NEWEST_MOUNTED_VERSION),
blocked_out: (u64_at(b, nx::BLOCKED_OUT), u64_at(b, nx::BLOCKED_OUT + 8)),
evict_mapping_tree_oid: u64_at(b, nx::EVICT_MAPPING_TREE_OID),
}
}
}
/// Volume superblock field offsets.
pub mod apfs {
pub const MAGIC: usize = 32;
pub const FS_INDEX: usize = 36;
pub const FEATURES: usize = 40;
pub const RO_COMPAT: usize = 48;
pub const INCOMPAT: usize = 56;
pub const UNMOUNT_TIME: usize = 64;
pub const RESERVE_BLOCK_COUNT: usize = 72;
pub const QUOTA_BLOCK_COUNT: usize = 80;
pub const ALLOC_COUNT: usize = 88;
pub const META_CRYPTO: usize = 96;
pub const ROOT_TREE_TYPE: usize = 116;
pub const EXTENTREF_TREE_TYPE: usize = 120;
pub const SNAP_META_TREE_TYPE: usize = 124;
pub const OMAP_OID: usize = 128;
pub const ROOT_TREE_OID: usize = 136;
pub const EXTENTREF_TREE_OID: usize = 144;
pub const SNAP_META_TREE_OID: usize = 152;
pub const REVERT_TO_XID: usize = 160;
pub const REVERT_TO_SBLOCK_OID: usize = 168;
pub const NEXT_OBJ_ID: usize = 176;
pub const NUM_FILES: usize = 184;
pub const NUM_DIRECTORIES: usize = 192;
pub const NUM_SYMLINKS: usize = 200;
pub const NUM_OTHER_FSOBJECTS: usize = 208;
pub const NUM_SNAPSHOTS: usize = 216;
pub const TOTAL_BLOCKS_ALLOCED: usize = 224;
pub const TOTAL_BLOCKS_FREED: usize = 232;
pub const VOL_UUID: usize = 240;
pub const LAST_MOD_TIME: usize = 256;
pub const FS_FLAGS: usize = 264;
pub const FORMATTED_BY: usize = 272;
pub const MODIFIED_BY: usize = 320;
/// The size of one `apfs_modified_by_t`.
pub const MODIFIED_BY_SIZE: usize = 48;
pub const VOLNAME: usize = 704;
pub const NEXT_DOC_ID: usize = 960;
pub const ROLE: usize = 964;
pub const ROOT_TO_XID: usize = 968;
pub const ER_STATE_OID: usize = 976;
pub const CLONEINFO_ID_EPOCH: usize = 984;
pub const CLONEINFO_XID: usize = 992;
pub const SNAP_META_EXT_OID: usize = 1000;
pub const VOLUME_GROUP_ID: usize = 1008;
pub const INTEGRITY_META_OID: usize = 1024;
pub const FEXT_TREE_OID: usize = 1032;
pub const FEXT_TREE_TYPE: usize = 1040;
pub const RESERVED_TYPE: usize = 1044;
pub const RESERVED_OID: usize = 1048;
/// The end of the fields the reference names.
pub const END: usize = 1056;
pub const FEATURE_DEFRAG: u64 = 0x4;
pub const FEATURE_HARDLINK_MAP_RECORDS: u64 = 0x2;
pub const FEATURE_STRICTATIME: u64 = 0x8;
pub const FEATURE_VOLGRP_SYSTEM_INO_SPACE: u64 = 0x10;
pub const INCOMPAT_CASE_INSENSITIVE: u64 = 0x1;
pub const INCOMPAT_DATALESS_SNAPS: u64 = 0x2;
pub const INCOMPAT_ENC_ROLLED: u64 = 0x4;
pub const INCOMPAT_NORMALIZATION_INSENSITIVE: u64 = 0x8;
pub const INCOMPAT_INCOMPLETE_RESTORE: u64 = 0x10;
pub const INCOMPAT_SEALED_VOLUME: u64 = 0x20;
pub const FS_UNENCRYPTED: u64 = 0x1;
pub const FS_ONEKEY: u64 = 0x8;
pub const ROLE_NONE: u16 = 0;
pub const ROLE_SYSTEM: u16 = 0x1;
pub const ROLE_USER: u16 = 0x2;
pub const ROLE_RECOVERY: u16 = 0x4;
pub const ROLE_VM: u16 = 0x8;
pub const ROLE_PREBOOT: u16 = 0x10;
pub const ROLE_INSTALLER: u16 = 0x20;
pub const ROLE_DATA: u16 = 0x40;
pub const ROLE_BASEBAND: u16 = 0x80;
pub const ROLE_UPDATE: u16 = 0xc0;
pub const ROLE_XART: u16 = 0x100;
pub const ROLE_HARDWARE: u16 = 0x140;
pub const ROLE_BACKUP: u16 = 0x180;
pub const ROLE_ENTERPRISE: u16 = 0x240;
pub const ROLE_PRELOGIN: u16 = 0x2c0;
}
/// A volume superblock, as the fields this crate uses. The raw block is kept so a rewrite keeps
/// every field this crate does not name.
#[derive(Clone, Debug)]
pub struct ApfsSuperblock {
pub hdr: ObjHeader,
pub raw: Vec<u8>,
pub fs_index: u32,
pub features: u64,
pub ro_compat: u64,
pub incompat: u64,
pub reserve_block_count: u64,
pub quota_block_count: u64,
pub alloc_count: u64,
pub root_tree_type: u32,
pub extentref_tree_type: u32,
pub snap_meta_tree_type: u32,
pub omap_oid: u64,
pub root_tree_oid: u64,
pub extentref_tree_oid: u64,
pub snap_meta_tree_oid: u64,
pub revert_to_xid: u64,
pub next_obj_id: u64,
pub num_files: u64,
pub num_directories: u64,
pub num_symlinks: u64,
pub num_other_fsobjects: u64,
pub num_snapshots: u64,
pub total_blocks_alloced: u64,
pub total_blocks_freed: u64,
pub uuid: [u8; 16],
pub last_mod_time: u64,
pub fs_flags: u64,
pub name: String,
pub next_doc_id: u32,
pub role: u16,
pub root_to_xid: u64,
pub er_state_oid: u64,
pub cloneinfo_id_epoch: u64,
pub cloneinfo_xid: u64,
pub snap_meta_ext_oid: u64,
pub volume_group_id: [u8; 16],
pub integrity_meta_oid: u64,
pub fext_tree_oid: u64,
pub fext_tree_type: u32,
}
impl ApfsSuperblock {
#[must_use]
pub fn parse(b: &[u8]) -> Self {
let name_bytes = &b[apfs::VOLNAME..apfs::VOLNAME + 256];
let end = name_bytes.iter().position(|c| *c == 0).unwrap_or(256);
Self {
hdr: ObjHeader::parse(b),
raw: b.to_vec(),
fs_index: u32_at(b, apfs::FS_INDEX),
features: u64_at(b, apfs::FEATURES),
ro_compat: u64_at(b, apfs::RO_COMPAT),
incompat: u64_at(b, apfs::INCOMPAT),
reserve_block_count: u64_at(b, apfs::RESERVE_BLOCK_COUNT),
quota_block_count: u64_at(b, apfs::QUOTA_BLOCK_COUNT),
alloc_count: u64_at(b, apfs::ALLOC_COUNT),
root_tree_type: u32_at(b, apfs::ROOT_TREE_TYPE),
extentref_tree_type: u32_at(b, apfs::EXTENTREF_TREE_TYPE),
snap_meta_tree_type: u32_at(b, apfs::SNAP_META_TREE_TYPE),
omap_oid: u64_at(b, apfs::OMAP_OID),
root_tree_oid: u64_at(b, apfs::ROOT_TREE_OID),
extentref_tree_oid: u64_at(b, apfs::EXTENTREF_TREE_OID),
snap_meta_tree_oid: u64_at(b, apfs::SNAP_META_TREE_OID),
revert_to_xid: u64_at(b, apfs::REVERT_TO_XID),
next_obj_id: u64_at(b, apfs::NEXT_OBJ_ID),
num_files: u64_at(b, apfs::NUM_FILES),
num_directories: u64_at(b, apfs::NUM_DIRECTORIES),
num_symlinks: u64_at(b, apfs::NUM_SYMLINKS),
num_other_fsobjects: u64_at(b, apfs::NUM_OTHER_FSOBJECTS),
num_snapshots: u64_at(b, apfs::NUM_SNAPSHOTS),
total_blocks_alloced: u64_at(b, apfs::TOTAL_BLOCKS_ALLOCED),
total_blocks_freed: u64_at(b, apfs::TOTAL_BLOCKS_FREED),
uuid: uuid_at(b, apfs::VOL_UUID),
last_mod_time: u64_at(b, apfs::LAST_MOD_TIME),
fs_flags: u64_at(b, apfs::FS_FLAGS),
name: String::from_utf8_lossy(&name_bytes[..end]).into_owned(),
next_doc_id: u32_at(b, apfs::NEXT_DOC_ID),
role: u16_at(b, apfs::ROLE),
root_to_xid: u64_at(b, apfs::ROOT_TO_XID),
er_state_oid: u64_at(b, apfs::ER_STATE_OID),
cloneinfo_id_epoch: u64_at(b, apfs::CLONEINFO_ID_EPOCH),
cloneinfo_xid: u64_at(b, apfs::CLONEINFO_XID),
snap_meta_ext_oid: u64_at(b, apfs::SNAP_META_EXT_OID),
volume_group_id: uuid_at(b, apfs::VOLUME_GROUP_ID),
integrity_meta_oid: u64_at(b, apfs::INTEGRITY_META_OID),
fext_tree_oid: u64_at(b, apfs::FEXT_TREE_OID),
fext_tree_type: u32_at(b, apfs::FEXT_TREE_TYPE),
}
}
#[must_use]
pub fn is_sealed(&self) -> bool {
self.incompat & apfs::INCOMPAT_SEALED_VOLUME != 0
}
#[must_use]
pub fn case_insensitive(&self) -> bool {
self.incompat & apfs::INCOMPAT_CASE_INSENSITIVE != 0
}
/// The `apfs_modified_by` entries that are set: who, when, and the last transaction.
#[must_use]
pub fn modified_by(&self) -> Vec<(String, u64, u64)> {
let mut v = Vec::new();
let one = |off: usize| {
let id = &self.raw[off..off + 32];
let end = id.iter().position(|c| *c == 0).unwrap_or(32);
(
String::from_utf8_lossy(&id[..end]).into_owned(),
u64_at(&self.raw, off + 32),
u64_at(&self.raw, off + 40),
)
};
v.push(one(apfs::FORMATTED_BY));
for i in 0..8 {
let e = one(apfs::MODIFIED_BY + i * apfs::MODIFIED_BY_SIZE);
if !e.0.is_empty() {
v.push(e);
}
}
v
}
}
/// Object map field offsets and flags.
pub mod omap {
pub const FLAGS: usize = 32;
pub const SNAP_COUNT: usize = 36;
pub const TREE_TYPE: usize = 40;
pub const SNAPSHOT_TREE_TYPE: usize = 44;
pub const TREE_OID: usize = 48;
pub const SNAPSHOT_TREE_OID: usize = 56;
pub const MOST_RECENT_SNAP: usize = 64;
pub const PENDING_REVERT_MIN: usize = 72;
pub const PENDING_REVERT_MAX: usize = 80;
pub const END: usize = 88;
pub const MANUALLY_MANAGED: u32 = 0x1;
pub const VAL_DELETED: u32 = 0x1;
pub const VAL_SAVED: u32 = 0x2;
pub const VAL_ENCRYPTED: u32 = 0x4;
pub const VAL_NOHEADER: u32 = 0x8;
}
/// An object map header.
#[derive(Clone, Copy, Debug)]
pub struct OmapPhys {
pub hdr: ObjHeader,
pub flags: u32,
pub snap_count: u32,
pub tree_type: u32,
pub snapshot_tree_type: u32,
pub tree_oid: u64,
pub snapshot_tree_oid: u64,
pub most_recent_snap: u64,
}
impl OmapPhys {
#[must_use]
pub fn parse(b: &[u8]) -> Self {
Self {
hdr: ObjHeader::parse(b),
flags: u32_at(b, omap::FLAGS),
snap_count: u32_at(b, omap::SNAP_COUNT),
tree_type: u32_at(b, omap::TREE_TYPE),
snapshot_tree_type: u32_at(b, omap::SNAPSHOT_TREE_TYPE),
tree_oid: u64_at(b, omap::TREE_OID),
snapshot_tree_oid: u64_at(b, omap::SNAPSHOT_TREE_OID),
most_recent_snap: u64_at(b, omap::MOST_RECENT_SNAP),
}
}
}
/// B-tree node flags, tree flags and layout.
pub mod btree {
pub const NODE_ROOT: u16 = 0x1;
pub const NODE_LEAF: u16 = 0x2;
pub const NODE_FIXED_KV_SIZE: u16 = 0x4;
pub const NODE_HASHED: u16 = 0x8;
pub const NODE_NOHEADER: u16 = 0x10;
pub const NODE_CHECK_KOFF_INVAL: u16 = 0x8000;
pub const UINT64_KEYS: u32 = 0x1;
pub const SEQUENTIAL_INSERT: u32 = 0x2;
pub const ALLOW_GHOSTS: u32 = 0x4;
pub const EPHEMERAL: u32 = 0x8;
pub const PHYSICAL: u32 = 0x10;
pub const NONPERSISTENT: u32 = 0x20;
pub const KV_NONALIGNED: u32 = 0x40;
pub const HASHED: u32 = 0x80;
pub const NOHEADER: u32 = 0x100;
/// Where a node's flags, level, key count and area locations sit.
pub const FLAGS: usize = 32;
pub const LEVEL: usize = 34;
pub const NKEYS: usize = 36;
pub const TABLE_SPACE: usize = 40;
pub const FREE_SPACE: usize = 44;
pub const KEY_FREE_LIST: usize = 48;
pub const VAL_FREE_LIST: usize = 52;
/// The start of a node's data, past its header.
pub const DATA: usize = 56;
/// The size of `btree_info_t`, at the end of a root node.
pub const INFO_SIZE: usize = 40;
/// An offset marking a value that is not there.
pub const OFF_INVALID: u16 = 0xffff;
}
/// The B-tree info at the end of a root node.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct BtreeInfo {
pub flags: u32,
pub node_size: u32,
pub key_size: u32,
pub val_size: u32,
pub longest_key: u32,
pub longest_val: u32,
pub key_count: u64,
pub node_count: u64,
}
impl BtreeInfo {
#[must_use]
pub fn parse(b: &[u8]) -> Self {
Self {
flags: u32_at(b, 0),
node_size: u32_at(b, 4),
key_size: u32_at(b, 8),
val_size: u32_at(b, 12),
longest_key: u32_at(b, 16),
longest_val: u32_at(b, 20),
key_count: u64_at(b, 24),
node_count: u64_at(b, 32),
}
}
}
/// Checkpoint map entries.
pub mod cpm {
pub const FLAGS: usize = 32;
pub const COUNT: usize = 36;
pub const MAP: usize = 40;
pub const ENTRY_SIZE: usize = 40;
pub const LAST: u32 = 0x1;
}
/// Integrity metadata (a sealed volume's) field offsets and values.
pub mod im {
pub const FLAGS: usize = 36;
pub const HASH_TYPE: usize = 40;
pub const ROOT_HASH_OFFSET: usize = 44;
pub const SEAL_BROKEN: u32 = 0x1;
pub const HASH_SHA256: u32 = 1;
}
/// File-system record types: the top four bits of a key's first word.
pub mod rec {
pub const SNAP_METADATA: u8 = 1;
pub const EXTENT: u8 = 2;
pub const INODE: u8 = 3;
pub const XATTR: u8 = 4;
pub const SIBLING_LINK: u8 = 5;
pub const DSTREAM_ID: u8 = 6;
pub const CRYPTO_STATE: u8 = 7;
pub const FILE_EXTENT: u8 = 8;
pub const DIR_REC: u8 = 9;
pub const DIR_STATS: u8 = 10;
pub const SNAP_NAME: u8 = 11;
pub const SIBLING_MAP: u8 = 12;
pub const FILE_INFO: u8 = 13;
pub const OBJ_ID_MASK: u64 = 0x0fff_ffff_ffff_ffff;
pub const TYPE_SHIFT: u32 = 60;
#[must_use]
pub const fn name(t: u8) -> &'static str {
match t {
SNAP_METADATA => "snap_metadata",
EXTENT => "phys_extent",
INODE => "inode",
XATTR => "xattr",
SIBLING_LINK => "sibling_link",
DSTREAM_ID => "dstream_id",
CRYPTO_STATE => "crypto_state",
FILE_EXTENT => "file_extent",
DIR_REC => "dir_rec",
DIR_STATS => "dir_stats",
SNAP_NAME => "snap_name",
SIBLING_MAP => "sibling_map",
FILE_INFO => "file_info",
_ => "unknown",
}
}
}
/// Well-known inode numbers.
pub mod ino {
pub const ROOT_DIR_PARENT: u64 = 1;
pub const ROOT_DIR: u64 = 2;
pub const PRIV_DIR: u64 = 3;
pub const SNAP_DIR: u64 = 6;
pub const PURGEABLE_DIR: u64 = 7;
pub const MIN_USER: u64 = 16;
/// The first inode number of a volume group's System volume.
pub const UNIFIED_ID_SPACE_MARK: u64 = 0x0800_0000_0000_0000;
pub const SYSTEM_INO_SPACE_BASE: u64 = 0x0fff_ffff_0000_0000;
}
/// Partition type GUIDs, in their usual string form.
pub mod part {
/// An APFS container (`Apple_APFS`).
pub const APFS: &str = "7C3457EF-0000-11AA-AA11-00306543ECAC";
/// The iBoot system container (`Apple_APFS_ISC`).
pub const APFS_ISC: &str = "69646961-6700-11AA-AA11-00306543ECAC";
/// The recoveryOS container (`Apple_APFS_Recovery`).
pub const APFS_RECOVERY: &str = "52637672-7900-11AA-AA11-00306543ECAC";
}
+975
View File
@@ -0,0 +1,975 @@
//! Reading a container: its newest checkpoint, its object maps, its volumes, and B-trees
//! searched from the root down.
//!
//! Every object read is checked: its Fletcher-64 checksum, and its identifier, type, subtype
//! and transaction against what led to it. Every node a search passes through also has its keys
//! checked to ascend strictly, its level to be one below its parent's, and its first key to be
//! no lower than its parent's key for it.
use std::cmp::Ordering;
use crate::btree::Node;
use crate::dev::Partition;
use crate::fs;
use crate::le::{u16_at, u32_at, u64_at};
use sha2::{Digest, Sha256};
use crate::ondisk::{
ApfsSuperblock, BtreeInfo, NX_MAGIC, NxSuperblock, ObjHeader, OmapPhys, apfs, btree, cpm, im,
obj, omap,
};
use crate::{Error, Result, corrupt, fletcher};
/// An object map entry's value: its flags, size and block address.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OmapVal {
pub flags: u32,
pub size: u32,
pub paddr: u64,
}
/// An object map: the root of its tree from (identifier, transaction) to [`OmapVal`].
#[derive(Clone, Copy, Debug)]
pub(crate) struct Omap {
tree: u64,
/// The transaction the map was read at; no node of its tree is newer.
xid: u64,
}
/// How a tree's child identifiers find their nodes.
#[derive(Clone, Copy)]
pub(crate) enum Addressing<'a> {
/// Identifiers are block addresses.
Physical,
/// Identifiers map through an object map, as of a transaction.
Virtual(&'a Omap, u64),
}
/// A key comparator.
pub(crate) type KeyOrder = fn(&[u8], &[u8]) -> Ordering;
/// A visitor of leaf records, by key and value, which returns whether to go on.
pub(crate) type Visit<'f> = dyn FnMut(&[u8], &[u8]) -> Result<bool> + 'f;
/// A leaf record's key and value.
pub(crate) type Record = (Vec<u8>, Vec<u8>);
/// An opened container, at its newest valid checkpoint.
pub struct Container {
dev: Partition,
block_size: u32,
/// The newest valid checkpoint's superblock.
nx: NxSuperblock,
omap: Omap,
}
impl std::fmt::Debug for Container {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Container")
.field("dev", &self.dev)
.field("block_size", &self.block_size)
.field("xid", &self.xid())
.finish_non_exhaustive()
}
}
impl Container {
/// Open the container on `dev`, at the newest checkpoint whose superblock and maps check.
///
/// # Errors
///
/// Block 0 is not a container superblock, no checkpoint is valid, or the container is of a
/// kind this crate does not read (Fusion, a checkpoint area in pieces).
pub fn open(dev: Partition) -> Result<Self> {
let mut head = vec![0u8; 4096];
dev.read_at(0, &mut head)?;
if u32_at(&head, 32) != NX_MAGIC {
return Err(corrupt(0, "not an APFS container (no NXSB magic)"));
}
let block_size = u32_at(&head, 36);
if !(4096..=65536).contains(&block_size) || !block_size.is_power_of_two() {
return Err(corrupt(0, format!("block size {block_size}")));
}
let mut b0 = vec![0u8; block_size as usize];
dev.read_at(0, &mut b0)?;
check_object(&b0, 0, None, Some(obj::NX_SUPERBLOCK), u64::MAX)?;
let nx0 = NxSuperblock::parse(&b0);
if nx0.incompat & crate::ondisk::nx::INCOMPAT_FUSION != 0 {
return Err(Error::Unsupported("a Fusion container".into()));
}
if nx0.xp_desc_blocks & 0x8000_0000 != 0 {
return Err(Error::Unsupported(
"a checkpoint descriptor area that is not contiguous".into(),
));
}
if nx0
.block_count
.checked_mul(u64::from(block_size))
.is_none_or(|b| b > dev.len())
{
return Err(corrupt(
0,
format!(
"{} blocks do not fit the partition's {} bytes",
nx0.block_count,
dev.len()
),
));
}
let mut c = Self {
dev,
block_size,
nx: nx0.clone(),
omap: Omap { tree: 0, xid: 0 },
};
// The checkpoints in the descriptor area, newest first: the first whose superblock and
// maps all check is the container's state.
let (base, n) = (nx0.xp_desc_base, u64::from(nx0.xp_desc_blocks));
let mut supers = Vec::new();
for i in 0..n {
let b = c.read_block(base + i)?;
if ObjHeader::parse(&b).kind() == obj::NX_SUPERBLOCK
&& u32_at(&b, 32) == NX_MAGIC
&& fletcher::verify(&b)
{
supers.push((ObjHeader::parse(&b).xid, base + i, b));
}
}
supers.sort_by_key(|s| std::cmp::Reverse(s.0));
let mut last_err = corrupt(base, "no valid checkpoint superblock");
for (xid, pa, b) in supers {
let nx = NxSuperblock::parse(&b);
match c.check_maps(&nx, pa, xid) {
Ok(()) => {
c.nx = nx;
c.omap = c.load_omap(c.nx.omap_oid, xid)?;
return Ok(c);
}
Err(e) => last_err = e,
}
}
Err(last_err)
}
/// Check the checkpoint maps of the checkpoint whose superblock `nx` is at `pa`.
fn check_maps(&self, nx: &NxSuperblock, pa: u64, xid: u64) -> Result<()> {
let (base, n) = (nx.xp_desc_base, u64::from(nx.xp_desc_blocks));
if nx.xp_desc_len == 0 || u64::from(nx.xp_desc_len) > n {
return Err(corrupt(
pa,
format!(
"checkpoint of {} blocks in a {n}-block area",
nx.xp_desc_len
),
));
}
for k in 0..u64::from(nx.xp_desc_len) {
let at = base + (u64::from(nx.xp_desc_index) + k) % n;
if at == pa {
continue;
}
let m = self.read_object(at, None, Some(obj::CHECKPOINT_MAP), xid)?;
if ObjHeader::parse(&m).xid != xid {
return Err(corrupt(at, "checkpoint map from another transaction"));
}
if u32_at(&m, cpm::COUNT) as usize > (m.len() - cpm::MAP) / cpm::ENTRY_SIZE {
return Err(corrupt(
at,
"checkpoint map with more entries than fit its block",
));
}
}
Ok(())
}
/// The size of every block.
#[must_use]
pub const fn block_size(&self) -> u32 {
self.block_size
}
/// The newest checkpoint's transaction.
#[must_use]
pub const fn xid(&self) -> u64 {
self.nx.hdr.xid
}
/// Where the container starts in the source it was opened on, in bytes.
#[must_use]
pub const fn base(&self) -> u64 {
self.dev.base()
}
/// The newest checkpoint's superblock.
#[must_use]
pub const fn superblock(&self) -> &NxSuperblock {
&self.nx
}
/// Read block `paddr`.
pub(crate) fn read_block(&self, paddr: u64) -> Result<Vec<u8>> {
let mut b = vec![0u8; self.block_size as usize];
self.read_bytes(paddr, 0, &mut b)?;
Ok(b)
}
/// Read `buf.len()` bytes from `off` bytes into block `paddr`, all of them inside the
/// container.
pub(crate) fn read_bytes(&self, paddr: u64, off: u64, buf: &mut [u8]) -> Result<()> {
let bs = u64::from(self.block_size);
let start = paddr.checked_mul(bs).and_then(|s| s.checked_add(off));
let end = start.and_then(|s| s.checked_add(buf.len() as u64));
match (start, end) {
(Some(s), Some(e)) if e <= self.nx.block_count * bs => self.dev.read_at(s, buf),
_ => Err(corrupt(
paddr,
format!("a read past the container's {} blocks", self.nx.block_count),
)),
}
}
/// Read the object at `paddr`, checking its checksum, its identifier (`oid`, where known),
/// its type (`kind`, where given) and that it is no newer than `max_xid`.
pub(crate) fn read_object(
&self,
paddr: u64,
oid: Option<u64>,
kind: Option<u32>,
max_xid: u64,
) -> Result<Vec<u8>> {
let b = self.read_block(paddr)?;
check_object(&b, paddr, oid, kind, max_xid)?;
Ok(b)
}
/// The object map whose header is at `paddr`.
fn load_omap(&self, paddr: u64, max_xid: u64) -> Result<Omap> {
let b = self.read_object(paddr, Some(paddr), Some(obj::OMAP), max_xid)?;
let phys = OmapPhys::parse(&b);
if phys.tree_type & obj::STORAGE_MASK != obj::PHYSICAL {
return Err(corrupt(
paddr,
format!("object map tree of type {:#x}", phys.tree_type),
));
}
Ok(Omap {
tree: phys.tree_oid,
xid: max_xid,
})
}
/// The newest mapping of `oid` in `m` at or before `xid`.
pub(crate) fn omap_lookup(
&self,
m: &Omap,
oid: u64,
xid: u64,
) -> Result<Option<(u64, OmapVal)>> {
if m.tree == 0 {
return Ok(None);
}
let mut key = [0u8; 16];
key[..8].copy_from_slice(&oid.to_le_bytes());
key[8..].copy_from_slice(&xid.to_le_bytes());
let t = Tree {
c: self,
root: m.tree,
addressing: Addressing::Physical,
subtype: obj::OMAP,
max_xid: m.xid,
order: fs::compare_u64_pairs,
root_hash: None,
};
let Some((k, v)) = t.last_le(&key)? else {
return Ok(None);
};
if u64_at(&k, 0) != oid {
return Ok(None);
}
if v.len() < 16 {
return Err(corrupt(m.tree, "short object map value"));
}
Ok(Some((
u64_at(&k, 8),
OmapVal {
flags: u32_at(&v, 0),
size: u32_at(&v, 4),
paddr: u64_at(&v, 8),
},
)))
}
/// The volume in slot `index`, as of the newest checkpoint.
///
/// # Errors
///
/// The slot is empty, or the volume's superblock or object map fail their checks.
pub fn volume(&self, index: usize) -> Result<Volume<'_>> {
let oid = *self
.nx
.fs_oid
.get(index)
.filter(|o| **o != 0)
.ok_or_else(|| Error::Invalid(format!("volume slot {index} is empty")))?;
let (vxid, v) = self
.omap_lookup(&self.omap, oid, self.xid())?
.ok_or_else(|| {
corrupt(
0,
format!("volume {oid} is not in the container's object map"),
)
})?;
if v.flags & omap::VAL_DELETED != 0 {
return Err(corrupt(v.paddr, format!("volume {oid} is deleted")));
}
let b = self.read_object(v.paddr, Some(oid), Some(obj::FS), vxid)?;
if u64_at(&b, 16) != vxid {
return Err(corrupt(
v.paddr,
"volume superblock's xid differs from its object map entry",
));
}
if u32_at(&b, apfs::MAGIC) != crate::ondisk::APFS_MAGIC {
return Err(corrupt(v.paddr, "volume superblock without APSB magic"));
}
let sb = ApfsSuperblock::parse(&b);
let omap = self.load_omap(sb.omap_oid, self.xid())?;
let root_hash = if sb.is_sealed() {
self.seal(&sb, &omap)?
} else {
None
};
Ok(Volume {
c: self,
index,
oid,
sb,
omap,
root_hash,
})
}
/// A sealed volume's root hash, the SHA-256 of its file-system tree's root node, from its
/// integrity metadata; `None` where the seal is broken.
fn seal(&self, sb: &ApfsSuperblock, omap: &Omap) -> Result<Option<Vec<u8>>> {
let oid = sb.integrity_meta_oid;
let (xid, v) = self.omap_lookup(omap, oid, self.xid())?.ok_or_else(|| {
corrupt(
0,
format!("sealed volume {:?} without its integrity metadata", sb.name),
)
})?;
let b = self.read_object(v.paddr, Some(oid), Some(obj::INTEGRITY_META), xid)?;
if u32_at(&b, im::FLAGS) & im::SEAL_BROKEN != 0 {
return Ok(None);
}
let kind = u32_at(&b, im::HASH_TYPE);
if kind != im::HASH_SHA256 {
return Err(Error::Unsupported(format!("a seal of hash type {kind}")));
}
let off = u32_at(&b, im::ROOT_HASH_OFFSET) as usize;
let hash = b
.get(off..off + HASH_LEN)
.ok_or_else(|| corrupt(v.paddr, "root hash past the block"))?;
Ok(Some(hash.to_vec()))
}
/// Every volume in the container, in slot order.
///
/// # Errors
///
/// A volume's superblock or object map fail their checks.
pub fn volumes(&self) -> Result<Vec<Volume<'_>>> {
let slots = (self.nx.max_file_systems as usize).min(self.nx.fs_oid.len());
(0..slots)
.filter(|i| self.nx.fs_oid[*i] != 0)
.map(|i| self.volume(i))
.collect()
}
/// The volume holding the operating system: the one whose role is System, or else the
/// container's only volume.
///
/// # Errors
///
/// No volume has that role and the container holds more than one, or a volume fails its
/// checks.
pub fn system_volume(&self) -> Result<Volume<'_>> {
let mut vols = self.volumes()?;
if let Some(i) = vols.iter().position(|v| v.sb.role == apfs::ROLE_SYSTEM) {
return Ok(vols.swap_remove(i));
}
match vols.len() {
1 => Ok(vols.remove(0)),
n => Err(Error::Invalid(format!(
"no volume has the System role among the container's {n}"
))),
}
}
}
/// Check an object's checksum, identifier, type and transaction.
pub(crate) fn check_object(
b: &[u8],
paddr: u64,
oid: Option<u64>,
kind: Option<u32>,
max_xid: u64,
) -> Result<()> {
if !fletcher::verify(b) {
return Err(Error::Checksum {
block: paddr,
stored: fletcher::stored(b),
computed: fletcher::checksum(b),
});
}
let h = ObjHeader::parse(b);
if let Some(o) = oid
&& h.oid != o
{
return Err(corrupt(
paddr,
format!("object {} where {o} was expected", h.oid),
));
}
if let Some(k) = kind
&& h.kind() != k
{
return Err(corrupt(
paddr,
format!("object of type {:#x} where {k:#x} was expected", h.kind()),
));
}
if h.xid > max_xid {
return Err(corrupt(
paddr,
format!("object from xid {} is newer than {max_xid}", h.xid),
));
}
Ok(())
}
/// A volume of a container.
pub struct Volume<'c> {
pub(crate) c: &'c Container,
/// The volume's slot in the container.
pub index: usize,
/// The volume's virtual identifier.
pub oid: u64,
/// The volume's superblock.
pub sb: ApfsSuperblock,
omap: Omap,
/// A sealed volume's root hash.
root_hash: Option<Vec<u8>>,
}
impl std::fmt::Debug for Volume<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Volume")
.field("index", &self.index)
.field("name", &self.sb.name)
.field("role", &self.sb.role)
.finish_non_exhaustive()
}
}
impl<'c> Volume<'c> {
/// The volume's name.
#[must_use]
pub fn name(&self) -> &str {
&self.sb.name
}
/// The volume's role (`APFS_VOL_ROLE_*`, [`apfs::ROLE_SYSTEM`] among them).
#[must_use]
pub const fn role(&self) -> u16 {
self.sb.role
}
/// The container the volume is in.
#[must_use]
pub const fn container(&self) -> &'c Container {
self.c
}
/// A sealed volume's root hash: the SHA-256 the integrity metadata records for its
/// file-system tree's root node. `None` on an unsealed volume or one whose seal is broken.
#[must_use]
pub fn root_hash(&self) -> Option<&[u8]> {
self.root_hash.as_deref()
}
/// The shape of every node of the file-system tree, parents before children, in key order:
/// for studying how a sealed volume's hashed tree is packed, so a writer can reproduce it.
///
/// # Errors
///
/// The tree fails its checks.
pub fn fs_tree_shape(&self) -> Result<Vec<NodeShape>> {
let mut out = Vec::new();
self.fs_tree()?.walk_nodes(&mut |s| {
out.push(s.clone());
Ok(())
})?;
Ok(out)
}
/// Every leaf record of the file-system tree, in key order, as (key, value): what a seal is
/// built from (`canon`, `seal`). It holds them all in memory, about 300 MB for a 27.2.1
/// system volume's 1.76 million records.
pub fn fs_tree_records(&self) -> Result<Vec<(Vec<u8>, Vec<u8>)>> {
let mut out = Vec::new();
self.fs_tree()?.scan(&[0u8; 8], &mut |k, v| {
out.push((k.to_vec(), v.to_vec()));
Ok(true)
})?;
Ok(out)
}
/// Read-only facts about a sealed volume's seal, for showing a written volume reproduces it:
/// the root hash, how many of each file-system record type the hashed tree holds (type `t`
/// is [`crate::ondisk::rec::name`]`(t)`), and the physical file-extent tree that carries the
/// block addresses the seal does not cover.
///
/// # Errors
///
/// A tree fails its checks.
pub fn seal_facts(&self) -> Result<SealFacts> {
let mut fs_record_types: std::collections::BTreeMap<u8, u64> =
std::collections::BTreeMap::new();
self.fs_tree()?.scan(&[0u8; 8], &mut |k, _| {
*fs_record_types.entry(fs::key_header(k).1).or_default() += 1;
Ok(true)
})?;
let mut facts = SealFacts {
root_hash: self.root_hash.clone(),
fs_record_types,
fext_records: 0,
fext_root_paddr: 0,
fext_root_has_object_header: false,
};
if let Some(t) = self.fext_tree()? {
t.scan(&[0u8; 16], &mut |_, _| {
facts.fext_records += 1;
Ok(true)
})?;
let paddr = t.root_block()?;
let b = self.c.read_block(paddr)?;
facts.fext_root_paddr = paddr;
// A tree outside the seal carries an ordinary object header, Fletcher-checked; a
// hashed (sealed) tree's nodes are headerless, their first 32 bytes zero.
facts.fext_root_has_object_header =
b[..32].iter().any(|x| *x != 0) && fletcher::verify(&b);
}
Ok(facts)
}
fn addressing(&self, tree_type: u32) -> Result<Addressing<'_>> {
match tree_type & obj::STORAGE_MASK {
obj::PHYSICAL => Ok(Addressing::Physical),
obj::VIRTUAL => Ok(Addressing::Virtual(&self.omap, self.c.xid())),
_ => Err(Error::Unsupported(format!(
"a volume tree of type {tree_type:#x}"
))),
}
}
/// The volume's file-system tree.
pub(crate) fn fs_tree(&self) -> Result<Tree<'_>> {
Ok(Tree {
c: self.c,
root: self.sb.root_tree_oid,
addressing: self.addressing(self.sb.root_tree_type)?,
subtype: obj::FSTREE,
max_xid: self.c.xid(),
order: fs::compare_keys,
root_hash: self.root_hash.as_deref(),
})
}
/// A sealed volume's file extent tree, which holds its files' extents in place of the
/// file-system tree.
pub(crate) fn fext_tree(&self) -> Result<Option<Tree<'_>>> {
if self.sb.fext_tree_oid == 0 {
return Ok(None);
}
Ok(Some(Tree {
c: self.c,
root: self.sb.fext_tree_oid,
addressing: self.addressing(self.sb.fext_tree_type)?,
subtype: obj::FEXT_TREE,
max_xid: self.c.xid(),
order: fs::compare_u64_pairs,
root_hash: None,
}))
}
}
/// What a sealed volume's seal covers and what it does not ([`Volume::seal_facts`]).
#[derive(Clone, Debug, Default)]
pub struct SealFacts {
/// The signed root hash: SHA-256 of the file-system tree's root node.
pub root_hash: Option<Vec<u8>>,
/// How many of each file-system record type the hashed tree holds. A sealed volume's holds
/// no file-extent records (type [`crate::ondisk::rec::FILE_EXTENT`]); its files' extents are
/// in the file-extent tree instead.
pub fs_record_types: std::collections::BTreeMap<u8, u64>,
/// How many physical extents the file-extent tree holds.
pub fext_records: u64,
/// The block address of the file-extent tree's root.
pub fext_root_paddr: u64,
/// Whether that root is an ordinary object (an object header, Fletcher-checked), which means
/// the file-extent tree is outside the seal and its block addresses may be rewritten.
pub fext_root_has_object_header: bool,
}
/// One node's shape, for studying how a tree is packed ([`Volume::fs_tree_shape`]).
#[derive(Clone, Debug)]
pub struct NodeShape {
/// The node's level: 0 for a leaf, higher toward the root.
pub level: u16,
/// How many entries the node holds.
pub nkeys: u32,
/// Whether this is the root node (its value area ends 40 bytes early, holding the tree info).
pub is_root: bool,
/// The node's unused bytes (`btn_free_space.len`).
pub free_space: u16,
/// The node's first key.
pub first_key: Vec<u8>,
/// The node's second key, for telling whether an index node repeats its first child's key as
/// a low fence.
pub second_key: Vec<u8>,
/// The node's last key.
pub last_key: Vec<u8>,
}
/// A B-tree, searched from its root.
pub(crate) struct Tree<'a> {
c: &'a Container,
root: u64,
addressing: Addressing<'a>,
subtype: u32,
max_xid: u64,
order: KeyOrder,
/// The SHA-256 the root node must have: a sealed volume's file-system tree's.
root_hash: Option<&'a [u8]>,
}
/// The size of a seal's hashes: SHA-256's.
const HASH_LEN: usize = 32;
/// The deepest a B-tree may be. A node's level is a 16-bit field an attacker controls, and
/// [`Tree::child`] holds every child's level to be one below its parent's, so a walk recurses as
/// deep as the root's level claims. Real APFS trees are a handful of levels (a 4 KiB node holds
/// hundreds of keys); even at the smallest branching that keeps a tree, 64 levels span the whole
/// 2^64 key space, so a root deeper than this is corrupt and its walk is refused rather than run.
const MAX_TREE_DEPTH: u16 = 64;
/// A tree's root node, with what its walks need.
struct Root {
node: Node,
info: BtreeInfo,
/// What a child identifier in an index entry is relative to.
child_base: u64,
}
impl Tree<'_> {
/// Call `f` on each leaf record from the first whose key is not below `start`, in key
/// order, until it returns false.
pub(crate) fn scan(&self, start: &[u8], f: &mut Visit<'_>) -> Result<()> {
let r = self.root()?;
self.scan_node(&r.node, &r, start, f).map(|_| ())
}
fn scan_node(&self, n: &Node, r: &Root, start: &[u8], f: &mut Visit<'_>) -> Result<bool> {
let keys = self.keys(n)?;
if n.is_leaf() {
for (i, k) in keys.iter().enumerate() {
if (self.order)(k, start) == Ordering::Less {
continue;
}
let (_, v) = n.entry(i as u32)?;
let v =
v.ok_or_else(|| corrupt(n.block, format!("leaf entry {i} without a value")))?;
if !f(k, v)? {
return Ok(false);
}
}
return Ok(true);
}
let first = keys
.iter()
.rposition(|k| (self.order)(k, start) != Ordering::Greater)
.unwrap_or(0);
for i in first..keys.len() {
let child = self.child(n, r, i)?;
if !self.scan_node(&child, r, start, f)? {
return Ok(false);
}
}
Ok(true)
}
/// The leaf record with the greatest key not above `key`.
pub(crate) fn last_le(&self, key: &[u8]) -> Result<Option<Record>> {
let r = self.root()?;
let mut n = r.node.clone();
loop {
let keys = self.keys(&n)?;
let Some(i) = keys
.iter()
.rposition(|k| (self.order)(k, key) != Ordering::Greater)
else {
return Ok(None);
};
if n.is_leaf() {
let (k, v) = n.entry(i as u32)?;
let v =
v.ok_or_else(|| corrupt(n.block, format!("leaf entry {i} without a value")))?;
return Ok(Some((k.to_vec(), v.to_vec())));
}
n = self.child(&n, &r, i)?;
}
}
/// The block address of the tree's root node.
pub(crate) fn root_block(&self) -> Result<u64> {
Ok(self.root()?.node.block)
}
/// Visit every node of the tree, parents before children, in key order, reporting each
/// node's shape for studying how it is packed.
pub(crate) fn walk_nodes(&self, cb: &mut dyn FnMut(&NodeShape) -> Result<()>) -> Result<()> {
let r = self.root()?;
self.walk_nodes_at(&r.node, &r, cb)
}
fn walk_nodes_at(
&self,
n: &Node,
r: &Root,
cb: &mut dyn FnMut(&NodeShape) -> Result<()>,
) -> Result<()> {
let keys = self.keys(n)?;
let first = keys.first().map(|k| k.to_vec()).unwrap_or_default();
let second = keys.get(1).map(|k| k.to_vec()).unwrap_or_default();
let last = keys.last().map(|k| k.to_vec()).unwrap_or_default();
cb(&NodeShape {
level: n.level,
nkeys: n.nkeys,
is_root: n.is_root(),
// btn_free_space is an nloc_t (off at FREE_SPACE, len two bytes after it); the
// unused byte count is the len.
free_space: u16_at(&n.bytes, btree::FREE_SPACE + 2),
first_key: first,
second_key: second,
last_key: last,
})?;
if !n.is_leaf() {
for i in 0..keys.len() {
let child = self.child(n, r, i)?;
self.walk_nodes_at(&child, r, cb)?;
}
}
Ok(())
}
fn root(&self) -> Result<Root> {
let (paddr, noheader) = self.resolve(self.root)?;
let node = self.read_node(
self.root,
paddr,
noheader,
true,
self.max_xid,
None,
self.root_hash,
)?;
if node.level >= MAX_TREE_DEPTH {
return Err(corrupt(
paddr,
format!("root at level {}, deeper than any real B-tree", node.level),
));
}
let info = node
.info()
.ok_or_else(|| corrupt(paddr, "root node without tree info"))?;
if info.node_size != self.c.block_size {
return Err(Error::Unsupported(format!(
"B-tree node size {} in a container of {}-byte blocks",
info.node_size, self.c.block_size
)));
}
// A hashed tree's index entries name their children relative to the root's identifier
// (measured on the sealed system volumes of macOS 14 to 27).
let child_base = if info.flags & btree::HASHED != 0 {
self.root
} else {
0
};
Ok(Root {
node,
info,
child_base,
})
}
/// Node `n`'s keys, checked to ascend strictly.
fn keys<'n>(&self, n: &'n Node) -> Result<Vec<&'n [u8]>> {
let mut keys: Vec<&'n [u8]> = Vec::with_capacity(n.nkeys as usize);
for i in 0..n.nkeys {
let (k, _) = n.entry(i)?;
if k.len() < 8 {
return Err(corrupt(n.block, format!("key {i} of {} bytes", k.len())));
}
if let Some(prev) = keys.last()
&& (self.order)(prev, k) != Ordering::Less
{
return Err(corrupt(
n.block,
format!("key {i} is not above the one before it"),
));
}
keys.push(k);
}
Ok(keys)
}
/// The child entry `i` of index node `n` names, checked against `n`.
fn child(&self, n: &Node, r: &Root, i: usize) -> Result<Node> {
let (k, v) = n.entry(i as u32)?;
let v = v
.filter(|v| v.len() >= 8)
.ok_or_else(|| corrupt(n.block, format!("index entry {i} without a child")))?;
let oid = r
.child_base
.checked_add(u64_at(v, 0))
.ok_or_else(|| corrupt(n.block, "child identifier overflows"))?;
let (paddr, noheader) = self.resolve(oid)?;
// A hashed tree's index entry holds its child's hash after the child's identifier.
let hash = if r.info.flags & btree::HASHED != 0 {
Some(v.get(8..8 + HASH_LEN).ok_or_else(|| {
corrupt(n.block, format!("index entry {i} without its child's hash"))
})?)
} else {
None
};
// A physical tree's child is never newer than its parent; a virtual tree's child is
// rewritten through the object map without its parent.
let node_xid = u64_at(&n.bytes, 16);
let max_xid = match self.addressing {
Addressing::Physical if node_xid != 0 => node_xid.min(self.max_xid),
_ => self.max_xid,
};
let c = self.read_node(oid, paddr, noheader, false, max_xid, Some(&r.info), hash)?;
if c.level + 1 != n.level {
return Err(corrupt(
paddr,
format!(
"child at level {} under a node at level {}",
c.level, n.level
),
));
}
if c.nkeys == 0 {
return Err(corrupt(paddr, "empty non-root node"));
}
let (ck, _) = c.entry(0)?;
if ck.len() < 8 || (self.order)(k, ck) == Ordering::Greater {
return Err(corrupt(
paddr,
"child's first key is below its parent's key for it",
));
}
Ok(c)
}
/// A node's block address, and whether it is stored without an object header.
fn resolve(&self, oid: u64) -> Result<(u64, bool)> {
match self.addressing {
Addressing::Physical => Ok((oid, false)),
Addressing::Virtual(m, xid) => {
let (_, v) = self.c.omap_lookup(m, oid, xid)?.ok_or_else(|| {
corrupt(
0,
format!("virtual object {oid} is not in the object map at xid {xid}"),
)
})?;
if v.flags & omap::VAL_DELETED != 0 {
return Err(corrupt(v.paddr, format!("virtual object {oid} is deleted")));
}
if v.flags & omap::VAL_ENCRYPTED != 0 {
return Err(Error::Unsupported(format!("encrypted object {oid}")));
}
Ok((v.paddr, v.flags & omap::VAL_NOHEADER != 0))
}
}
}
/// Read node `oid` at `paddr`. A node with an object header has it checked; a node
/// without one (a sealed volume's) is checked by `hash`, its SHA-256 as its parent or the
/// seal records it, which a node with a header is held to as well where one is given.
#[allow(clippy::too_many_arguments)]
fn read_node(
&self,
oid: u64,
paddr: u64,
noheader: bool,
root: bool,
max_xid: u64,
info: Option<&BtreeInfo>,
hash: Option<&[u8]>,
) -> Result<Node> {
let b = self.c.read_block(paddr)?;
if let Some(h) = hash
&& Sha256::digest(&b)[..] != *h
{
return Err(corrupt(
paddr,
format!("node {oid}'s hash differs from the one recorded for it"),
));
}
if noheader || u16_at(&b, btree::FLAGS) & btree::NODE_NOHEADER != 0 {
if hash.is_none() {
return Err(Error::Unsupported(format!(
"headerless node {oid} without a hash to check it by"
)));
}
if b[..32].iter().any(|x| *x != 0) {
return Err(corrupt(paddr, "headerless node with a header"));
}
return self.parse_node(paddr, b, root, info);
}
let kind = if root { obj::BTREE } else { obj::BTREE_NODE };
check_object(&b, paddr, Some(oid), Some(kind), max_xid)?;
let st = u32_at(&b, 28);
if st != self.subtype {
return Err(corrupt(
paddr,
format!("tree node of subtype {st:#x}, expected {:#x}", self.subtype),
));
}
self.parse_node(paddr, b, root, info)
}
fn parse_node(
&self,
paddr: u64,
b: Vec<u8>,
root: bool,
info: Option<&BtreeInfo>,
) -> Result<Node> {
let flags = u16_at(&b, btree::FLAGS);
if root != (flags & btree::NODE_ROOT != 0) {
return Err(corrupt(
paddr,
if root {
"tree root without the root flag"
} else {
"non-root node with the root flag"
},
));
}
Node::parse(paddr, b, info)
}
}
+271
View File
@@ -0,0 +1,271 @@
//! Building a sealed volume's hashed file-system tree: pack a stream of records, in key order,
//! into headerless nodes, and hash each node into its parent to a signed root
//! (Apple File System Reference, "Sealed Volumes").
//!
//! The packing here is our own — records filled into each node until the next does not fit — not
//! a copy of how Apple's kernel lays its nodes out. The result is a self-consistent hashed tree:
//! every index entry carries the SHA-256 of the block it points at, and the root hash is the
//! SHA-256 of the root block. A reader that walks it checks out.
use sha2::{Digest, Sha256};
use crate::fs;
use crate::ondisk::{btree, obj};
use crate::write::node::{Layout, NodeSpec};
/// A file-system block holds a node; the sealed system volumes we build are 4 KiB.
pub const BLOCK: usize = 4096;
/// A node's header, before its table of contents.
const HDR: usize = 56;
/// The tree info at the end of a root node.
const INFO: usize = 40;
/// The sealed file-system tree's flags: headerless, hashed, non-aligned, sequential-insert.
pub const TREE_FLAGS: u32 =
btree::NOHEADER | btree::HASHED | btree::KV_NONALIGNED | btree::SEQUENTIAL_INSERT;
/// One leaf record, in key order.
#[derive(Clone)]
pub struct Record {
pub key: Vec<u8>,
pub val: Vec<u8>,
}
/// A built node: its identifier, level, first key (its parent's separator), the SHA-256 of its
/// block, and the block itself.
pub struct BuiltNode {
pub oid: u64,
pub level: u16,
pub first_key: Vec<u8>,
pub hash: [u8; 32],
pub block: Vec<u8>,
}
/// A built hashed tree.
pub struct SealedTree {
/// Every node, parents after children (leaves first, root last).
pub nodes: Vec<BuiltNode>,
/// The root node's identifier. Index values name children relative to it, so the tree's
/// blocks and hashes are the same wherever its identifiers start ([`SealedTree::rebase`]).
pub root_oid: u64,
/// The signed root hash: SHA-256 of the root block.
pub root_hash: [u8; 32],
/// The tree info recorded in the root node.
pub longest_key: u32,
pub longest_val: u32,
pub key_count: u64,
}
impl SealedTree {
/// The same tree with its identifiers starting at `root_oid`: its blocks do not change.
pub fn rebase(&mut self, root_oid: u64) {
for n in &mut self.nodes {
n.oid = n.oid - self.root_oid + root_oid;
}
self.root_oid = root_oid;
}
}
/// Divide a level's entries, given by their key and value sizes, among nodes each holding as
/// many as fit; returns each node's end (exclusive).
fn pack(n: usize, size: impl Fn(usize) -> (usize, usize), level: u16) -> Vec<usize> {
let mut bounds = Vec::new();
let mut i = 0;
while i < n {
let (mut kb, mut vb, mut cnt) = (0, 0, 0);
while i + cnt < n {
let (k, v) = size(i + cnt);
if !Layout::Variable.fits(cnt + 1, kb + k, vb + v, false, level) {
break;
}
kb += k;
vb += v;
cnt += 1;
}
// A record larger than a node is refused before a tree is built ([`build`]).
i += cnt.max(1);
bounds.push(i);
}
bounds
}
/// An index entry's value: the child's identifier relative to the root's, then its hash.
fn index_val(rel: u64, hash: &[u8; 32]) -> Vec<u8> {
let mut v = Vec::with_capacity(8 + 32);
v.extend_from_slice(&rel.to_le_bytes());
v.extend_from_slice(hash);
v
}
/// Build a sealed hashed tree from `records` in key order: leaves filled until the next record
/// does not fit, then index levels the same way, each index entry its child's first key, its
/// identifier relative to the root and its SHA-256, until a level fits one node, the root.
/// `root_oid` is the root's identifier; the others follow it, leaves first.
///
/// # Panics
///
/// If `records` is empty, or a record does not fit a node.
#[must_use]
pub fn build(records: &[Record], root_oid: u64) -> SealedTree {
assert!(
!records.is_empty(),
"a sealed tree needs at least one record"
);
for r in records {
assert!(
Layout::Variable.fits(1, r.key.len(), r.val.len(), false, 0),
"a record of {} key and {} value bytes fits no node",
r.key.len(),
r.val.len()
);
}
let longest_key = records.iter().map(|r| r.key.len()).max().unwrap_or(0) as u32;
let longest_val = records.iter().map(|r| r.val.len()).max().unwrap_or(0) as u32;
let key_count = records.len() as u64;
let mut nodes: Vec<BuiltNode> = Vec::new();
let mut next_rel = 1u64;
let mut node =
|entries: &[(Vec<u8>, Vec<u8>)], level: u16, is_root: bool, nodes: &mut Vec<BuiltNode>| {
let rel = if is_root {
0
} else {
next_rel += 1;
next_rel - 1
};
let block = NodeSpec {
obj_type: 0,
subtype: obj::FSTREE,
oid: 0,
xid: 0,
level,
is_root,
headerless: true,
hashed: true,
layout: Layout::Variable,
tree_flags: TREE_FLAGS,
longest_key,
longest_val,
key_count,
node_count: nodes.len() as u64 + 1,
entries,
}
.build();
let hash: [u8; 32] = Sha256::digest(&block).into();
nodes.push(BuiltNode {
oid: root_oid + rel,
level,
first_key: entries[0].0.clone(),
hash,
block,
});
(rel, hash)
};
// The leaves. A level that fits one node is the root.
let all = |n: usize, size: &dyn Fn(usize) -> (usize, usize), level: u16| {
let (kb, vb) = (0..n).fold((0, 0), |(k, v), i| {
let (a, b) = size(i);
(k + a, v + b)
});
Layout::Variable.fits(n, kb, vb, true, level)
};
let leaf_size = |i: usize| (records[i].key.len(), records[i].val.len());
let pairs = |r: &[Record]| -> Vec<(Vec<u8>, Vec<u8>)> {
r.iter().map(|r| (r.key.clone(), r.val.clone())).collect()
};
let mut above: Vec<(Vec<u8>, Vec<u8>)> = Vec::new();
if all(records.len(), &leaf_size, 0) {
node(&pairs(records), 0, true, &mut nodes);
} else {
let mut start = 0;
for end in pack(records.len(), leaf_size, 0) {
let (rel, hash) = node(&pairs(&records[start..end]), 0, false, &mut nodes);
above.push((records[start].key.clone(), index_val(rel, &hash)));
start = end;
}
// Index levels until one holds a level whole.
let mut level = 1u16;
loop {
let entries = std::mem::take(&mut above);
let size = |i: usize| (entries[i].0.len(), entries[i].1.len());
if all(entries.len(), &size, level) {
node(&entries, level, true, &mut nodes);
break;
}
let mut start = 0;
for end in pack(entries.len(), size, level) {
let (rel, hash) = node(&entries[start..end], level, false, &mut nodes);
above.push((entries[start].0.clone(), index_val(rel, &hash)));
start = end;
}
level += 1;
}
}
let root_hash = nodes.last().expect("a root").hash;
SealedTree {
nodes,
root_oid,
root_hash,
longest_key,
longest_val,
key_count,
}
}
/// Check a built tree is a self-consistent Merkle tree: every index entry's stored hash is the
/// SHA-256 of the block it names, each block's stored hash matches its bytes, and the root hash
/// is the SHA-256 of the root block. Returns the number of index entries checked, or an error
/// string naming the first inconsistency.
pub fn verify(tree: &SealedTree) -> Result<u64, String> {
use std::collections::HashMap;
let by_oid: HashMap<u64, &BuiltNode> = tree.nodes.iter().map(|n| (n.oid, n)).collect();
let mut checked = 0u64;
let mut root_seen = false;
for n in &tree.nodes {
let h: [u8; 32] = Sha256::digest(&n.block).into();
if h != n.hash {
return Err(format!("node {}: stored hash != SHA-256(block)", n.oid));
}
let flags = u16::from_le_bytes([n.block[32], n.block[33]]);
let is_root = flags & btree::NODE_ROOT != 0;
if is_root {
root_seen = true;
if n.hash != tree.root_hash {
return Err("root node hash != tree.root_hash".into());
}
}
if flags & btree::NODE_LEAF != 0 {
continue;
}
// Index node: each value is child-oid-relative + child hash.
let nkeys = u32::from_le_bytes([n.block[36], n.block[37], n.block[38], n.block[39]]);
let toc = HDR;
let val_end = BLOCK - if is_root { INFO } else { 0 };
for i in 0..nkeys as usize {
let t = toc + i * 8;
let vo = u16::from_le_bytes([n.block[t + 4], n.block[t + 5]]) as usize;
let vs = val_end - vo;
let rel = u64::from_le_bytes(n.block[vs..vs + 8].try_into().unwrap());
let child_hash = &n.block[vs + 8..vs + 40];
let child_oid = tree.root_oid + rel;
let child = by_oid
.get(&child_oid)
.ok_or_else(|| format!("node {}: child oid {child_oid} missing", n.oid))?;
if child.hash[..] != *child_hash {
return Err(format!(
"node {}: entry {i} hash != child {child_oid}'s block hash",
n.oid
));
}
if child.level + 1 != n.level {
return Err(format!("node {}: child {child_oid} at wrong level", n.oid));
}
checked += 1;
}
}
if !root_seen {
return Err("no root node".into());
}
let _ = fs::key_header;
Ok(checked)
}
+445
View File
@@ -0,0 +1,445 @@
//! Copying a directory of one volume into a new volume, record for record: the directory becomes
//! the new volume's root, and every object below it keeps its mode, owner, flags, times,
//! attributes and compressed form, renumbered into the new volume, its data streams' bytes read
//! from where the source keeps them.
//!
//! A caller may replace any entry with a symbolic link (nothing below a replaced directory is
//! copied), and add files of its own in directories the copy holds. This is how a restore makes
//! the Data volume from the system image's data template (docs/design.md, "The disk").
//!
//! The records copied are those a data template holds: inodes (with their name and data-stream
//! fields), directory entries, attributes (held in their record, or in a data stream such as a
//! resource fork's), data-stream identifiers and file extents. A hard link, a sibling record or a
//! directory's statistics fails the copy rather than being copied wrong.
use std::collections::HashMap;
use crate::fs::{self, key_header, key_word};
use crate::ondisk::{ino, rec};
use super::fsbuild::{self, SYMLINK_XATTR};
use super::records::{DT_LNK, INODE_FLAGS_BASE, InodeBuilder, dir_rec, name_xfield, xfields};
use super::volume::{Counts, Stream};
/// What becomes of an entry the copy reaches.
pub enum Replace {
/// Copied as it is (a directory with what is below it).
Keep,
/// Replaced by a symbolic link to this target; nothing below it is copied.
Link(Vec<u8>),
}
/// A run of a source stream: `len` bytes from source block `phys`, or a hole.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SourceRun {
pub len: u64,
pub phys: Option<u64>,
}
/// A copied tree: its records (but file extents), its data streams, where each stream's bytes are
/// in the source, in order, what the volume counts, and the next identifier.
pub struct Copied {
pub records: Vec<(Vec<u8>, Vec<u8>)>,
pub streams: Vec<Stream>,
/// For each stream, its runs in the source; or, for a file the caller added, the index of
/// that file among the additions.
pub sources: Vec<StreamSource>,
pub counts: Counts,
pub next_obj_id: u64,
}
/// Where a copied stream's bytes come from.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum StreamSource {
/// The source volume's blocks.
Runs(Vec<SourceRun>),
/// The caller's added file of this index.
Added(usize),
}
/// A tree the copy cannot make.
#[derive(Debug, thiserror::Error)]
pub enum CopyError {
#[error("object {0:#x}: the copy has no {1} record kind")]
Unsupported(u64, &'static str),
#[error("object {0:#x} has no inode")]
NoInode(u64),
#[error("{0}: added in a directory the copy does not hold")]
NoParent(String),
#[error("stream {0:#x}: its extents do not cover it from its start")]
Gap(u64),
}
/// A record: its key and its value.
type Record = (Vec<u8>, Vec<u8>);
/// The records of each object, by identifier.
struct Index<'a> {
by_oid: HashMap<u64, Vec<&'a Record>>,
}
impl<'a> Index<'a> {
fn new(records: &'a [(Vec<u8>, Vec<u8>)]) -> Self {
let mut by_oid: HashMap<u64, Vec<&Record>> = HashMap::new();
for r in records {
by_oid.entry(key_header(&r.0).0).or_default().push(r);
}
Self { by_oid }
}
fn of(&self, oid: u64) -> &[&'a (Vec<u8>, Vec<u8>)] {
self.by_oid.get(&oid).map_or(&[], Vec::as_slice)
}
}
fn u64_at(b: &[u8], at: usize) -> u64 {
u64::from_le_bytes(b[at..at + 8].try_into().unwrap())
}
fn put_u64(b: &mut [u8], at: usize, v: u64) {
b[at..at + 8].copy_from_slice(&v.to_le_bytes());
}
/// A record's key with its identifier replaced, the rest kept.
fn rekey(k: &[u8], oid: u64) -> Vec<u8> {
let (_, t) = key_header(k);
let mut out = k.to_vec();
out[..8].copy_from_slice(&key_word(oid, t).to_le_bytes());
out
}
/// The runs of stream `id` in the source, from its file extents, in order.
fn runs_of(idx: &Index, id: u64) -> Result<Vec<SourceRun>, CopyError> {
let mut ext: Vec<(u64, u64, u64)> = idx
.of(id)
.iter()
.filter(|(k, _)| key_header(k).1 == rec::FILE_EXTENT)
.map(|(k, v)| {
let e = fs::FileExtent::parse(k, v);
(e.logical, e.len, e.phys)
})
.collect();
ext.sort_unstable();
let mut at = 0;
let mut runs = Vec::with_capacity(ext.len());
for (logical, len, phys) in ext {
if logical != at {
return Err(CopyError::Gap(id));
}
runs.push(SourceRun {
len,
phys: (phys != 0).then_some(phys),
});
at += len;
}
Ok(runs)
}
/// The total length of runs.
fn runs_len(runs: &[SourceRun]) -> u64 {
runs.iter().map(|r| r.len).sum()
}
/// Copy the tree below directory `root` of the volume whose records are `records` (all of them,
/// in any order) into a new volume, names hashed folding case where `fold`. `decide` is asked,
/// for each entry below `root` that is not itself a symbolic link, by its path from `root` and
/// whether it is a directory, whether to copy it or make it a link; a link made is stamped `t`.
/// `added` are files to add, each in a directory the copy holds.
///
/// # Errors
///
/// [`CopyError`] for a record kind the copy does not make, an object without its inode, a
/// stream whose extents leave a gap, or an addition whose directory the copy lacks.
pub fn copy_tree(
records: &[(Vec<u8>, Vec<u8>)],
root: u64,
fold: bool,
t: u64,
decide: &mut dyn FnMut(&str, bool) -> Replace,
added: &[fsbuild::Item],
) -> Result<Copied, CopyError> {
let idx = Index::new(records);
let mut out = Copied {
records: Vec::new(),
streams: Vec::new(),
sources: Vec::new(),
counts: Counts::default(),
next_obj_id: ino::MIN_USER,
};
let new_oid = |out: &mut Copied| {
let o = out.next_obj_id;
out.next_obj_id += 1;
o
};
// Each copied directory's path and new identifier, for the additions.
let mut dirs: HashMap<String, u64> = HashMap::from([(String::new(), ino::ROOT_DIR)]);
let mut children: HashMap<u64, i32> = HashMap::new();
// Depth first: (source object, new identifier, new parent, path).
let mut stack: Vec<(u64, u64, u64, String)> = vec![(root, ino::ROOT_DIR, 1, String::new())];
while let Some((src, oid, parent, path)) = stack.pop() {
let recs = idx.of(src);
let inode = recs
.iter()
.find(|(k, _)| key_header(k).1 == rec::INODE)
.ok_or(CopyError::NoInode(src))?;
let parsed = fs::Inode::parse(&inode.1).ok_or(CopyError::NoInode(src))?;
if parsed.private_id != src {
return Err(CopyError::Unsupported(src, "shared data stream"));
}
if !parsed.is_dir() && parsed.nchildren_or_nlink > 1 {
return Err(CopyError::Unsupported(src, "hard link"));
}
let is_dir = parsed.is_dir();
match parsed.mode & 0o170000 {
0o040000 => out.counts.directories += u64::from(oid != ino::ROOT_DIR),
0o100000 => out.counts.files += 1,
0o120000 => out.counts.symlinks += 1,
_ => out.counts.other += 1,
}
if is_dir {
dirs.insert(path.clone(), oid);
}
for (k, v) in recs {
match key_header(k).1 {
rec::INODE => {
let mut v = v.clone();
put_u64(&mut v, 0, parent);
put_u64(&mut v, 8, oid);
if oid == ino::ROOT_DIR {
// The volume's root names itself `root`.
v.truncate(fs::INODE_FIXED);
let mut fields: Vec<_> = parsed
.xfields
.iter()
.filter(|x| x.kind != fs::xf::NAME)
.map(|x| super::records::XField {
kind: x.kind,
flags: x.flags,
data: x.data.clone(),
})
.collect();
fields.insert(0, name_xfield(b"root"));
v.extend_from_slice(&xfields(&fields));
}
out.records.push((rekey(k, oid), v));
}
rec::DIR_REC => {
let child = u64_at(v, 0);
let name = fs::drec_name(k);
let cpath = if path.is_empty() {
String::from_utf8_lossy(name).into_owned()
} else {
format!("{path}/{}", String::from_utf8_lossy(name))
};
let child_inode = idx
.of(child)
.iter()
.find(|(k, _)| key_header(k).1 == rec::INODE)
.and_then(|(_, v)| fs::Inode::parse(v))
.ok_or(CopyError::NoInode(child))?;
let child_is_dir = child_inode.is_dir();
let is_link = child_inode.mode & 0o170000 == 0o120000;
let replace = if is_link {
Replace::Keep
} else {
decide(&cpath, child_is_dir)
};
let new_child = new_oid(&mut out);
*children.entry(oid).or_default() += 1;
let mut val = v.clone();
put_u64(&mut val, 0, new_child);
match replace {
Replace::Keep => {
out.records.push((rekey(k, oid), val));
stack.push((child, new_child, oid, cpath));
}
Replace::Link(target) => {
out.records
.push(dir_rec(oid, name, fold, new_child, t, DT_LNK));
out.records.extend(link_records(
new_child,
oid,
name,
&target,
t,
&child_inode,
));
out.counts.symlinks += 1;
}
}
}
rec::XATTR => {
let mut val = v.clone();
if let Some((_, fs::XattrData::Stream(sid, _))) = fs::parse_xattr(v) {
let runs = runs_of(&idx, sid)?;
let nsid = new_oid(&mut out);
put_u64(&mut val, 4, nsid);
out.streams.push(Stream {
id: nsid,
owner: oid,
len: runs_len(&runs),
});
out.sources.push(StreamSource::Runs(runs));
}
out.records.push((rekey(k, oid), val));
}
rec::DSTREAM_ID => {
let runs = runs_of(&idx, src)?;
out.streams.push(Stream {
id: oid,
owner: oid,
len: runs_len(&runs),
});
out.sources.push(StreamSource::Runs(runs));
out.records.push((rekey(k, oid), v.clone()));
}
rec::FILE_EXTENT => {}
rec::DIR_STATS => return Err(CopyError::Unsupported(src, "directory statistics")),
rec::SIBLING_LINK | rec::SIBLING_MAP => {
return Err(CopyError::Unsupported(src, "sibling"));
}
other => return Err(CopyError::Unsupported(src, rec::name(other))),
}
}
}
// The additions, each a new entry of its directory.
for (i, it) in added.iter().enumerate() {
let (dir, name) = it.path.rsplit_once('/').unwrap_or(("", &it.path));
let parent = *dirs
.get(dir)
.ok_or_else(|| CopyError::NoParent(it.path.clone()))?;
let oid = new_oid(&mut out);
*children.entry(parent).or_default() += 1;
let len = match it.kind {
fsbuild::Kind::File { len } => len,
_ => {
return Err(CopyError::Unsupported(
oid,
"added entry that is not a file",
));
}
};
let mut fields = vec![name_xfield(name.as_bytes())];
if len > 0 {
fields.push(super::records::dstream_xfield(super::records::dstream(
len,
super::volume::blocks_of(len) * super::geometry::BLOCK_SIZE,
0,
len,
0,
)));
out.streams.push(Stream {
id: oid,
owner: oid,
len,
});
out.sources.push(StreamSource::Added(i));
out.records.push((
key_word(oid, rec::DSTREAM_ID).to_le_bytes().to_vec(),
1u32.to_le_bytes().to_vec(),
));
}
out.records.push(dir_rec(
parent,
name.as_bytes(),
fold,
oid,
t,
super::records::DT_REG,
));
out.records.push(
InodeBuilder {
oid,
parent,
private_id: oid,
create_time: t,
mod_time: t,
change_time: t,
access_time: t,
internal_flags: INODE_FLAGS_BASE,
nchildren_or_nlink: 1,
default_protection_class: 0,
write_generation_counter: 1,
bsd_flags: it.bsd_flags,
owner: it.uid,
group: it.gid,
mode: 0o100000 | (it.mode & 0o7777),
uncompressed_size: 0,
xfields: fields,
}
.build(),
);
out.counts.files += 1;
}
// A directory that gained an addition counts it.
for (k, v) in &mut out.records {
let (oid, t) = key_header(k);
if t == rec::INODE
&& let (Some(n), Some(inode)) = (children.get(&oid), fs::Inode::parse(v))
&& inode.is_dir()
{
v[56..60].copy_from_slice(&n.to_le_bytes());
}
}
// The volume's private directory and its entry, as every volume has.
for (k, v) in super::records::empty_volume_records(fold, t) {
let (oid, kind) = key_header(&k);
let is_root = (kind == rec::INODE && oid == ino::ROOT_DIR)
|| (kind == rec::DIR_REC && fs::drec_name(&k) == b"root");
if !is_root || kind == rec::DIR_REC {
out.records.push((k, v));
}
}
out.records
.sort_by(|a, b| crate::fs::compare_keys(&a.0, &b.0));
Ok(out)
}
/// A symbolic link's inode and its target attribute, in place of `was`: the link keeps its
/// permissions, owner and flags (but compression, which a link's content never has), as VZ's
/// restore makes its links into the data template **[vz]**.
fn link_records(
oid: u64,
parent: u64,
name: &[u8],
target: &[u8],
t: u64,
was: &fs::Inode,
) -> Vec<(Vec<u8>, Vec<u8>)> {
let mut v = target.to_vec();
v.push(0);
let mut xk = key_word(oid, rec::XATTR).to_le_bytes().to_vec();
xk.extend_from_slice(&((SYMLINK_XATTR.len() + 1) as u16).to_le_bytes());
xk.extend_from_slice(SYMLINK_XATTR);
xk.push(0);
let mut xv = Vec::with_capacity(4 + v.len());
xv.extend_from_slice(&(fs::XATTR_DATA_EMBEDDED | fs::XATTR_FILE_SYSTEM_OWNED).to_le_bytes());
xv.extend_from_slice(&(v.len() as u16).to_le_bytes());
xv.extend_from_slice(&v);
vec![
InodeBuilder {
oid,
parent,
private_id: oid,
create_time: t,
mod_time: t,
change_time: t,
access_time: t,
internal_flags: INODE_FLAGS_BASE,
nchildren_or_nlink: 1,
default_protection_class: 0,
write_generation_counter: 1,
bsd_flags: was.bsd_flags & !crate::decmpfs::UF_COMPRESSED,
owner: was.owner,
group: was.group,
mode: 0o120000 | (was.mode & 0o7777),
uncompressed_size: 0,
xfields: vec![name_xfield(name)],
}
.build(),
(xk, xv),
]
}
@@ -0,0 +1,297 @@
//! Turning a tree of files, directories, symbolic links and clones into a volume's file-system
//! records and data streams, as a volume holding them records them (Apple File System
//! Reference, "File-System Objects"; each record's form checked against volumes `fsck_apfs`
//! accepts, and a clone's against the one Virtualization.framework's restore makes in Preboot).
//!
//! Every entry is numbered in the order given, from the first user identifier up, so a parent,
//! which comes before its children, is numbered first. Each gets an inode, carrying its own name,
//! and a directory entry in its parent. A file with bytes gets a data stream, its identifier the
//! inode's; a clone shares the data stream of the file it clones, which then has two references,
//! as `clonefile` leaves a clone until either is written. A symbolic link keeps its target in the
//! `com.apple.fs.symlink` attribute.
use std::collections::HashMap;
use crate::fs::key_word;
use crate::ondisk::{ino, rec};
use super::records::{
self, DT_DIR, DT_LNK, DT_REG, INODE_FLAGS_BASE, InodeBuilder, XField, dir_rec, dstream,
dstream_xfield, name_xfield,
};
use super::volume::{Counts, Stream, blocks_of};
/// `INODE_WAS_CLONED`: the inode was made by cloning another, or another by cloning it.
const INODE_WAS_CLONED: u64 = 0x10;
/// `INODE_WAS_EVER_CLONED`.
const INODE_WAS_EVER_CLONED: u64 = 0x400;
/// An attribute's value is stored in the record (`XATTR_DATA_EMBEDDED`).
const XATTR_EMBEDDED: u16 = crate::fs::XATTR_DATA_EMBEDDED;
/// An attribute the file system owns (`XATTR_FILE_SYSTEM_OWNED`).
const XATTR_FS_OWNED: u16 = crate::fs::XATTR_FILE_SYSTEM_OWNED;
/// The attribute a symbolic link keeps its target in.
pub const SYMLINK_XATTR: &[u8] = b"com.apple.fs.symlink";
/// The most bytes an attribute's value may have stored in its record.
pub const MAX_EMBEDDED_XATTR: usize = 3804;
/// What an entry is.
#[derive(Clone, Debug)]
pub enum Kind {
Dir,
/// A regular file of `len` bytes, its bytes written by the caller where the volume places
/// its stream.
File {
len: u64,
},
/// A symbolic link to the target given.
Symlink(Vec<u8>),
/// A clone of the file at the path given, which comes before it.
Clone(String),
}
/// One entry of the tree.
#[derive(Clone, Debug)]
pub struct Item {
/// Its path from the volume's root, without a leading `/`.
pub path: String,
pub kind: Kind,
/// Its permission bits; the file type comes from `kind`.
pub mode: u16,
pub uid: u32,
pub gid: u32,
pub bsd_flags: u32,
/// Its extended attributes, each stored in its record.
pub xattrs: Vec<(Vec<u8>, Vec<u8>)>,
}
/// A tree's records, its data streams with the entry each is for, and what the volume's
/// superblock counts.
pub struct Built {
pub records: Vec<(Vec<u8>, Vec<u8>)>,
pub streams: Vec<Stream>,
/// The index into the items of the file each stream holds the bytes of.
pub stream_items: Vec<usize>,
pub counts: Counts,
/// The first identifier the volume has not handed out.
pub next_obj_id: u64,
}
/// A tree that cannot be a volume.
#[derive(Debug, thiserror::Error)]
pub enum BuildError {
#[error("{0}: its parent is not a directory before it")]
NoParent(String),
#[error("{0}: given twice")]
Duplicate(String),
#[error("{0}: a clone of {1}, which is not a file with bytes before it")]
BadClone(String, String),
#[error("{0}: attribute {1} is {2} bytes, more than a record holds")]
XattrTooBig(String, String, usize),
}
/// An attribute record of inode `oid`: its name (and a NUL) keys it, and its value is stored.
fn xattr(oid: u64, name: &[u8], value: &[u8], flags: u16) -> (Vec<u8>, Vec<u8>) {
let mut k = key_word(oid, rec::XATTR).to_le_bytes().to_vec();
k.extend_from_slice(&((name.len() + 1) as u16).to_le_bytes());
k.extend_from_slice(name);
k.push(0);
let mut v = Vec::with_capacity(4 + value.len());
v.extend_from_slice(&flags.to_le_bytes());
v.extend_from_slice(&(value.len() as u16).to_le_bytes());
v.extend_from_slice(value);
(k, v)
}
/// A data stream's reference count record.
fn dstream_id(id: u64, refcnt: u32) -> (Vec<u8>, Vec<u8>) {
(
key_word(id, rec::DSTREAM_ID).to_le_bytes().to_vec(),
refcnt.to_le_bytes().to_vec(),
)
}
/// The last component of a path.
fn base_name(path: &str) -> &str {
path.rsplit_once('/').map_or(path, |p| p.1)
}
/// The directory a path is in, `""` for the root.
fn parent_of(path: &str) -> &str {
path.rsplit_once('/').map_or("", |p| p.0)
}
/// Build the records of `items`, every time `t`, names hashed folding case where `fold`.
///
/// # Errors
///
/// [`BuildError`] for an entry whose parent is missing or not a directory, a path given twice, a
/// clone of anything but an earlier file with bytes, or an attribute too big to store in its
/// record.
pub fn build(items: &[Item], fold: bool, t: u64) -> Result<Built, BuildError> {
// Number every entry, and find each one's parent.
let mut oid_of: HashMap<&str, u64> = HashMap::from([("", ino::ROOT_DIR)]);
let mut is_dir: HashMap<u64, bool> = HashMap::from([(ino::ROOT_DIR, true)]);
let mut children: HashMap<u64, u32> = HashMap::new();
let mut next = ino::MIN_USER;
let mut oids = Vec::with_capacity(items.len());
let mut parents = Vec::with_capacity(items.len());
for it in items {
let parent = *oid_of
.get(parent_of(&it.path))
.filter(|p| is_dir.get(p).copied().unwrap_or(false))
.ok_or_else(|| BuildError::NoParent(it.path.clone()))?;
if oid_of.contains_key(it.path.as_str()) {
return Err(BuildError::Duplicate(it.path.clone()));
}
let oid = next;
next += 1;
oid_of.insert(&it.path, oid);
is_dir.insert(oid, matches!(it.kind, Kind::Dir));
*children.entry(parent).or_default() += 1;
oids.push(oid);
parents.push(parent);
}
// Each file's data stream: its own, or, for a clone, the one it shares.
let mut stream_of: Vec<Option<u64>> = vec![None; items.len()];
let mut refs: HashMap<u64, u32> = HashMap::new();
let mut len_of: HashMap<u64, u64> = HashMap::new();
let mut cloned: Vec<bool> = vec![false; items.len()];
let mut index_of: HashMap<u64, usize> = HashMap::new();
let mut built = Built {
records: Vec::new(),
streams: Vec::new(),
stream_items: Vec::new(),
counts: Counts::default(),
next_obj_id: next,
};
for (i, it) in items.iter().enumerate() {
index_of.insert(oids[i], i);
match &it.kind {
Kind::File { len } if *len > 0 => {
stream_of[i] = Some(oids[i]);
refs.insert(oids[i], 1);
len_of.insert(oids[i], *len);
built.streams.push(Stream {
id: oids[i],
owner: oids[i],
len: *len,
});
built.stream_items.push(i);
}
Kind::Clone(of) => {
let orig = oid_of
.get(of.as_str())
.and_then(|o| index_of.get(o).map(|&j| (*o, j)))
.filter(|&(o, j)| j < i && stream_of[j] == Some(o))
.ok_or_else(|| BuildError::BadClone(it.path.clone(), of.clone()))?;
stream_of[i] = Some(orig.0);
*refs.get_mut(&orig.0).expect("a stream's references") += 1;
cloned[i] = true;
cloned[orig.1] = true;
}
_ => {}
}
}
// The root directory, the private directory and their entries, then each item's.
let root_children = children.get(&ino::ROOT_DIR).copied().unwrap_or(0);
for (k, v) in records::empty_volume_records(fold, t) {
let (oid, kind) = crate::fs::key_header(&k);
if kind == rec::INODE && oid == ino::ROOT_DIR {
let mut v = v;
v[56..60].copy_from_slice(&(root_children as i32).to_le_bytes());
built.records.push((k, v));
} else {
built.records.push((k, v));
}
}
for (i, it) in items.iter().enumerate() {
let oid = oids[i];
let name = base_name(&it.path).as_bytes();
let (dtype, type_bits) = match it.kind {
Kind::Dir => (DT_DIR, 0o040000),
Kind::File { .. } | Kind::Clone(_) => (DT_REG, 0o100000),
Kind::Symlink(_) => (DT_LNK, 0o120000),
};
built
.records
.push(dir_rec(parents[i], name, fold, oid, t, dtype));
let mut xfields: Vec<XField> = vec![name_xfield(name)];
let mut private_id = oid;
if let Some(s) = stream_of[i] {
private_id = s;
let len = len_of[&s];
xfields.push(dstream_xfield(dstream(
len,
blocks_of(len) * super::geometry::BLOCK_SIZE,
0,
len,
0,
)));
}
let mut internal_flags = INODE_FLAGS_BASE;
if cloned[i] {
internal_flags |= INODE_WAS_CLONED | INODE_WAS_EVER_CLONED;
}
let nchildren = match it.kind {
Kind::Dir => children.get(&oid).copied().unwrap_or(0) as i32,
_ => 1,
};
built.records.push(
InodeBuilder {
oid,
parent: parents[i],
private_id,
create_time: t,
mod_time: t,
change_time: t,
access_time: t,
internal_flags,
nchildren_or_nlink: nchildren,
default_protection_class: 0,
write_generation_counter: 1,
bsd_flags: it.bsd_flags,
owner: it.uid,
group: it.gid,
mode: type_bits | (it.mode & 0o7777),
uncompressed_size: 0,
xfields,
}
.build(),
);
if stream_of[i] == Some(oid) {
built.records.push(dstream_id(oid, refs[&oid]));
}
if let Kind::Symlink(target) = &it.kind {
let mut v = target.clone();
v.push(0);
built.records.push(xattr(
oid,
SYMLINK_XATTR,
&v,
XATTR_EMBEDDED | XATTR_FS_OWNED,
));
}
for (n, v) in &it.xattrs {
if v.len() > MAX_EMBEDDED_XATTR {
return Err(BuildError::XattrTooBig(
it.path.clone(),
String::from_utf8_lossy(n).into_owned(),
v.len(),
));
}
built.records.push(xattr(oid, n, v, XATTR_EMBEDDED));
}
match it.kind {
Kind::Dir => built.counts.directories += 1,
Kind::File { .. } | Kind::Clone(_) => built.counts.files += 1,
Kind::Symlink(_) => built.counts.symlinks += 1,
}
}
built
.records
.sort_by(|a, b| crate::fs::compare_keys(&a.0, &b.0));
Ok(built)
}
@@ -0,0 +1,243 @@
//! Where a freshly formatted APFS container's structures go, computed from its block count the
//! way `newfs_apfs` sizes them (and `ferrosys`, whose formulas these match, records as observed
//! on every container macOS formats).
//!
//! A container of 4 KiB blocks is laid out from block 0: the container superblock, then the
//! checkpoint descriptor area, the checkpoint data area, the space manager's internal-pool bitmap
//! ring and its internal pool, and then — past the pool — the object maps, volumes and trees. The
//! descriptor and data areas are sized to hold the checkpoints a container is formatted with and
//! the room its free queues may grow into; the internal pool holds every chunk-info, address and
//! bitmap block three times over. This module computes those sizes and the first block past the
//! pool, where the writer begins placing everything else.
/// Every block is 4 KiB; the writer forms no other size.
pub const BLOCK_SIZE: u64 = 4096;
/// A chunk is a block's worth of bits: 32768 blocks.
pub const BLOCKS_PER_CHUNK: u64 = BLOCK_SIZE * 8;
/// A chunk-info block describes this many chunks (past its 40-byte header, 32 bytes each).
pub const CHUNKS_PER_CIB: u64 = (BLOCK_SIZE - 40) / 32;
/// A chunk-info address block holds this many addresses (past its 40-byte header, 8 bytes each).
pub const CIBS_PER_CAB: u64 = (BLOCK_SIZE - 40) / 8;
/// The internal-pool bitmap ring keeps sixteen slots per pool bitmap block.
pub const POOL_BITMAP_SLOTS: u64 = 16;
/// The fixed part of a `spaceman_phys`, where its trailing arrays begin.
pub const SPACEMAN_STRUCT_SIZE: u64 = 2520;
/// The most volumes a container records room for.
pub const MAX_VOLUMES: u64 = 100;
/// A volume slot is kept for every 512 MiB of container.
const BYTES_PER_VOLUME_SLOT: u64 = 512 << 20;
/// A checkpoint-mapping block maps this many objects (past its 40-byte header, 40 bytes each).
const MAPPINGS_PER_BLOCK: u64 = (BLOCK_SIZE - 40) / 40;
/// A free-queue node holds this many entries (past the node header, tree info and an uncounted
/// head, 28 bytes each).
const QUEUE_ENTRIES_PER_NODE: u64 = (BLOCK_SIZE - 56 - 40 - 24) / 28;
/// A free queue is held to two mebibytes of nodes.
const QUEUE_NODE_CAP: u64 = (2 << 20) / BLOCK_SIZE;
/// A container's layout: the counts and block addresses a fresh format places.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Geometry {
pub block_count: u64,
pub chunk_count: u64,
pub cib_count: u64,
pub cab_count: u64,
/// The internal pool's blocks (`sm_ip_block_count`).
pub pool_blocks: u64,
/// Pool bitmap blocks, each with sixteen ring slots (`sm_ip_bm_block_count` = 16× this).
pub pool_bitmaps: u64,
/// The checkpoint descriptor area, from block 1.
pub desc_blocks: u64,
/// The checkpoint data area, past the descriptor area.
pub data_base: u64,
pub data_blocks: u64,
/// The internal-pool bitmap ring, past the data area (`sm_ip_bm_base`).
pub pool_bitmap_base: u64,
/// The internal pool, past the bitmap ring (`sm_ip_base`).
pub pool_base: u64,
/// The first block past the pool, where object maps, volumes and trees begin.
pub first_free: u64,
/// Volume slots the container records room for (`nx_max_file_systems`).
pub max_volumes: u64,
/// The smaller of the main free queue's node limit and eight.
pub ephemeral_min_blocks: u64,
/// The internal pool's and main device's free-queue node limits.
pub fq_pool_limit: u64,
pub fq_main_limit: u64,
/// The space manager's fixed structure in blocks (one, for our sizes).
pub manager_blocks: u64,
/// The offsets of the space manager's trailing arrays.
pub xid_array_offset: u64,
pub slot_array_offset: u64,
pub free_list_offset: u64,
pub address_offset: u64,
pub second_address_offset: u64,
}
/// The node limit a free queue of `entries` entries takes, held to the two-mebibyte cap: a queue
/// that needs two nodes is given three, as `newfs_apfs` does.
fn queue_nodes(entries: u64) -> u64 {
let needed = entries.div_ceil(QUEUE_ENTRIES_PER_NODE).max(1);
let needed = if needed == 2 { 3 } else { needed };
needed.min(QUEUE_NODE_CAP)
}
/// The volume slots a container of `block_count` blocks is formatted with by default: one per
/// 512 MiB, at most 100. A container is given at least as many as the volumes it holds.
#[must_use]
pub fn volume_capacity(block_count: u64) -> u64 {
(block_count * BLOCK_SIZE)
.div_ceil(BYTES_PER_VOLUME_SLOT)
.min(MAX_VOLUMES)
}
impl Geometry {
/// The layout a container of `block_count` 4 KiB blocks is formatted with, with room for the
/// default number of volumes.
#[must_use]
pub fn of(block_count: u64) -> Self {
Self::with_max_volumes(block_count, volume_capacity(block_count))
}
/// The layout a container of `block_count` 4 KiB blocks is formatted with, with room for
/// `max_volumes` volumes — which sizes the checkpoint areas, so the writer gives a container
/// at least as many slots as it holds volumes.
#[must_use]
pub fn with_max_volumes(block_count: u64, max_volumes: u64) -> Self {
let chunk_count = block_count.div_ceil(BLOCKS_PER_CHUNK);
let cib_count = chunk_count.div_ceil(CHUNKS_PER_CIB);
let cab_count = if cib_count > CIBS_PER_CAB {
cib_count.div_ceil(CIBS_PER_CAB)
} else {
0
};
let pool_blocks = 3 * (chunk_count + cib_count + cab_count);
let pool_bitmaps = pool_blocks.div_ceil(BLOCKS_PER_CHUNK);
let slots = POOL_BITMAP_SLOTS * pool_bitmaps;
let listed = if cab_count > 0 { cab_count } else { cib_count };
// The space manager's trailing arrays, and the block it needs.
let xid_array_offset = SPACEMAN_STRUCT_SIZE;
let slot_array_offset = xid_array_offset + 8 * pool_bitmaps;
let free_list_offset = slot_array_offset + (2 * pool_bitmaps).div_ceil(8) * 8;
let address_offset = free_list_offset + (2 * slots).div_ceil(8) * 8;
let second_address_offset = address_offset + 8 * listed;
let manager_blocks = second_address_offset.div_ceil(BLOCK_SIZE);
let fq_pool_limit = queue_nodes(pool_blocks.div_ceil(8));
let share = match block_count {
n if n < 1 << 18 => 32,
n if n < 1 << 20 => 16,
_ => 8,
};
let fq_main_limit = queue_nodes(block_count.div_ceil(share));
let ephemeral_min_blocks = fq_main_limit.min(8);
// The data area holds the checkpoints and the room the free queues may grow into; the
// descriptor area holds enough mapping blocks to map all of it, rounded up to four, and
// four more.
let data_blocks = 4
+ 8 * manager_blocks
+ 32 * ephemeral_min_blocks * max_volumes
+ 4 * (fq_pool_limit + fq_main_limit);
let map_blocks = data_blocks.div_ceil(MAPPINGS_PER_BLOCK);
let desc_blocks = 4 * map_blocks.div_ceil(4) + 4;
let data_base = 1 + desc_blocks;
let pool_bitmap_base = data_base + data_blocks;
let pool_base = pool_bitmap_base + slots;
let first_free = pool_base + pool_blocks;
Self {
block_count,
chunk_count,
cib_count,
cab_count,
pool_blocks,
pool_bitmaps,
desc_blocks,
data_base,
data_blocks,
pool_bitmap_base,
pool_base,
first_free,
max_volumes,
ephemeral_min_blocks,
fq_pool_limit,
fq_main_limit,
manager_blocks,
xid_array_offset,
slot_array_offset,
free_list_offset,
address_offset,
second_address_offset,
}
}
/// The ring slots the pool bitmap area holds (`sm_ip_bm_block_count`).
#[must_use]
pub const fn pool_bitmap_slots(&self) -> u64 {
POOL_BITMAP_SLOTS * self.pool_bitmaps
}
}
#[cfg(test)]
mod tests {
use super::*;
// Every value measured on a container diskutil/newfs formatted, or formatted by ferrosys
// (which matches newfs): the iBoot system container (500 MiB), the recoveryOS container
// (~5 GiB), a 60 GiB main container, and a 256 GiB one.
#[test]
fn geometry_matches_formatted_containers() {
let isc = Geometry::of(128_000);
assert_eq!(isc.chunk_count, 4);
assert_eq!(isc.cib_count, 1);
assert_eq!(isc.pool_blocks, 15);
assert_eq!((isc.desc_blocks, isc.data_blocks), (8, 388));
assert_eq!(
(isc.data_base, isc.pool_bitmap_base, isc.pool_base),
(9, 397, 413)
);
assert_eq!((isc.fq_pool_limit, isc.fq_main_limit), (1, 29));
assert_eq!(isc.max_volumes, 1);
assert_eq!(isc.address_offset, 2568);
assert_eq!(isc.second_address_offset, 2576);
let recos = Geometry::of(1_310_710);
assert_eq!(
(recos.chunk_count, recos.cib_count, recos.pool_blocks),
(40, 1, 123)
);
assert_eq!((recos.desc_blocks, recos.data_blocks), (52, 4624));
assert_eq!((recos.pool_bitmap_base, recos.pool_base), (4677, 4693));
assert_eq!((recos.fq_pool_limit, recos.fq_main_limit), (1, 512));
assert_eq!(recos.max_volumes, 10);
let main = Geometry::of(15_333_160);
assert_eq!(
(main.chunk_count, main.cib_count, main.pool_blocks),
(468, 4, 1416)
);
assert_eq!((main.desc_blocks, main.data_blocks), (280, 27672));
assert_eq!((main.pool_bitmap_base, main.pool_base), (27953, 27969));
assert_eq!((main.fq_pool_limit, main.fq_main_limit), (3, 512));
assert_eq!(main.max_volumes, 100);
assert_eq!(main.second_address_offset, 2600);
let big = Geometry::of(67_108_864);
assert_eq!(
(big.chunk_count, big.cib_count, big.pool_blocks),
(2048, 17, 6195)
);
assert_eq!((big.desc_blocks, big.data_blocks), (280, 27684));
assert_eq!((big.fq_pool_limit, big.fq_main_limit), (6, 512));
}
#[test]
fn the_pool_is_marked_used_and_everything_else_is_free() {
// Chunk 0 holds every structure through the pool; the writer then places objects from
// first_free. For the iBoot container the pool ends at 428, as the formatted one's does.
let isc = Geometry::of(128_000);
assert_eq!(isc.first_free, 428);
}
}
+663
View File
@@ -0,0 +1,663 @@
//! Writing APFS: building a container's structures block by block, from the file-system records
//! up, as a restore writes a guest's disk without any of Apple's tools.
//!
//! The pieces are built bottom-up. [`node`] serialises one B-tree node; [`records`] builds the
//! file-system records a volume holds. Higher layers — the volume's trees, the container's
//! space manager and object map, and the whole disk — are added as the writer grows.
pub mod copy;
pub mod fsbuild;
pub mod geometry;
pub mod node;
pub mod records;
pub mod sealed;
pub mod space;
pub mod tree;
pub mod volume;
use crate::ondisk::apfs;
/// A bare container of `block_count` 4 KiB blocks, identified by `uuid`, holding no volume — the
/// state a freshly formatted container is in before a volume is added. Returns the blocks it
/// writes, as (block address, bytes); every other block of the container is zero.
#[must_use]
pub fn bare_container(block_count: u64, uuid: [u8; 16]) -> Vec<(u64, Vec<u8>)> {
// Past the internal pool the container object map takes two blocks, its object and its tree.
let g = geometry::Geometry::of(block_count);
space::scaffold(&g, uuid, &[], &[], space::FIRST_VOLUME_OID, 2)
}
/// A volume to place in a container: its name, identifier, role and group, its features, and
/// its file-system records (but file extents) and data streams, as [`fsbuild::build`] makes them
/// from a tree of files.
pub struct VolumeDef<'a> {
pub name: &'a str,
pub uuid: [u8; 16],
pub role: u16,
/// Whether it is a volume group's System volume, which carries the group feature.
pub system: bool,
/// The volume group's identifier, or zero.
pub group: [u8; 16],
pub records: Vec<(Vec<u8>, Vec<u8>)>,
pub streams: Vec<volume::Stream>,
pub counts: volume::Counts,
pub next_obj_id: u64,
/// A sealed volume's seal, in place of `records` and `streams`.
pub seal: Option<sealed::Seal>,
}
impl<'a> VolumeDef<'a> {
/// A volume holding the tree `built`.
#[must_use]
pub fn of(name: &'a str, uuid: [u8; 16], role: u16, built: fsbuild::Built) -> Self {
Self {
name,
uuid,
role,
system: false,
group: [0; 16],
records: built.records,
streams: built.streams,
counts: built.counts,
next_obj_id: built.next_obj_id,
seal: None,
}
}
/// A sealed system volume of `seal`, in volume group `group`.
#[must_use]
pub fn sealed(
name: &'a str,
uuid: [u8; 16],
group: [u8; 16],
counts: volume::Counts,
seal: sealed::Seal,
) -> Self {
Self {
name,
uuid,
role: apfs::ROLE_SYSTEM,
system: true,
group,
records: Vec::new(),
streams: Vec::new(),
counts,
next_obj_id: seal.inum + 1,
seal: Some(seal),
}
}
}
/// A formed container: the blocks of its structures (block, bytes), every other block zero, and
/// for each volume the first block of each of its streams, where the caller writes the stream's
/// bytes (0 for an empty one).
pub struct Formed {
pub blocks: Vec<(u64, Vec<u8>)>,
pub stream_blocks: Vec<Vec<u64>>,
}
/// A container of `block_count` 4 KiB blocks holding `volumes`, each placed past the container's
/// object map in the order given, and recording `t` (nanoseconds since 1970) as when each volume
/// was formatted and last changed.
///
/// # Errors
///
/// [`tree::TreeError`] when the volumes do not fit the container.
pub fn container(
block_count: u64,
uuid: [u8; 16],
t: u64,
volumes: Vec<VolumeDef>,
) -> Result<Formed, tree::TreeError> {
// A container is given at least as many volume slots as it holds, which sizes its checkpoint
// areas; one geometry is shared by the scaffold and the volume placement.
let max_volumes = geometry::volume_capacity(block_count).max(volumes.len() as u64);
let g = geometry::Geometry::with_max_volumes(block_count, max_volumes);
// The container object map takes the first two blocks past the pool; the volumes follow.
let mut alloc = tree::Alloc::new(g.first_free + 2, block_count);
let mut next_oid = space::FIRST_VOLUME_OID;
let mut blocks: Vec<(u64, Vec<u8>)> = Vec::new();
let mut omap_entries: Vec<(Vec<u8>, Vec<u8>)> = Vec::new();
let mut fs_oids: Vec<u64> = Vec::new();
let mut stream_blocks = Vec::new();
for (i, def) in volumes.into_iter().enumerate() {
let features = if def.system { 0x12 } else { 0x2 };
if let Some(seal) = def.seal {
let built = sealed::sealed_volume(
sealed::SealedSpec {
index: i as u32,
name: def.name,
uuid: def.uuid,
role: def.role,
features,
group: def.group,
t,
counts: def.counts,
seal,
},
&mut alloc,
&mut next_oid,
)?;
blocks.extend(built.blocks);
omap_entries.push(built.container_omap_record);
fs_oids.push(built.sb_oid);
stream_blocks.push(built.stream_blocks);
continue;
}
let built = volume::volume(
volume::VolumeSpec {
index: i as u32,
name: def.name,
uuid: def.uuid,
role: def.role,
features,
incompat: apfs::INCOMPAT_CASE_INSENSITIVE,
next_obj_id: def.next_obj_id,
group: def.group,
t,
records: def.records,
streams: &def.streams,
counts: def.counts,
},
&mut alloc,
&mut next_oid,
)?;
blocks.extend(built.blocks);
omap_entries.push(built.container_omap_record);
fs_oids.push(built.sb_oid);
stream_blocks.push(built.stream_blocks);
}
// The container object map's records order by their two-word key (identifier, transaction).
omap_entries.sort_by(|a, b| crate::fs::compare_u64_pairs(&a.0, &b.0));
let used_after_pool = alloc.next() - g.first_free;
let mut out = space::scaffold(&g, uuid, &omap_entries, &fs_oids, next_oid, used_after_pool);
out.extend(blocks);
Ok(Formed {
blocks: out,
stream_blocks,
})
}
/// A fixed instant in 2026 (nanoseconds since 1970) for the writer's tests and tools.
pub const FORMAT_TIME: u64 = 1_793_000_000_000_000_000;
/// Write `blocks` (block address, bytes) into `sink`, a destination already the container's full
/// size and reading back as zero where nothing is written, so it stays sparse.
///
/// # Errors
///
/// Any write or seek error from `sink`.
pub fn write_blocks<W: std::io::Write + std::io::Seek>(
sink: &mut W,
blocks: &[(u64, Vec<u8>)],
) -> std::io::Result<()> {
for (addr, bytes) in blocks {
sink.seek(std::io::SeekFrom::Start(addr * geometry::BLOCK_SIZE))?;
sink.write_all(bytes)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::node::{Layout, NodeSpec};
use super::records::{self, DT_DIR, InodeBuilder, name_xfield};
use std::collections::HashMap;
use std::sync::Arc;
/// A container held as only the blocks written to it, the rest zero — so a reader touches a
/// handful of blocks without the whole container existing in memory.
struct SparseBlocks {
blocks: HashMap<u64, Vec<u8>>,
len: u64,
}
impl SparseBlocks {
fn of(block_count: u64, written: Vec<(u64, Vec<u8>)>) -> Self {
Self {
blocks: written.into_iter().collect(),
len: block_count * super::geometry::BLOCK_SIZE,
}
}
}
impl crate::dev::Source for SparseBlocks {
fn read_at(&self, off: u64, buf: &mut [u8]) -> std::io::Result<()> {
let bs = super::geometry::BLOCK_SIZE as usize;
let mut done = 0usize;
while done < buf.len() {
let pos = off as usize + done;
let (blk, within) = ((pos / bs) as u64, pos % bs);
let n = (bs - within).min(buf.len() - done);
match self.blocks.get(&blk) {
Some(data) => buf[done..done + n].copy_from_slice(&data[within..within + n]),
None => buf[done..done + n].fill(0),
}
done += n;
}
Ok(())
}
fn len(&self) -> u64 {
self.len
}
}
// A bare container the writer builds opens as an APFS container with no volumes, its object
// map and space manager read and checked by the reader (checksums, identifiers, transactions).
#[test]
fn a_bare_container_opens_and_reads() {
let block_count = 128_000; // the iBoot system container's size
let blocks = super::bare_container(block_count, [0x33; 16]);
let src = Arc::new(SparseBlocks::of(block_count, blocks));
let c = crate::open(src).expect("open the bare container");
assert_eq!(c.volumes().expect("list volumes").len(), 0);
}
// A container with two empty volumes opens, lists them by name, and reads each one's
// file-system records (its root and private directories) back through the reader.
#[test]
fn a_container_with_volumes_opens_and_reads() {
let block_count = 128_000;
let empty = || super::fsbuild::build(&[], true, super::FORMAT_TIME).unwrap();
let mut system = super::VolumeDef::of(
"Macintosh HD",
[0x11; 16],
crate::ondisk::apfs::ROLE_SYSTEM,
empty(),
);
system.system = true;
let vols = vec![
system,
super::VolumeDef::of(
"Preboot",
[0x22; 16],
crate::ondisk::apfs::ROLE_PREBOOT,
empty(),
),
];
let formed = super::container(block_count, [0x33; 16], super::FORMAT_TIME, vols).unwrap();
let src = Arc::new(SparseBlocks::of(block_count, formed.blocks));
let c = crate::open(src).expect("open the container");
let names: Vec<String> = c
.volumes()
.expect("list volumes")
.iter()
.map(|v| v.name().to_owned())
.collect();
assert_eq!(names, ["Macintosh HD", "Preboot"]);
let recs = c.volumes().unwrap()[1]
.fs_tree_records()
.expect("read Preboot's records");
assert_eq!(recs.len(), 4); // two directory entries and two inodes
}
/// A tree of directories, files of many sizes, empty files, symbolic links, attributes and a
/// clone, big enough that every tree of the volume has index nodes, and the bytes of each
/// file.
pub(super) fn many_files(n: usize) -> (Vec<super::fsbuild::Item>, Vec<Vec<u8>>) {
use super::fsbuild::{Item, Kind};
let item = |path: String, kind: Kind, mode: u16| Item {
path,
kind,
mode,
uid: 0,
gid: 0,
bsd_flags: 0,
xattrs: Vec::new(),
};
let mut items = Vec::new();
let mut bytes = Vec::new();
let dir = |items: &mut Vec<Item>, bytes: &mut Vec<Vec<u8>>, p: &str| {
items.push(item(p.to_owned(), Kind::Dir, 0o755));
bytes.push(Vec::new());
};
dir(&mut items, &mut bytes, "top");
for d in 0..8 {
dir(&mut items, &mut bytes, &format!("top/sub{d}"));
}
for i in 0..n {
let len = (i * 997) % 20_000;
let body: Vec<u8> = (0..len).map(|j| (i + j * 31) as u8).collect();
let mut it = item(
format!("top/sub{}/file-{i:05}", i % 8),
Kind::File { len: len as u64 },
0o644,
);
if i % 50 == 0 {
it.xattrs
.push((b"com.example.tag".to_vec(), format!("tag {i}").into_bytes()));
}
items.push(it);
bytes.push(body);
if i % 100 == 0 {
items.push(item(
format!("top/link-{i:05}"),
Kind::Symlink(format!("sub{}/file-{i:05}", i % 8).into_bytes()),
0o755,
));
bytes.push(Vec::new());
}
}
// A clone of a file with bytes.
let orig = items
.iter()
.position(|it| matches!(it.kind, Kind::File { len } if len > 0))
.unwrap();
let orig_path = items[orig].path.clone();
let orig_bytes = bytes[orig].clone();
items.push(item("top/the-clone".into(), Kind::Clone(orig_path), 0o644));
bytes.push(orig_bytes);
(items, bytes)
}
/// Form a container of one volume holding `items`, writing each stream's bytes, as a sparse
/// set of blocks.
pub(super) fn form_with_files(
block_count: u64,
items: &[super::fsbuild::Item],
bytes: &[Vec<u8>],
) -> HashMap<u64, Vec<u8>> {
let built = super::fsbuild::build(items, true, super::FORMAT_TIME).unwrap();
let stream_items = built.stream_items.clone();
let def = super::VolumeDef::of("Files", [0x44; 16], crate::ondisk::apfs::ROLE_NONE, built);
let formed =
super::container(block_count, [0x55; 16], super::FORMAT_TIME, vec![def]).unwrap();
let mut blocks: HashMap<u64, Vec<u8>> = formed.blocks.into_iter().collect();
for (s, &first) in formed.stream_blocks[0].iter().enumerate() {
let data = &bytes[stream_items[s]];
for (k, chunk) in data.chunks(4096).enumerate() {
let mut b = chunk.to_vec();
b.resize(4096, 0);
blocks.insert(first + k as u64, b);
}
}
blocks
}
// A volume of thousands of files reads back through the reader: every file's bytes, every
// link's target, the clone's bytes, and the attributes.
#[test]
fn a_volume_of_many_files_reads_back() {
use super::fsbuild::Kind;
let block_count = 128_000;
let (items, bytes) = many_files(3000);
let blocks = form_with_files(block_count, &items, &bytes);
let src = Arc::new(SparseBlocks {
blocks,
len: block_count * super::geometry::BLOCK_SIZE,
});
let c = crate::open(src).expect("open the container");
let vols = c.volumes().unwrap();
let v = &vols[0];
let shape = v.fs_tree_shape().unwrap();
assert!(
shape.iter().any(|n| n.level > 0),
"the file-system tree has index nodes"
);
for (it, want) in items.iter().zip(&bytes) {
let path = format!("/{}", it.path);
match &it.kind {
Kind::File { .. } | Kind::Clone(_) => {
let got = v.read_file(&path).unwrap_or_else(|e| panic!("{path}: {e}"));
assert!(
got == *want,
"{path}: {} bytes read, {} written",
got.len(),
want.len()
);
}
_ => {}
}
}
}
// A sealed system volume of thousands of files reads back through its seal: the reader
// checks every node of the hashed tree against its parent's entry and the root against the
// integrity metadata, and reads every file's bytes through the file-extent tree.
#[test]
fn a_sealed_volume_reads_back_through_its_seal() {
use super::fsbuild::Kind;
use super::sealed::Seal;
use super::volume::Stream;
use crate::seal::{self, Record};
let block_count = 128_000;
let (all, all_bytes) = many_files(3000);
// A sealed set gives a cloned stream once; this volume holds none.
let keep: Vec<usize> = (0..all.len())
.filter(|&i| !matches!(all[i].kind, Kind::Clone(_)))
.collect();
let items: Vec<_> = keep.iter().map(|&i| all[i].clone()).collect();
let bytes: Vec<_> = keep.iter().map(|&i| all_bytes[i].clone()).collect();
let built = super::fsbuild::build(&items, true, super::FORMAT_TIME).unwrap();
let mut recs: Vec<Record> = built
.records
.iter()
.map(|(k, v)| Record {
key: k.clone(),
val: v.clone(),
})
.collect();
for (st, &it) in built.streams.iter().zip(&built.stream_items) {
recs.extend(crate::canon::file_infos(st.id, &bytes[it], 4096));
}
recs.sort_by(|a, b| crate::fs::compare_keys(&a.key, &b.key));
let tree = seal::build(&recs, 0);
let hash = tree.root_hash;
assert!(
tree.nodes.iter().any(|n| n.level > 1),
"the hashed tree has two index levels"
);
let streams = built
.streams
.iter()
.map(|s| Stream {
id: s.id,
owner: s.owner,
len: s.len.div_ceil(4096) * 4096,
})
.collect();
let seal = Seal {
tree,
streams,
snapshot: "com.apple.os.update-test".into(),
snapshot_uuid: [0x66; 16],
inum: built.next_obj_id,
next_doc_id: 3,
};
let def =
super::VolumeDef::sealed("Macintosh HD", [0x44; 16], [0x77; 16], built.counts, seal);
let formed =
super::container(block_count, [0x55; 16], super::FORMAT_TIME, vec![def]).unwrap();
let mut blocks: HashMap<u64, Vec<u8>> = formed.blocks.into_iter().collect();
for (s, &first) in formed.stream_blocks[0].iter().enumerate() {
for (k, chunk) in bytes[built.stream_items[s]].chunks(4096).enumerate() {
let mut b = chunk.to_vec();
b.resize(4096, 0);
blocks.insert(first + k as u64, b);
}
}
let c = crate::open(Arc::new(SparseBlocks {
blocks,
len: block_count * super::geometry::BLOCK_SIZE,
}))
.expect("open the container");
let v = c.system_volume().unwrap();
assert_eq!(
v.root_hash(),
Some(&hash[..]),
"the integrity metadata's root hash"
);
let got = v
.fs_tree_records()
.expect("read the hashed tree, every node checked");
assert_eq!(got.len(), recs.len());
assert!(
got.iter()
.zip(&recs)
.all(|((k, v), r)| *k == r.key && *v == r.val)
);
for (it, want) in items.iter().zip(&bytes) {
if let Kind::File { .. } = it.kind {
let path = format!("/{}", it.path);
let got = v.read_file(&path).unwrap_or_else(|e| panic!("{path}: {e}"));
assert!(
got == *want,
"{path}: {} bytes read, {} written",
got.len(),
want.len()
);
}
}
let facts = v.seal_facts().unwrap();
assert!(
facts.fext_root_has_object_header,
"the file-extent tree is outside the seal"
);
assert!(
!facts
.fs_record_types
.contains_key(&crate::ondisk::rec::FILE_EXTENT)
);
}
fn unhex(s: &str) -> Vec<u8> {
(0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
.collect()
}
// The four records of a freshly made volume, read off a container `diskutil` formatted
// (`/tmp/rvg-r1/ref-fresh/vols.raw`, volume 0's file-system tree). Times differ between the
// root and the private directory, so each record carries its own.
const ROOT_T: u64 = 0x18e7_3f55_80a3_e8bb;
const PRIV_T: u64 = 0x18e7_3f55_80a3_fd13;
#[test]
fn a_directory_entry_matches_a_formatted_volumes() {
let (k, v) = records::dir_rec(1, b"root", true, 2, ROOT_T, DT_DIR);
assert_eq!(k, unhex("010000000000009005e471b6726f6f7400"));
assert_eq!(v, unhex("0200000000000000bbe8a380553fe7180400"));
let (k, v) = records::dir_rec(1, b"private-dir", true, 3, PRIV_T, DT_DIR);
assert_eq!(k, unhex("01000000000000900c8ca6ac707269766174652d64697200"));
assert_eq!(v, unhex("030000000000000013fda380553fe7180400"));
}
fn fresh_dir(oid: u64, name: &[u8], t: u64, mode: u16) -> InodeBuilder {
InodeBuilder {
oid,
parent: 1,
private_id: oid,
create_time: t,
mod_time: t,
change_time: t,
access_time: t,
internal_flags: records::INODE_FLAGS_BASE,
nchildren_or_nlink: 0,
default_protection_class: 0,
write_generation_counter: 1,
bsd_flags: 0,
owner: 0,
group: 0,
mode,
uncompressed_size: 0,
xfields: vec![name_xfield(name)],
}
}
#[test]
fn an_inode_matches_a_formatted_volumes() {
let (k, v) = fresh_dir(2, b"root", ROOT_T, 0o040755).build();
assert_eq!(k, unhex("0200000000000030"));
assert_eq!(
v,
unhex(
"01000000000000000200000000000000bbe8a380553fe718bbe8a380553fe718bbe8a380553fe718\
bbe8a380553fe7180080000000000000000000000000000001000000000000000000000000000000\
ed41000000000000000000000100080004020500726f6f7400000000"
)
);
let (k, v) = fresh_dir(3, b"private-dir", PRIV_T, 0o040644).build();
assert_eq!(k, unhex("0300000000000030"));
assert_eq!(
v,
unhex(
"0100000000000000030000000000000013fda380553fe71813fda380553fe71813fda380553fe718\
13fda380553fe7180080000000000000000000000000000001000000000000000000000000000000\
a441000000000000000000000100100004020c00707269766174652d6469720000000000"
)
);
}
// A root-and-leaf node of the four records lays out exactly as the formatted volume's does:
// table of contents 64 bytes, keys 57, the free gap, then the values, and a valid checksum.
#[test]
fn an_empty_volume_node_lays_out_as_a_formatted_ones() {
let recs = records::empty_volume_records(true, ROOT_T);
let longest_key = recs.iter().map(|(k, _)| k.len()).max().unwrap() as u32;
let longest_val = recs.iter().map(|(_, v)| v.len()).max().unwrap() as u32;
let node = NodeSpec {
obj_type: 0x0000_0002, // virtual B-tree
subtype: 0x0e, // file-system tree
oid: 0x404,
xid: 2,
level: 0,
is_root: true,
headerless: false,
hashed: false,
layout: Layout::Variable,
tree_flags: 0x42,
longest_key,
longest_val,
key_count: recs.len() as u64,
node_count: 1,
entries: &recs,
}
.build();
assert_eq!(node.len(), 4096);
assert!(crate::fletcher::verify(&node));
// Header, flags, level and key count.
assert_eq!(u32::from_le_bytes(node[24..28].try_into().unwrap()), 0x02);
assert_eq!(u32::from_le_bytes(node[28..32].try_into().unwrap()), 0x0e);
assert_eq!(u16::from_le_bytes(node[32..34].try_into().unwrap()), 0x3); // root|leaf
assert_eq!(u16::from_le_bytes(node[34..36].try_into().unwrap()), 0); // level
assert_eq!(u32::from_le_bytes(node[36..40].try_into().unwrap()), 4); // nkeys
// Table of contents: offset 0, length 64. Free gap starts at 57 (the key bytes).
assert_eq!(u16::from_le_bytes(node[40..42].try_into().unwrap()), 0);
assert_eq!(u16::from_le_bytes(node[42..44].try_into().unwrap()), 64);
assert_eq!(u16::from_le_bytes(node[44..46].try_into().unwrap()), 57);
assert_eq!(longest_key, 24);
assert_eq!(longest_val, 116);
// The tree info at the end: flags 0x42, node size 4096, 4 keys, 1 node.
let info = 4096 - 40;
assert_eq!(
u32::from_le_bytes(node[info..info + 4].try_into().unwrap()),
0x42
);
assert_eq!(
u64::from_le_bytes(node[info + 24..info + 32].try_into().unwrap()),
4
);
assert_eq!(
u64::from_le_bytes(node[info + 32..info + 40].try_into().unwrap()),
1
);
// Keys ascend by the file-system key order.
let ks = 56 + 64;
let mut prev: Option<Vec<u8>> = None;
for i in 0..4 {
let (ko, kl) = (
u16::from_le_bytes(node[56 + 8 * i..58 + 8 * i].try_into().unwrap()) as usize,
u16::from_le_bytes(node[58 + 8 * i..60 + 8 * i].try_into().unwrap()) as usize,
);
let key = node[ks + ko..ks + ko + kl].to_vec();
if let Some(p) = &prev {
assert_eq!(crate::fs::compare_keys(p, &key), std::cmp::Ordering::Less);
}
prev = Some(key);
}
}
}
+227
View File
@@ -0,0 +1,227 @@
//! Serialising one APFS B-tree node — its header, table of contents, keys and values, and, for a
//! root, the tree info at the end — laid out as `read.rs` reads one back and as Apple's own nodes
//! are (Apple File System Reference, "B-Trees").
//!
//! A node is one 4 KiB block. Its 32-byte object header carries a Fletcher-64 checksum, its
//! identifier, transaction, type and subtype, unless the tree is headerless (a sealed volume's
//! file-system tree), when the first 32 bytes stay zero and the node is hashed into its parent
//! instead. Past the header sit the flags, level and key count, the locations of the table of
//! contents, the free gap and the two free lists, then the data area: the table of contents, the
//! keys packed upward, the free gap, and the values packed downward from the end (before the tree
//! info of a root).
use crate::fletcher;
use crate::ondisk::btree;
/// A node is one block.
pub const BLOCK: usize = 4096;
/// The data area begins past the 56-byte node header.
const DATA: usize = btree::DATA;
/// The tree info at the end of a root node.
const INFO: usize = btree::INFO_SIZE;
/// How a node stores its keys and values.
#[derive(Clone, Copy, Debug)]
pub enum Layout {
/// Keys and values of varying size; each table entry is four 16-bit offsets and lengths
/// (key offset, key length, value offset, value length).
Variable,
/// Keys and values of one size each, kept in the tree info; each table entry is two 16-bit
/// offsets (key offset, value offset).
Fixed { key_size: u16, val_size: u16 },
}
impl Layout {
/// The table of contents' size in bytes for a node of `nkeys` entries, for a root (or not).
///
/// A variable tree grows its table in 64-byte chunks of eight 8-byte entries, with one chunk
/// the minimum. A fixed tree sizes its table to the node's full capacity — as many fixed
/// entries as the block holds past the header and the tree info — rounded up to 64 bytes, so
/// a node can fill without growing it.
fn toc_bytes(self, nkeys: usize, is_root: bool, level: u16) -> usize {
match self {
Self::Variable => nkeys.div_ceil(8).max(1) * 64,
Self::Fixed { .. } => (self.capacity(is_root, level) * 4).div_ceil(64) * 64,
}
}
/// The entries a node of a fixed tree holds: as many as fit past the header (and a root's
/// tree info), each a 4-byte table entry, a key and a value — the value of an index node
/// being a child's 8-byte identifier rather than a leaf's value. Unbounded for a variable
/// tree, whose nodes fill by bytes.
#[must_use]
pub fn capacity(self, is_root: bool, level: u16) -> usize {
match self {
Self::Variable => usize::MAX,
Self::Fixed { key_size, val_size } => {
let tail = if is_root { INFO } else { 0 };
let val = if level == 0 { usize::from(val_size) } else { 8 };
(BLOCK - DATA - tail) / (4 + usize::from(key_size) + val)
}
}
}
/// Whether `nkeys` entries of `keybytes` and `valbytes` in all fit one node.
#[must_use]
pub fn fits(
self,
nkeys: usize,
keybytes: usize,
valbytes: usize,
is_root: bool,
level: u16,
) -> bool {
match self {
Self::Variable => {
let tail = if is_root { INFO } else { 0 };
DATA + self.toc_bytes(nkeys, is_root, level) + keybytes + valbytes + tail <= BLOCK
}
Self::Fixed { .. } => nkeys <= self.capacity(is_root, level),
}
}
const fn is_fixed(self) -> bool {
matches!(self, Self::Fixed { .. })
}
}
/// What a node is built from.
pub struct NodeSpec<'a> {
/// The object type with its storage flags (`0x4000_0002` physical, `0x0000_0002` virtual),
/// or `0x03` for a non-root node. Ignored where the tree is headerless.
pub obj_type: u32,
/// The tree's subtype: omap `0x0b`, file-system tree `0x0e`, extent reference `0x0f`,
/// snapshot metadata `0x10`, file-extent tree `0x1f`.
pub subtype: u32,
/// The node's identifier: a physical node's block address, a virtual node's object
/// identifier. Ignored where the tree is headerless.
pub oid: u64,
/// The transaction that wrote it.
pub xid: u64,
/// 0 for a leaf, rising toward the root.
pub level: u16,
/// Whether this is the tree's root, which carries the tree info.
pub is_root: bool,
/// Whether the tree is headerless (a sealed file-system tree), its first 32 bytes left zero.
pub headerless: bool,
/// Whether each index entry carries the hash of its child (a sealed file-system tree).
pub hashed: bool,
/// How keys and values are stored.
pub layout: Layout,
/// The B-tree info flags, where this is a root (`0x12` omap, `0x42` file-system tree, `0x52`
/// extent reference and snapshot metadata, `0x1c2` a sealed file-system tree).
pub tree_flags: u32,
/// The longest key and value in the whole tree, for the tree info.
pub longest_key: u32,
pub longest_val: u32,
/// The number of leaf records and of nodes in the whole tree, for the tree info.
pub key_count: u64,
pub node_count: u64,
/// The node's entries, already in key order.
pub entries: &'a [(Vec<u8>, Vec<u8>)],
}
impl NodeSpec<'_> {
/// Serialise the node into one block.
#[must_use]
pub fn build(&self) -> Vec<u8> {
let mut b = vec![0u8; BLOCK];
let nkeys = self.entries.len();
let is_leaf = self.level == 0;
let mut flags = 0u16;
if self.is_root {
flags |= btree::NODE_ROOT;
}
if is_leaf {
flags |= btree::NODE_LEAF;
}
if self.layout.is_fixed() {
flags |= btree::NODE_FIXED_KV_SIZE;
}
if self.hashed {
flags |= btree::NODE_HASHED;
}
if self.headerless {
flags |= btree::NODE_NOHEADER;
}
b[btree::FLAGS..btree::FLAGS + 2].copy_from_slice(&flags.to_le_bytes());
b[btree::LEVEL..btree::LEVEL + 2].copy_from_slice(&self.level.to_le_bytes());
b[btree::NKEYS..btree::NKEYS + 4].copy_from_slice(&(nkeys as u32).to_le_bytes());
let toc = self.layout.toc_bytes(nkeys, self.is_root, self.level);
// btn_table_space: offset 0 from the data area, length the table size.
b[btree::TABLE_SPACE..btree::TABLE_SPACE + 2].copy_from_slice(&0u16.to_le_bytes());
b[btree::TABLE_SPACE + 2..btree::TABLE_SPACE + 4]
.copy_from_slice(&(toc as u16).to_le_bytes());
let kbase = DATA + toc;
let val_end = BLOCK - if self.is_root { INFO } else { 0 };
let keybytes: usize = self.entries.iter().map(|(k, _)| k.len()).sum();
let valbytes: usize = self.entries.iter().map(|(_, v)| v.len()).sum();
// btn_free_space: offset from the key area where the gap starts (past the keys), length
// the gap between the keys and the values.
let free_off = keybytes;
let free_len = (val_end - valbytes) - (kbase + keybytes);
b[btree::FREE_SPACE..btree::FREE_SPACE + 2]
.copy_from_slice(&(free_off as u16).to_le_bytes());
b[btree::FREE_SPACE + 2..btree::FREE_SPACE + 4]
.copy_from_slice(&(free_len as u16).to_le_bytes());
// Both free lists empty: our nodes carry no freed fragments.
b[btree::KEY_FREE_LIST..btree::KEY_FREE_LIST + 2]
.copy_from_slice(&btree::OFF_INVALID.to_le_bytes());
b[btree::KEY_FREE_LIST + 2..btree::KEY_FREE_LIST + 4].copy_from_slice(&0u16.to_le_bytes());
b[btree::VAL_FREE_LIST..btree::VAL_FREE_LIST + 2]
.copy_from_slice(&btree::OFF_INVALID.to_le_bytes());
b[btree::VAL_FREE_LIST + 2..btree::VAL_FREE_LIST + 4].copy_from_slice(&0u16.to_le_bytes());
// Keys packed upward from the key area; values packed downward from the value-area end.
let fixed = self.layout.is_fixed();
let mut koff = 0usize;
let mut voff = 0usize;
for (i, (k, v)) in self.entries.iter().enumerate() {
let ko = koff;
b[kbase + ko..kbase + ko + k.len()].copy_from_slice(k);
voff += v.len();
let vo = voff;
b[val_end - vo..val_end - vo + v.len()].copy_from_slice(v);
if fixed {
let t = DATA + i * 4;
b[t..t + 2].copy_from_slice(&(ko as u16).to_le_bytes());
b[t + 2..t + 4].copy_from_slice(&(vo as u16).to_le_bytes());
} else {
let t = DATA + i * 8;
b[t..t + 2].copy_from_slice(&(ko as u16).to_le_bytes());
b[t + 2..t + 4].copy_from_slice(&(k.len() as u16).to_le_bytes());
b[t + 4..t + 6].copy_from_slice(&(vo as u16).to_le_bytes());
b[t + 6..t + 8].copy_from_slice(&(v.len() as u16).to_le_bytes());
}
koff += k.len();
}
if self.is_root {
let (ks, vs) = match self.layout {
Layout::Variable => (0u32, 0u32),
Layout::Fixed { key_size, val_size } => (u32::from(key_size), u32::from(val_size)),
};
let info = BLOCK - INFO;
b[info..info + 4].copy_from_slice(&self.tree_flags.to_le_bytes());
b[info + 4..info + 8].copy_from_slice(&(BLOCK as u32).to_le_bytes());
b[info + 8..info + 12].copy_from_slice(&ks.to_le_bytes());
b[info + 12..info + 16].copy_from_slice(&vs.to_le_bytes());
b[info + 16..info + 20].copy_from_slice(&self.longest_key.to_le_bytes());
b[info + 20..info + 24].copy_from_slice(&self.longest_val.to_le_bytes());
b[info + 24..info + 32].copy_from_slice(&self.key_count.to_le_bytes());
b[info + 32..info + 40].copy_from_slice(&self.node_count.to_le_bytes());
}
if !self.headerless {
b[8..16].copy_from_slice(&self.oid.to_le_bytes());
b[16..24].copy_from_slice(&self.xid.to_le_bytes());
b[24..28].copy_from_slice(&self.obj_type.to_le_bytes());
b[28..32].copy_from_slice(&self.subtype.to_le_bytes());
fletcher::seal(&mut b);
}
b
}
}
@@ -0,0 +1,204 @@
//! Building file-system records — inodes, directory entries, their extended fields, data streams
//! and file extents — as `fs.rs` reads them back (Apple File System Reference, "File-System
//! Objects").
//!
//! A record is a (key, value) pair. Keys order a volume's tree; `fs::compare_keys` gives that
//! order, and a tree is built from records sorted by it. The builders here write the little-endian
//! fields each record type holds; the caller supplies the identifiers, times and modes.
use crate::fs::{key_word, xf};
use crate::names;
use crate::ondisk::rec;
/// A directory entry's `DT_*` type: a directory.
pub const DT_DIR: u16 = 4;
/// A directory entry's `DT_*` type: a regular file.
pub const DT_REG: u16 = 8;
/// A directory entry's `DT_*` type: a symbolic link.
pub const DT_LNK: u16 = 10;
/// An inode's internal flags, as a freshly made volume's root and private directories carry them.
pub const INODE_FLAGS_BASE: u64 = 0x8000;
/// One extended field of an inode or directory entry: its kind, flags and data.
pub struct XField {
pub kind: u8,
pub flags: u8,
pub data: Vec<u8>,
}
/// Encode an `xf_blob_t`: a count and used-data size, then each field's header, then the field
/// data each padded to eight bytes.
#[must_use]
pub fn xfields(fields: &[XField]) -> Vec<u8> {
if fields.is_empty() {
return Vec::new();
}
let used: usize = fields.iter().map(|f| f.data.len().div_ceil(8) * 8).sum();
let mut b = Vec::new();
b.extend_from_slice(&(fields.len() as u16).to_le_bytes());
b.extend_from_slice(&(used as u16).to_le_bytes());
for f in fields {
b.push(f.kind);
b.push(f.flags);
b.extend_from_slice(&(f.data.len() as u16).to_le_bytes());
}
for f in fields {
b.extend_from_slice(&f.data);
let pad = f.data.len().div_ceil(8) * 8 - f.data.len();
b.extend(std::iter::repeat_n(0u8, pad));
}
b
}
/// A NAME extended field (an inode's own name, or a hard link's): the name and a NUL, kind 4,
/// not copied with the inode.
#[must_use]
pub fn name_xfield(name: &[u8]) -> XField {
let mut data = name.to_vec();
data.push(0);
XField {
kind: xf::NAME,
flags: xf::FLAG_DO_NOT_COPY,
data,
}
}
/// A `j_dstream_t`: logical size, allocated size, crypto id, and bytes written and read.
#[must_use]
pub fn dstream(size: u64, alloced: u64, crypto: u64, written: u64, read: u64) -> Vec<u8> {
let mut b = Vec::with_capacity(40);
for v in [size, alloced, crypto, written, read] {
b.extend_from_slice(&v.to_le_bytes());
}
b
}
/// A DSTREAM extended field (a file's data stream), kind 8, a system field.
#[must_use]
pub fn dstream_xfield(stream: Vec<u8>) -> XField {
XField {
kind: xf::DSTREAM,
flags: xf::FLAG_SYSTEM_FIELD,
data: stream,
}
}
/// What an inode record holds.
pub struct InodeBuilder {
pub oid: u64,
pub parent: u64,
pub private_id: u64,
pub create_time: u64,
pub mod_time: u64,
pub change_time: u64,
pub access_time: u64,
pub internal_flags: u64,
pub nchildren_or_nlink: i32,
pub default_protection_class: u32,
pub write_generation_counter: u32,
pub bsd_flags: u32,
pub owner: u32,
pub group: u32,
pub mode: u16,
pub uncompressed_size: u64,
pub xfields: Vec<XField>,
}
impl InodeBuilder {
/// The (key, value) of this inode.
#[must_use]
pub fn build(&self) -> (Vec<u8>, Vec<u8>) {
let key = key_word(self.oid, rec::INODE).to_le_bytes().to_vec();
let mut v = Vec::with_capacity(92);
for x in [
self.parent,
self.private_id,
self.create_time,
self.mod_time,
self.change_time,
self.access_time,
self.internal_flags,
] {
v.extend_from_slice(&x.to_le_bytes());
}
v.extend_from_slice(&self.nchildren_or_nlink.to_le_bytes());
v.extend_from_slice(&self.default_protection_class.to_le_bytes());
v.extend_from_slice(&self.write_generation_counter.to_le_bytes());
v.extend_from_slice(&self.bsd_flags.to_le_bytes());
v.extend_from_slice(&self.owner.to_le_bytes());
v.extend_from_slice(&self.group.to_le_bytes());
v.extend_from_slice(&self.mode.to_le_bytes());
v.extend_from_slice(&0u16.to_le_bytes()); // pad1
v.extend_from_slice(&self.uncompressed_size.to_le_bytes());
v.extend_from_slice(&xfields(&self.xfields));
(key, v)
}
}
/// A directory entry record (a hashed `j_drec_hashed_key_t`): the parent's identifier keys it,
/// then a word holding the name length (with its NUL) and the name's 22-bit hash, then the name
/// and a NUL. The value names the child, when it was added, and its `DT_*` type.
#[must_use]
pub fn dir_rec(
parent: u64,
name: &[u8],
fold: bool,
file_id: u64,
date_added: u64,
dtype: u16,
) -> (Vec<u8>, Vec<u8>) {
let name_len = (name.len() + 1) as u32; // includes the NUL
let nlh = (name_len & 0x3ff) | (names::hash(name, fold) << 10);
let mut key = key_word(parent, rec::DIR_REC).to_le_bytes().to_vec();
key.extend_from_slice(&nlh.to_le_bytes());
key.extend_from_slice(name);
key.push(0);
let mut val = Vec::with_capacity(18);
val.extend_from_slice(&file_id.to_le_bytes());
val.extend_from_slice(&date_added.to_le_bytes());
val.extend_from_slice(&dtype.to_le_bytes());
(key, val)
}
/// The two records a freshly made volume's root directory (inode 2) and private directory (inode
/// 3) and their two directory entries amount to, in key order, every time set to `t` nanoseconds.
///
/// A new APFS volume holds exactly these four records: the root directory's entry for
/// `private-dir`, its entry for `root`, the root inode, and the private-directory inode. Both
/// directories are `drwxr-xr-x`, owned by root, parented to inode 1, and carry their own name as
/// a NAME extended field.
#[must_use]
pub fn empty_volume_records(fold: bool, t: u64) -> Vec<(Vec<u8>, Vec<u8>)> {
let dir = |oid: u64, name: &[u8], mode: u16| {
InodeBuilder {
oid,
parent: 1,
private_id: oid,
create_time: t,
mod_time: t,
change_time: t,
access_time: t,
internal_flags: INODE_FLAGS_BASE,
nchildren_or_nlink: 0,
default_protection_class: 0,
write_generation_counter: 1,
bsd_flags: 0,
owner: 0,
group: 0,
mode,
uncompressed_size: 0,
xfields: vec![name_xfield(name)],
}
.build()
};
// The root directory is `drwxr-xr-x`, the private directory `drw-r--r--`.
let mut recs = vec![
dir_rec(1, b"private-dir", fold, 3, t, DT_DIR),
dir_rec(1, b"root", fold, 2, t, DT_DIR),
dir(2, b"root", 0o040755),
dir(3, b"private-dir", 0o040644),
];
recs.sort_by(|a, b| crate::fs::compare_keys(&a.0, &b.0));
recs
}
@@ -0,0 +1,365 @@
//! Building a sealed system volume: its hashed file-system tree ([`crate::seal`]), headerless
//! and mapped through the volume's object map, and around it what the seal leaves out — the
//! physical file-extent tree that says where each data stream is, the integrity metadata that
//! records the root hash, and the one snapshot the volume boots from, named for that hash.
//!
//! Laid out as a sealed system volume of a fresh VZ restore is **[vz]**:
//! - the live superblock: incompatible features case-insensitive and sealed (`0x21`), flags
//! `0x201`, one snapshot, an empty extent-reference tree, the integrity metadata, the
//! snapshot's extended metadata and a file-extent tree of its own (physical, fixed 16-byte
//! keys and values), which it counts as allocated on top of what the snapshot holds;
//! - the snapshot: a superblock copy (physical, named by its block) like the live one but with
//! no object map, extent-reference or snapshot trees, no snapshots, one object identifier
//! fewer and its own file-extent tree, the same records as the live one's in other blocks
//! (`fsck_apfs` finds one tree reached from both overlapping, and counts it twice); its own
//! extent-reference tree, a physical extent per data stream owned by its inode; and two
//! records in the snapshot metadata tree, its metadata and its name;
//! - the object map: the tree's nodes mapped without headers, the integrity metadata and the
//! snapshot's extended metadata mapped as ordinary objects, and a snapshot tree of one entry,
//! the snapshot's transaction.
//!
//! The snapshot is taken in the one transaction that writes the container, as a freshly sealed
//! image's is before anything mounts it.
use crate::fs::key_word;
use crate::ondisk::{obj, omap, rec};
use crate::seal::SealedTree;
use super::geometry::BLOCK_SIZE;
use super::node::Layout;
use super::space::XID;
use super::tree::{self, Alloc, TreeError, TreeKind};
use super::volume::{Block, Counts, Stream, Super, Volume, blocks_of, phys_extent, superblock};
/// A sealed volume's incompatible features: case-insensitive, sealed.
const INCOMPAT: u64 = 0x21;
/// A sealed volume's flags: unencrypted, and `0x200`, which every sealed system volume of a VZ
/// restore carries **[vz]** and the reference does not name.
const FS_FLAGS: u64 = 0x201;
/// The integrity metadata's version, and its hash type (SHA-256).
const INTEGRITY_VERSION: u32 = 2;
const HASH_SHA256: u32 = 1;
/// Where the integrity metadata keeps the root hash.
const ROOT_HASH_OFFSET: u32 = 128;
/// The snapshot extended metadata's version.
const SNAP_META_EXT_VERSION: u32 = 1;
/// The snapshot name record's identifier: every bit of an object identifier.
const SNAP_NAME_OID: u64 = rec::OBJ_ID_MASK;
/// What seals a volume: its hashed tree, its data streams (each given its blocks, one extent),
/// and its snapshot's name and identifier.
pub struct Seal {
/// The hashed file-system tree, its identifiers from any base; placed, they are rebased.
pub tree: SealedTree,
/// The data streams, each `len` a whole number of blocks.
pub streams: Vec<Stream>,
/// The snapshot's name, `com.apple.os.update-<root hash>`.
pub snapshot: String,
pub snapshot_uuid: [u8; 16],
/// The next object identifier when the snapshot was taken; the live volume's is one more.
pub inum: u64,
pub next_doc_id: u32,
}
/// What a sealed volume is built from.
pub struct SealedSpec<'a> {
pub index: u32,
pub name: &'a str,
pub uuid: [u8; 16],
pub role: u16,
pub features: u64,
pub group: [u8; 16],
pub t: u64,
pub counts: Counts,
pub seal: Seal,
}
/// A file-extent tree record: stream `id`'s bytes from `logical`, `len` bytes at block `phys`.
fn fext(id: u64, logical: u64, len: u64, phys: u64) -> (Vec<u8>, Vec<u8>) {
let mut k = Vec::with_capacity(16);
k.extend_from_slice(&id.to_le_bytes());
k.extend_from_slice(&logical.to_le_bytes());
let mut v = Vec::with_capacity(16);
v.extend_from_slice(&len.to_le_bytes()); // len_and_flags, no flags
v.extend_from_slice(&phys.to_le_bytes());
(k, v)
}
/// An object-map record with flags.
fn omap_entry(oid: u64, flags: u32, paddr: u64) -> (Vec<u8>, Vec<u8>) {
let mut k = Vec::with_capacity(16);
k.extend_from_slice(&oid.to_le_bytes());
k.extend_from_slice(&XID.to_le_bytes());
let mut v = Vec::with_capacity(16);
v.extend_from_slice(&flags.to_le_bytes());
v.extend_from_slice(&(BLOCK_SIZE as u32).to_le_bytes());
v.extend_from_slice(&paddr.to_le_bytes());
(k, v)
}
/// The snapshot metadata tree's two records: the snapshot's metadata and its name.
fn snapshot_records(
name: &str,
extentref: u64,
sblock: u64,
t: u64,
inum: u64,
) -> Vec<(Vec<u8>, Vec<u8>)> {
let mut cname = name.as_bytes().to_vec();
cname.push(0);
let name_len = cname.len() as u16;
let meta_k = key_word(XID, rec::SNAP_METADATA).to_le_bytes().to_vec();
let mut meta_v = Vec::with_capacity(50 + cname.len());
meta_v.extend_from_slice(&extentref.to_le_bytes());
meta_v.extend_from_slice(&sblock.to_le_bytes());
meta_v.extend_from_slice(&t.to_le_bytes()); // create_time
meta_v.extend_from_slice(&t.to_le_bytes()); // change_time
meta_v.extend_from_slice(&inum.to_le_bytes());
meta_v.extend_from_slice(&(obj::PHYSICAL | obj::BTREE).to_le_bytes());
meta_v.extend_from_slice(&0u32.to_le_bytes()); // flags
meta_v.extend_from_slice(&name_len.to_le_bytes());
meta_v.extend_from_slice(&cname);
let mut name_k = key_word(SNAP_NAME_OID, rec::SNAP_NAME)
.to_le_bytes()
.to_vec();
name_k.extend_from_slice(&name_len.to_le_bytes());
name_k.extend_from_slice(&cname);
let name_v = XID.to_le_bytes().to_vec();
vec![(meta_k, meta_v), (name_k, name_v)]
}
/// Build the sealed volume `spec` describes, its blocks from `alloc` and its virtual identifiers
/// from `next_oid`.
///
/// # Errors
///
/// [`TreeError`] when the container has no room, or a record fits no node.
pub fn sealed_volume(
spec: SealedSpec,
alloc: &mut Alloc,
next_oid: &mut u64,
) -> Result<Volume, TreeError> {
let SealedSpec { seal, .. } = spec;
let Seal {
mut tree,
streams,
snapshot,
snapshot_uuid,
inum,
next_doc_id,
} = seal;
let first = alloc.next();
let sb_oid = *next_oid;
*next_oid += 1;
let mut blocks: Vec<(u64, Vec<u8>)> = Vec::new();
// The data streams, each one extent: the file-extent tree says where, the snapshot's
// extent-reference tree that its inode owns it.
let mut fexts = Vec::with_capacity(streams.len());
let mut extentref = Vec::with_capacity(streams.len());
let mut stream_blocks = Vec::with_capacity(streams.len());
let mut data_blocks = 0u64;
for s in &streams {
let n = blocks_of(s.len);
if n == 0 {
stream_blocks.push(0);
continue;
}
let phys = alloc.take(n).ok_or(TreeError::NoSpace)?;
stream_blocks.push(phys);
data_blocks += n;
fexts.push(fext(s.id, 0, n * BLOCK_SIZE, phys));
extentref.push(phys_extent(phys, n, s.owner));
}
fexts.sort_by(|a, b| crate::fs::compare_u64_pairs(&a.0, &b.0));
extentref.sort_by(|a, b| crate::fs::compare_keys(&a.0, &b.0));
let omap_obj = alloc.take(1).ok_or(TreeError::NoSpace)?;
// The hashed tree's nodes, headerless, their identifiers from here.
let root_oid = *next_oid;
*next_oid += tree.nodes.len() as u64;
tree.rebase(root_oid);
let mut mapped = Vec::with_capacity(tree.nodes.len() + 2);
for n in tree.nodes {
let paddr = alloc.take(1).ok_or(TreeError::NoSpace)?;
mapped.push(omap_entry(n.oid, omap::VAL_NOHEADER, paddr));
blocks.push((paddr, n.block));
}
// The integrity metadata, recording the root hash.
let im_oid = *next_oid;
*next_oid += 1;
let im = alloc.take(1).ok_or(TreeError::NoSpace)?;
{
let mut b = Block::new();
b.header(im_oid, XID, obj::INTEGRITY_META, 0);
b.u32(32, INTEGRITY_VERSION);
b.u32(36, 0); // flags
b.u32(40, HASH_SHA256);
b.u32(44, ROOT_HASH_OFFSET);
b.bytes(ROOT_HASH_OFFSET as usize, &tree.root_hash);
blocks.push((im, b.seal()));
}
mapped.push(omap_entry(im_oid, 0, im));
// The snapshot's extended metadata.
let sme_oid = *next_oid;
*next_oid += 1;
let sme = alloc.take(1).ok_or(TreeError::NoSpace)?;
{
let mut b = Block::new();
b.header(sme_oid, XID, obj::SNAP_META_EXT, 0);
b.u32(32, SNAP_META_EXT_VERSION);
b.u32(36, 0); // flags
b.u64(40, XID); // the snapshot's transaction
b.bytes(48, &snapshot_uuid);
b.u64(64, 0); // token
blocks.push((sme, b.seal()));
}
mapped.push(omap_entry(sme_oid, 0, sme));
mapped.sort_by(|a, b| crate::fs::compare_u64_pairs(&a.0, &b.0));
let physical = |layout, subtype, tree_flags| TreeKind {
layout,
subtype,
tree_flags,
virtual_nodes: false,
};
let fixed = |key_size, val_size| Layout::Fixed { key_size, val_size };
// The snapshot's file-extent tree; the live volume gets a copy of its own, last.
let ft_snap = tree::build(
&fexts,
physical(fixed(16, 16), obj::FEXT_TREE, 0x12),
alloc,
next_oid,
)?;
let er_live = tree::build(
&[],
physical(Layout::Variable, obj::BLOCKREFTREE, 0x52),
alloc,
next_oid,
)?;
let er_snap = tree::build(
&extentref,
physical(Layout::Variable, obj::BLOCKREFTREE, 0x52),
alloc,
next_oid,
)?;
let snap_sb = alloc.take(1).ok_or(TreeError::NoSpace)?;
let sm = tree::build(
&snapshot_records(&snapshot, er_snap.root, snap_sb, spec.t, inum),
physical(Layout::Variable, obj::SNAPMETATREE, 0x52),
alloc,
next_oid,
)?;
let om = tree::build(
&mapped,
physical(fixed(16, 16), obj::OMAP, 0x12),
alloc,
next_oid,
)?;
let snaps = [(XID.to_le_bytes().to_vec(), vec![0u8; 16])];
let ost = tree::build(
&snaps,
physical(fixed(8, 16), obj::OMAP_SNAPSHOT, 0x10),
alloc,
next_oid,
)?;
// The volume's object map, with its one snapshot.
{
let mut b = Block::new();
b.header(omap_obj, XID, obj::PHYSICAL | obj::OMAP, 0);
b.u32(omap::FLAGS, 0);
b.u32(omap::SNAP_COUNT, 1);
b.u32(omap::TREE_TYPE, obj::PHYSICAL | obj::BTREE);
b.u32(omap::SNAPSHOT_TREE_TYPE, obj::PHYSICAL | obj::BTREE);
b.u64(omap::TREE_OID, om.root);
b.u64(omap::SNAPSHOT_TREE_OID, ost.root);
b.u64(omap::MOST_RECENT_SNAP, XID);
blocks.push((omap_obj, b.seal()));
}
// Every block the volume owned when the snapshot was taken, but the superblocks (as a
// volume's count leaves out its own superblock, `fsck_apfs` leaves out the snapshot's copy
// too); then the live volume's own file-extent tree, and with it.
let snap_alloc_count = alloc.next() - first - 1;
let ft_live = tree::build(
&fexts,
physical(fixed(16, 16), obj::FEXT_TREE, 0x12),
alloc,
next_oid,
)?;
let live_alloc_count = alloc.next() - first - 1;
for t in [
ft_snap.nodes,
ft_live.nodes,
er_live.nodes,
er_snap.nodes,
sm.nodes,
om.nodes,
ost.nodes,
] {
blocks.extend(t);
}
// The superblocks: the snapshot's copy, then the live one.
let sb = alloc.take(1).ok_or(TreeError::NoSpace)?;
let fields = |snapshot: bool| Super {
index: spec.index,
name: spec.name,
uuid: spec.uuid,
role: spec.role,
features: spec.features,
incompat: INCOMPAT,
fs_flags: FS_FLAGS,
alloc_count: if snapshot {
snap_alloc_count
} else {
live_alloc_count
},
omap: if snapshot { 0 } else { omap_obj },
root: root_oid,
extentref: if snapshot { 0 } else { er_live.root },
snapmeta: if snapshot { 0 } else { sm.root },
next_obj_id: if snapshot { inum } else { inum + 1 },
next_doc_id,
counts: spec.counts,
data_blocks,
group: spec.group,
t: spec.t,
};
let sealed = |b: &mut Block, snapshot: bool| {
b.u64(crate::ondisk::apfs::NUM_SNAPSHOTS, u64::from(!snapshot));
b.u64(crate::ondisk::apfs::INTEGRITY_META_OID, im_oid);
b.u64(
crate::ondisk::apfs::FEXT_TREE_OID,
if snapshot { ft_snap.root } else { ft_live.root },
);
if !snapshot {
b.u64(crate::ondisk::apfs::SNAP_META_EXT_OID, sme_oid);
}
};
{
let mut b = superblock(&fields(true));
sealed(&mut b, true);
b.header(snap_sb, XID, obj::PHYSICAL | obj::FS, 0);
blocks.push((snap_sb, b.seal()));
}
{
let mut b = superblock(&fields(false));
sealed(&mut b, false);
b.header(sb_oid, XID, obj::FS, 0);
blocks.push((sb, b.seal()));
}
Ok(Volume {
blocks,
stream_blocks,
sb_oid,
container_omap_record: super::space::omap_record(sb_oid, XID, sb),
})
}
@@ -0,0 +1,356 @@
//! Building a container's scaffold: the superblock, its one checkpoint, the space manager and its
//! internal pool, the reaper, and the container object map. These are the blocks every container
//! has before any volume, laid out as a freshly formatted container's are (the bare container a
//! `newfs_apfs` leaves, before a volume is added).
//!
//! The writer forms a single checkpoint, transaction 1, holding everything, with empty free
//! queues — the state a bare `newfs_apfs` container is in, which `fsck_apfs` accepts. The space
//! manager's main device marks every block through the internal pool, and then the blocks the
//! object map and the volumes take, as used in one chunk bitmap; the internal pool's own bitmap
//! marks the chunk-info and bitmap blocks it holds. Blocks the container does not touch stay zero,
//! so a file destination stays sparse.
use crate::fletcher;
use crate::ondisk::{NX_MAGIC, cpm, nx, obj};
use super::geometry::{BLOCK_SIZE, Geometry};
use super::node::{Layout, NodeSpec};
/// A block is 4 KiB.
const BLOCK: usize = BLOCK_SIZE as usize;
/// The space manager is ephemeral object 0x400, the reaper 0x401; volumes and their trees take
/// virtual identifiers from 0x402 up.
pub const SPACEMAN_OID: u64 = 0x400;
pub const REAPER_OID: u64 = 0x401;
pub const FIRST_VOLUME_OID: u64 = 0x402;
/// The one transaction a fresh container is written in.
pub const XID: u64 = 1;
/// A 4 KiB block being filled, little-endian.
struct Block(Vec<u8>);
impl Block {
fn new() -> Self {
Self(vec![0u8; BLOCK])
}
fn u16(&mut self, at: usize, v: u16) {
self.0[at..at + 2].copy_from_slice(&v.to_le_bytes());
}
fn u32(&mut self, at: usize, v: u32) {
self.0[at..at + 4].copy_from_slice(&v.to_le_bytes());
}
fn u64(&mut self, at: usize, v: u64) {
self.0[at..at + 8].copy_from_slice(&v.to_le_bytes());
}
/// Write the object header (checksum last) for a non-headerless object.
fn header(&mut self, oid: u64, xid: u64, type_and_flags: u32, subtype: u32) {
self.u64(8, oid);
self.u64(16, xid);
self.u32(24, type_and_flags);
self.u32(28, subtype);
}
fn seal(mut self) -> Vec<u8> {
fletcher::seal(&mut self.0);
self.0
}
}
/// The container object map's record for a volume: its superblock's virtual identifier maps to
/// the block the superblock is at. Fixed 16-byte key `(oid, xid)` and 16-byte value `(flags,
/// size, paddr)`.
#[must_use]
pub fn omap_record(oid: u64, xid: u64, paddr: u64) -> (Vec<u8>, Vec<u8>) {
let mut k = Vec::with_capacity(16);
k.extend_from_slice(&oid.to_le_bytes());
k.extend_from_slice(&xid.to_le_bytes());
let mut v = Vec::with_capacity(16);
v.extend_from_slice(&0u32.to_le_bytes()); // flags
v.extend_from_slice(&(BLOCK as u32).to_le_bytes()); // size
v.extend_from_slice(&paddr.to_le_bytes());
(k, v)
}
/// Build a container's scaffold for `block_count` blocks, `uuid` its identifier, with the object
/// map holding `omap_entries` (already in key order) and `used_after_pool` blocks taken past the
/// internal pool by the object map and the volumes (so the main device's free count and chunk
/// bitmap are right). The object map's own two blocks are included in `used_after_pool` by the
/// caller.
#[must_use]
pub fn scaffold(
g: &Geometry,
uuid: [u8; 16],
omap_entries: &[(Vec<u8>, Vec<u8>)],
fs_oids: &[u64],
next_oid: u64,
used_after_pool: u64,
) -> Vec<(u64, Vec<u8>)> {
let block_count = g.block_count;
let mut out: Vec<(u64, Vec<u8>)> = Vec::new();
// The object map sits first past the pool, its root next.
let omap_oid = g.first_free;
let omap_root = g.first_free + 1;
// Blocks used on the main device: everything through the pool, then what the caller placed.
let used = g.first_free + used_after_pool;
// --- Container superblock (block 0 and the descriptor copy) ---
let nxsb = |copy_oid: u64| -> Vec<u8> {
let mut b = Block::new();
b.header(copy_oid, XID, obj::EPHEMERAL | obj::NX_SUPERBLOCK, 0);
b.u32(nx::MAGIC, NX_MAGIC);
b.u32(nx::BLOCK_SIZE, BLOCK as u32);
b.u64(nx::BLOCK_COUNT, block_count);
b.u64(nx::INCOMPAT, nx::INCOMPAT_VERSION2);
b.0[nx::UUID..nx::UUID + 16].copy_from_slice(&uuid);
b.u64(nx::NEXT_OID, next_oid);
b.u64(nx::NEXT_XID, XID + 1);
b.u32(nx::XP_DESC_BLOCKS, g.desc_blocks as u32);
b.u32(nx::XP_DATA_BLOCKS, g.data_blocks as u32);
b.u64(nx::XP_DESC_BASE, 1);
b.u64(nx::XP_DATA_BASE, g.data_base);
b.u32(nx::XP_DESC_NEXT, 2);
b.u32(nx::XP_DATA_NEXT, 2);
b.u32(nx::XP_DESC_INDEX, 0);
b.u32(nx::XP_DESC_LEN, 2);
b.u32(nx::XP_DATA_INDEX, 0);
b.u32(nx::XP_DATA_LEN, 2);
b.u64(nx::SPACEMAN_OID, SPACEMAN_OID);
b.u64(nx::OMAP_OID, omap_oid);
b.u64(nx::REAPER_OID, REAPER_OID);
b.u32(nx::MAX_FILE_SYSTEMS, g.max_volumes as u32);
for (i, oid) in fs_oids.iter().enumerate() {
b.u64(nx::FS_OID + 8 * i, *oid);
}
// The ephemeral object ring: minimum blocks and one ring, as a fresh container records.
b.u64(nx::EPHEMERAL_INFO, 0x8_0004_0001);
b.seal()
};
out.push((0, nxsb(1)));
out.push((2, nxsb(1)));
// --- Checkpoint map (block 1): maps the two ephemeral objects to their data blocks ---
{
let mut b = Block::new();
b.header(1, XID, obj::PHYSICAL | obj::CHECKPOINT_MAP, 0);
b.u32(cpm::FLAGS, cpm::LAST);
b.u32(cpm::COUNT, 2);
let mut entry = |i: usize, ty: u32, oid: u64, paddr: u64| {
let o = cpm::MAP + i * cpm::ENTRY_SIZE;
b.u32(o, ty); // cpm_type
b.u32(o + 4, 0); // cpm_subtype
b.u32(o + 8, BLOCK as u32); // cpm_size
b.u32(o + 12, 0); // cpm_pad
b.u64(o + 16, 0); // cpm_fs_oid
b.u64(o + 24, oid); // cpm_oid
b.u64(o + 32, paddr); // cpm_paddr
};
entry(0, obj::EPHEMERAL | obj::SPACEMAN, SPACEMAN_OID, g.data_base);
entry(
1,
obj::EPHEMERAL | obj::NX_REAPER,
REAPER_OID,
g.data_base + 1,
);
out.push((1, b.seal()));
}
// --- Space manager (data block 0), its chunk-info block and bitmaps ---
out.extend(space_manager(g, block_count, used));
// --- Reaper (data block 1) ---
{
let mut b = Block::new();
b.header(REAPER_OID, XID, obj::EPHEMERAL | obj::NX_REAPER, 0);
b.u64(32, 1); // nr_next_reap_id
b.u32(64, 1); // nr_flags: NR_BHM_FLAG, always set
b.u32(108, (BLOCK - 112) as u32); // nr_state_buffer_size
out.push((g.data_base + 1, b.seal()));
}
// --- Container object map and its (possibly empty) tree ---
{
let mut b = Block::new();
b.header(omap_oid, XID, obj::PHYSICAL | obj::OMAP, 0);
b.u32(32, 1); // om_flags: OMAP_MANUALLY_MANAGED
b.u32(36, 0); // om_snap_count
b.u32(40, obj::PHYSICAL | obj::BTREE); // om_tree_type
b.u32(44, obj::PHYSICAL | obj::BTREE); // om_snapshot_tree_type
b.u64(48, omap_root); // om_tree_oid
out.push((omap_oid, b.seal()));
}
let longest = if omap_entries.is_empty() { 0 } else { 16 };
out.push((
omap_root,
NodeSpec {
obj_type: obj::PHYSICAL | obj::BTREE,
subtype: obj::OMAP,
oid: omap_root,
xid: XID,
level: 0,
is_root: true,
headerless: false,
hashed: false,
layout: Layout::Fixed {
key_size: 16,
val_size: 16,
},
tree_flags: 0x12,
longest_key: longest,
longest_val: longest,
key_count: omap_entries.len() as u64,
node_count: 1,
entries: omap_entries,
}
.build(),
));
out
}
/// The space manager object, its chunk-info block, the main device's one chunk bitmap and the
/// internal pool's bitmap — the blocks that record which of the container's blocks are used.
fn space_manager(g: &Geometry, block_count: u64, used: u64) -> Vec<(u64, Vec<u8>)> {
let mut out = Vec::new();
let bpc = super::geometry::BLOCKS_PER_CHUNK;
let per_cib = super::geometry::CHUNKS_PER_CIB;
assert!(
g.cab_count == 0,
"a container of more than {} chunk-info blocks",
super::geometry::CIBS_PER_CAB
);
// The blocks of each chunk that are used: the used blocks are the prefix [0, used).
let chunk_used = |c: u64| -> (u64, u64) {
let start = c * bpc;
let blocks = bpc.min(block_count - start);
(blocks, used.saturating_sub(start).min(blocks))
};
// The internal pool holds the chunk-info blocks first, then a bitmap for each chunk with any
// block used, in chunk order.
let cib_addr = |i: u64| g.pool_base + i;
let mut bitmap_addr = vec![0u64; g.chunk_count as usize];
let mut next_pool = g.pool_base + g.cib_count;
for c in 0..g.chunk_count {
if chunk_used(c).1 > 0 {
bitmap_addr[c as usize] = next_pool;
next_pool += 1;
}
}
let pool_used = next_pool - g.pool_base;
assert!(
pool_used <= g.pool_blocks,
"the internal pool holds every chunk's bitmap"
);
// --- The space manager object itself (one block) ---
{
let mut b = Block::new();
b.header(SPACEMAN_OID, XID, obj::EPHEMERAL | obj::SPACEMAN, 0);
b.u32(32, BLOCK as u32); // sm_block_size
b.u32(36, bpc as u32); // sm_blocks_per_chunk
b.u32(40, per_cib as u32); // sm_chunks_per_cib
b.u32(44, super::geometry::CIBS_PER_CAB as u32);
// Main device (offset 48): block/chunk/cib/cab counts, free count, address offset.
b.u64(48, block_count);
b.u64(48 + 8, g.chunk_count);
b.u32(48 + 16, g.cib_count as u32);
b.u32(48 + 20, g.cab_count as u32);
b.u64(48 + 24, block_count - used); // main device free count
b.u32(48 + 32, g.address_offset as u32);
// The second device, which a container on one device keeps empty, lists from where the
// main device's list ends.
b.u32(96 + 32, g.second_address_offset as u32);
b.u32(144, 1); // sm_flags: SM_FLAG_VERSIONED
b.u32(148, 16); // sm_ip_bm_tx_multiplier
b.u64(152, g.pool_blocks); // sm_ip_block_count
b.u32(160, g.pool_bitmaps as u32); // sm_ip_bm_size_in_blocks
b.u32(164, g.pool_bitmap_slots() as u32); // sm_ip_bm_block_count
b.u64(168, g.pool_bitmap_base); // sm_ip_bm_base
b.u64(176, g.pool_base); // sm_ip_base
// Three free queues (offsets 200/240/280), empty, with their node limits.
b.u16(200 + 24, g.fq_pool_limit as u16);
b.u16(240 + 24, g.fq_main_limit as u16);
// The internal-pool bitmap ring: slot 0 is the live bitmap, slots 1..n a free list.
let ring = g.pool_bitmap_slots();
b.u16(320, 1); // sm_ip_bm_free_head
b.u16(322, (ring - 1) as u16); // sm_ip_bm_free_tail
b.u32(324, g.xid_array_offset as u32);
b.u32(328, g.slot_array_offset as u32);
b.u32(332, g.free_list_offset as u32);
b.u32(336, 1); // sm_version
b.u32(340, super::geometry::SPACEMAN_STRUCT_SIZE as u32);
// Trailing arrays. The current internal-pool bitmap (one block) is in ring slot 0,
// written in this transaction.
b.u64(g.xid_array_offset as usize, XID);
b.u16(g.slot_array_offset as usize, 0);
// The free list threads slots 1..ring-1, each to the next, the last to none; slot 0,
// in use, points nowhere.
let fl = g.free_list_offset as usize;
for slot in 0..ring as usize {
let next = if slot == 0 || slot == ring as usize - 1 {
0xffff
} else {
(slot + 1) as u16
};
b.u16(fl + slot * 2, next);
}
// The main device's address list: the chunk-info blocks.
let ao = g.address_offset as usize;
for i in 0..g.cib_count {
b.u64(ao + i as usize * 8, cib_addr(i));
}
out.push((g.data_base, b.seal()));
}
// --- The chunk-info blocks: each describes up to 126 chunks ---
for i in 0..g.cib_count {
let first = i * per_cib;
let count = per_cib.min(g.chunk_count - first);
let mut b = Block::new();
b.header(cib_addr(i), XID, obj::PHYSICAL | obj::SPACEMAN_CIB, 0);
b.u32(32, i as u32); // cib_index
b.u32(36, count as u32); // cib_chunk_info_count
for j in 0..count {
let c = first + j;
let at = 40 + j as usize * 32;
let (blocks, in_use) = chunk_used(c);
b.u64(at, XID); // ci_xid
b.u64(at + 8, c * bpc); // ci_addr
b.u32(at + 16, blocks as u32); // ci_block_count
b.u32(at + 20, (blocks - in_use) as u32); // ci_free_count
b.u64(at + 24, bitmap_addr[c as usize]); // ci_bitmap_addr, 0 where all free
}
out.push((cib_addr(i), b.seal()));
}
// --- Each used chunk's bitmap: its used blocks' bits set ---
for c in 0..g.chunk_count {
let (_, in_use) = chunk_used(c);
if in_use > 0 {
let mut bm = vec![0u8; BLOCK];
set_bits(&mut bm, in_use as usize);
out.push((bitmap_addr[c as usize], bm));
}
}
// --- The internal pool's bitmap (ring slot 0): its chunk-info and bitmap blocks used ---
{
let mut bm = vec![0u8; BLOCK];
set_bits(&mut bm, pool_used as usize);
out.push((g.pool_bitmap_base, bm));
}
out
}
/// Set the low `n` bits of a bitmap block (bit `i` is bit `i & 7` of byte `i >> 3`), the way a
/// chunk bitmap marks blocks `[0, n)` used.
fn set_bits(bm: &mut [u8], n: usize) {
for byte in bm.iter_mut().take(n / 8) {
*byte = 0xff;
}
let rem = n % 8;
if rem != 0 {
bm[n / 8] = ((1u16 << rem) - 1) as u8;
}
}
+213
View File
@@ -0,0 +1,213 @@
//! Building a whole B-tree from records in key order: leaves packed until the next record does
//! not fit, then each level of index nodes above them the same way, until one node — the root —
//! holds a level. Every node is a block of its own; the caller's allocator gives each its block.
//!
//! An index entry is its child's first key and the child's identifier, eight bytes: the child's
//! block address in a physical tree, its virtual identifier in a virtual tree (a volume's
//! file-system tree), which the volume's object map then resolves. A virtual tree's nodes are
//! returned with the object-map records that map them.
use crate::ondisk::obj;
use super::node::{Layout, NodeSpec};
use super::space::XID;
/// Hands out blocks one run after another, from a first block up to an end.
#[derive(Debug)]
pub struct Alloc {
next: u64,
end: u64,
}
impl Alloc {
/// An allocator of the blocks `[start, end)`.
#[must_use]
pub const fn new(start: u64, end: u64) -> Self {
Self { next: start, end }
}
/// The first of `n` contiguous blocks, or `None` when fewer than `n` are left.
pub fn take(&mut self, n: u64) -> Option<u64> {
let at = self.next;
let next = at.checked_add(n)?;
(next <= self.end).then(|| {
self.next = next;
at
})
}
/// The first block not yet handed out.
#[must_use]
pub const fn next(&self) -> u64 {
self.next
}
}
/// What kind of tree to build.
#[derive(Clone, Copy, Debug)]
pub struct TreeKind {
pub layout: Layout,
/// The tree's subtype (`obj::OMAP`, `obj::FSTREE`, `obj::BLOCKREFTREE`, ...).
pub subtype: u32,
/// The B-tree info flags the root records.
pub tree_flags: u32,
/// Whether the tree's nodes are virtual objects (resolved by an object map) rather than
/// physical ones (named by their block).
pub virtual_nodes: bool,
}
/// A built tree: its root's identifier, every node as (block, bytes), and, for a virtual tree,
/// the object-map records (virtual identifier, block) of its nodes.
pub struct Built {
pub root: u64,
pub nodes: Vec<(u64, Vec<u8>)>,
pub mapped: Vec<(u64, u64)>,
}
/// What ran out building a tree.
#[derive(Debug, thiserror::Error)]
pub enum TreeError {
#[error("the container has no room for the tree's nodes")]
NoSpace,
#[error("a record of {key} key and {val} value bytes fits no node")]
TooBig { key: usize, val: usize },
}
/// Divide `entries` among nodes of `level`, each holding as many as fit, the last the rest.
fn partition(
entries: &[(Vec<u8>, Vec<u8>)],
layout: Layout,
level: u16,
) -> Result<Vec<std::ops::Range<usize>>, TreeError> {
let mut out = Vec::new();
let mut start = 0;
while start < entries.len() {
let (mut kb, mut vb) = (0usize, 0usize);
let mut end = start;
while end < entries.len() {
let (k, v) = &entries[end];
if !layout.fits(end - start + 1, kb + k.len(), vb + v.len(), false, level) {
break;
}
kb += k.len();
vb += v.len();
end += 1;
}
if end == start {
let (k, v) = &entries[start];
return Err(TreeError::TooBig {
key: k.len(),
val: v.len(),
});
}
out.push(start..end);
start = end;
}
Ok(out)
}
/// Whether all of `entries` fit one root node at `level`.
fn fits_root(entries: &[(Vec<u8>, Vec<u8>)], layout: Layout, level: u16) -> bool {
let kb: usize = entries.iter().map(|(k, _)| k.len()).sum();
let vb: usize = entries.iter().map(|(_, v)| v.len()).sum();
layout.fits(entries.len(), kb, vb, true, level)
}
/// Build a tree of `kind` from `records`, in key order, its nodes' blocks taken from `alloc` and,
/// for a virtual tree, their identifiers from `next_oid`.
///
/// # Errors
///
/// [`TreeError::NoSpace`] when `alloc` runs out, [`TreeError::TooBig`] for a record no node
/// holds.
pub fn build(
records: &[(Vec<u8>, Vec<u8>)],
kind: TreeKind,
alloc: &mut Alloc,
next_oid: &mut u64,
) -> Result<Built, TreeError> {
let longest_key = records.iter().map(|(k, _)| k.len()).max().unwrap_or(0) as u32;
let longest_val = records.iter().map(|(_, v)| v.len()).max().unwrap_or(0) as u32;
// Lay out each level: the nodes' entry ranges, identifiers and blocks.
struct Node {
id: u64,
paddr: u64,
level: u16,
entries: Vec<(Vec<u8>, Vec<u8>)>,
}
let mut nodes: Vec<Node> = Vec::new();
let mut level_entries: Vec<(Vec<u8>, Vec<u8>)> = records.to_vec();
let mut level = 0u16;
let place = |alloc: &mut Alloc, next_oid: &mut u64| -> Result<(u64, u64), TreeError> {
let paddr = alloc.take(1).ok_or(TreeError::NoSpace)?;
let id = if kind.virtual_nodes {
let oid = *next_oid;
*next_oid += 1;
oid
} else {
paddr
};
Ok((id, paddr))
};
loop {
if fits_root(&level_entries, kind.layout, level) {
let (id, paddr) = place(alloc, next_oid)?;
nodes.push(Node {
id,
paddr,
level,
entries: level_entries,
});
break;
}
let mut above = Vec::new();
for r in partition(&level_entries, kind.layout, level)? {
let (id, paddr) = place(alloc, next_oid)?;
above.push((level_entries[r.start].0.clone(), id.to_le_bytes().to_vec()));
nodes.push(Node {
id,
paddr,
level,
entries: level_entries[r].to_vec(),
});
}
level_entries = above;
level += 1;
}
let node_count = nodes.len() as u64;
let root_index = nodes.len() - 1;
let storage = if kind.virtual_nodes { 0 } else { obj::PHYSICAL };
let mut built = Built {
root: nodes[root_index].id,
nodes: Vec::with_capacity(nodes.len()),
mapped: Vec::new(),
};
for (i, n) in nodes.iter().enumerate() {
let is_root = i == root_index;
let bytes = NodeSpec {
obj_type: storage | if is_root { obj::BTREE } else { obj::BTREE_NODE },
subtype: kind.subtype,
oid: n.id,
xid: XID,
level: n.level,
is_root,
headerless: false,
hashed: false,
layout: kind.layout,
tree_flags: kind.tree_flags,
longest_key,
longest_val,
key_count: records.len() as u64,
node_count,
entries: &n.entries,
}
.build();
built.nodes.push((n.paddr, bytes));
if kind.virtual_nodes {
built.mapped.push((n.id, n.paddr));
}
}
Ok(built)
}
@@ -0,0 +1,337 @@
//! Building one volume: its superblock, its object map, and its three trees — the file-system
//! tree (virtual, its nodes mapped through the volume's object map), and the extent-reference
//! and snapshot metadata trees (physical) — laid out as a freshly formatted volume's are.
//!
//! The caller gives the volume's file-system records (inodes, directory entries, attributes,
//! data-stream identifiers) and its data streams. The volume takes a run of blocks for each
//! stream, records where it is with a file extent in the file-system tree and a physical extent
//! in the extent-reference tree (one reference, owned by the stream's inode), and returns where
//! each stream goes, so the caller writes its bytes there.
use crate::fletcher;
use crate::fs::key_word;
use crate::ondisk::{APFS_MAGIC, apfs, obj, rec};
use super::geometry::BLOCK_SIZE;
use super::node::Layout;
use super::space::{XID, omap_record};
use super::tree::{self, Alloc, TreeError, TreeKind};
const BLOCK: usize = BLOCK_SIZE as usize;
/// The meta-crypto state a volume without encryption records: version 5, class 6, revision 1.
const META_CRYPTO: [u8; 20] = [
0x05, 0, 0, 0, 0, 0, 0, 0, 0x06, 0, 0, 0, 0xb2, 0x01, 0x41, 0x1a, 0x01, 0, 0, 0,
];
/// A physical extent's kind: a new extent, as every extent a format writes is.
const PEXT_KIND_NEW: u64 = 1;
/// One data stream of the volume: its identifier (the inode's private identifier, or an
/// attribute stream's), the inode that owns it, and its length in bytes.
#[derive(Clone, Copy, Debug)]
pub struct Stream {
pub id: u64,
pub owner: u64,
pub len: u64,
}
/// How many objects of each kind the volume holds, for its superblock.
#[derive(Clone, Copy, Debug, Default)]
pub struct Counts {
pub files: u64,
pub directories: u64,
pub symlinks: u64,
pub other: u64,
}
/// What a volume is built from.
pub struct VolumeSpec<'a> {
/// The volume's slot in the container, from 0.
pub index: u32,
pub name: &'a str,
pub uuid: [u8; 16],
/// The volume's role (`apfs::ROLE_*`).
pub role: u16,
/// The volume's optional features (`0x2`, plus `0x10` for a volume-group System volume).
pub features: u64,
/// The volume's incompatible features (`0x1` case-insensitive).
pub incompat: u64,
/// The next object identifier the volume hands out.
pub next_obj_id: u64,
/// The volume group's identifier, or zero.
pub group: [u8; 16],
/// The instant the volume records as its own.
pub t: u64,
/// The file-system records but file extents, in any order.
pub records: Vec<(Vec<u8>, Vec<u8>)>,
/// The data streams, each given blocks of its own.
pub streams: &'a [Stream],
pub counts: Counts,
}
/// A built volume: its metadata blocks (block, bytes), the first block of each stream (in the
/// order given; 0 for an empty stream), and the container object-map record that maps the
/// superblock's virtual identifier to its block.
pub struct Volume {
pub blocks: Vec<(u64, Vec<u8>)>,
pub stream_blocks: Vec<u64>,
pub sb_oid: u64,
pub container_omap_record: (Vec<u8>, Vec<u8>),
}
/// A 4 KiB block being filled, little-endian.
pub(super) struct Block(pub(super) Vec<u8>);
impl Block {
pub(super) fn new() -> Self {
Self(vec![0u8; BLOCK])
}
pub(super) fn u16(&mut self, at: usize, v: u16) {
self.0[at..at + 2].copy_from_slice(&v.to_le_bytes());
}
pub(super) fn u32(&mut self, at: usize, v: u32) {
self.0[at..at + 4].copy_from_slice(&v.to_le_bytes());
}
pub(super) fn u64(&mut self, at: usize, v: u64) {
self.0[at..at + 8].copy_from_slice(&v.to_le_bytes());
}
pub(super) fn bytes(&mut self, at: usize, v: &[u8]) {
self.0[at..at + v.len()].copy_from_slice(v);
}
pub(super) fn header(&mut self, oid: u64, xid: u64, type_and_flags: u32, subtype: u32) {
self.u64(8, oid);
self.u64(16, xid);
self.u32(24, type_and_flags);
self.u32(28, subtype);
}
pub(super) fn seal(mut self) -> Vec<u8> {
fletcher::seal(&mut self.0);
self.0
}
}
/// The blocks a stream of `len` bytes takes.
#[must_use]
pub const fn blocks_of(len: u64) -> u64 {
len.div_ceil(BLOCK_SIZE)
}
/// A file extent record: stream `id`'s bytes from `logical`, `len` bytes (whole blocks) at block
/// `phys`.
#[must_use]
pub fn file_extent(id: u64, logical: u64, len: u64, phys: u64) -> (Vec<u8>, Vec<u8>) {
let mut k = key_word(id, rec::FILE_EXTENT).to_le_bytes().to_vec();
k.extend_from_slice(&logical.to_le_bytes());
let mut v = Vec::with_capacity(24);
v.extend_from_slice(&len.to_le_bytes()); // len_and_flags, no flags
v.extend_from_slice(&phys.to_le_bytes());
v.extend_from_slice(&0u64.to_le_bytes()); // crypto_id
(k, v)
}
/// A physical extent record: `blocks` blocks from `phys`, owned by `owner`, referenced once.
#[must_use]
pub fn phys_extent(phys: u64, blocks: u64, owner: u64) -> (Vec<u8>, Vec<u8>) {
let k = key_word(phys, rec::EXTENT).to_le_bytes().to_vec();
let mut v = Vec::with_capacity(20);
v.extend_from_slice(&(blocks | (PEXT_KIND_NEW << 60)).to_le_bytes());
v.extend_from_slice(&owner.to_le_bytes());
v.extend_from_slice(&1i32.to_le_bytes());
(k, v)
}
/// Build the volume `spec` describes, its blocks from `alloc` and its virtual identifiers from
/// `next_oid`.
///
/// # Errors
///
/// [`TreeError`] when the container has no room, or a record fits no node.
pub fn volume(
spec: VolumeSpec,
alloc: &mut Alloc,
next_oid: &mut u64,
) -> Result<Volume, TreeError> {
let first = alloc.next();
let sb_oid = *next_oid;
*next_oid += 1;
// The streams' blocks, each one extent.
let mut fs_records = spec.records;
let mut extentref = Vec::new();
let mut stream_blocks = Vec::with_capacity(spec.streams.len());
let mut data_blocks = 0u64;
for s in spec.streams {
let n = blocks_of(s.len);
if n == 0 {
stream_blocks.push(0);
continue;
}
let phys = alloc.take(n).ok_or(TreeError::NoSpace)?;
stream_blocks.push(phys);
data_blocks += n;
fs_records.push(file_extent(s.id, 0, n * BLOCK_SIZE, phys));
extentref.push(phys_extent(phys, n, s.owner));
}
fs_records.sort_by(|a, b| crate::fs::compare_keys(&a.0, &b.0));
extentref.sort_by(|a, b| crate::fs::compare_keys(&a.0, &b.0));
let mut blocks: Vec<(u64, Vec<u8>)> = Vec::new();
let omap_obj = alloc.take(1).ok_or(TreeError::NoSpace)?;
let physical = |subtype, tree_flags, layout| TreeKind {
layout,
subtype,
tree_flags,
virtual_nodes: false,
};
let er = tree::build(
&extentref,
physical(obj::BLOCKREFTREE, 0x52, Layout::Variable),
alloc,
next_oid,
)?;
let sm = tree::build(
&[],
physical(obj::SNAPMETATREE, 0x52, Layout::Variable),
alloc,
next_oid,
)?;
let fs = tree::build(
&fs_records,
TreeKind {
layout: Layout::Variable,
subtype: obj::FSTREE,
tree_flags: 0x42,
virtual_nodes: true,
},
alloc,
next_oid,
)?;
let mut mapped: Vec<(Vec<u8>, Vec<u8>)> = fs
.mapped
.iter()
.map(|&(oid, paddr)| omap_record(oid, XID, paddr))
.collect();
mapped.sort_by(|a, b| crate::fs::compare_u64_pairs(&a.0, &b.0));
let om = tree::build(
&mapped,
physical(
obj::OMAP,
0x12,
Layout::Fixed {
key_size: 16,
val_size: 16,
},
),
alloc,
next_oid,
)?;
// The volume's object map (not manually managed), resolving the file-system tree's nodes.
{
let mut b = Block::new();
b.header(omap_obj, XID, obj::PHYSICAL | obj::OMAP, 0);
b.u32(32, 0); // om_flags
b.u32(40, obj::PHYSICAL | obj::BTREE); // om_tree_type
b.u32(44, obj::PHYSICAL | obj::BTREE); // om_snapshot_tree_type
b.u64(48, om.root); // om_tree_oid
blocks.push((omap_obj, b.seal()));
}
for t in [er.nodes, sm.nodes, fs.nodes, om.nodes] {
blocks.extend(t);
}
// Every block the volume owns but its superblock.
let alloc_count = alloc.next() - first;
let sb = alloc.take(1).ok_or(TreeError::NoSpace)?;
let mut b = superblock(&Super {
index: spec.index,
name: spec.name,
uuid: spec.uuid,
role: spec.role,
features: spec.features,
incompat: spec.incompat,
fs_flags: apfs::FS_UNENCRYPTED,
alloc_count,
omap: omap_obj,
root: fs.root,
extentref: er.root,
snapmeta: sm.root,
next_obj_id: spec.next_obj_id,
next_doc_id: 3,
counts: spec.counts,
data_blocks,
group: spec.group,
t: spec.t,
});
b.header(sb_oid, XID, obj::FS, 0);
blocks.push((sb, b.seal()));
Ok(Volume {
blocks,
stream_blocks,
sb_oid,
container_omap_record: omap_record(sb_oid, XID, sb),
})
}
/// What a volume superblock records.
pub(super) struct Super<'a> {
pub index: u32,
pub name: &'a str,
pub uuid: [u8; 16],
pub role: u16,
pub features: u64,
pub incompat: u64,
pub fs_flags: u64,
/// Every block the volume owns but its superblock.
pub alloc_count: u64,
pub omap: u64,
pub root: u64,
pub extentref: u64,
pub snapmeta: u64,
pub next_obj_id: u64,
pub next_doc_id: u32,
pub counts: Counts,
/// The blocks the volume's data streams take.
pub data_blocks: u64,
pub group: [u8; 16],
pub t: u64,
}
/// A volume superblock of `s`, its object header left for the caller.
pub(super) fn superblock(s: &Super) -> Block {
let mut b = Block::new();
b.u32(apfs::MAGIC, APFS_MAGIC);
b.u32(apfs::FS_INDEX, s.index);
b.u64(apfs::FEATURES, s.features);
b.u64(apfs::INCOMPAT, s.incompat);
b.u64(apfs::ALLOC_COUNT, s.alloc_count);
b.bytes(apfs::META_CRYPTO, &META_CRYPTO);
b.u32(apfs::ROOT_TREE_TYPE, obj::BTREE); // virtual
b.u32(apfs::EXTENTREF_TREE_TYPE, obj::PHYSICAL | obj::BTREE);
b.u32(apfs::SNAP_META_TREE_TYPE, obj::PHYSICAL | obj::BTREE);
b.u64(apfs::OMAP_OID, s.omap);
b.u64(apfs::ROOT_TREE_OID, s.root);
b.u64(apfs::EXTENTREF_TREE_OID, s.extentref);
b.u64(apfs::SNAP_META_TREE_OID, s.snapmeta);
b.u64(apfs::NEXT_OBJ_ID, s.next_obj_id);
b.u64(apfs::NUM_FILES, s.counts.files);
b.u64(apfs::NUM_DIRECTORIES, s.counts.directories);
b.u64(apfs::NUM_SYMLINKS, s.counts.symlinks);
b.u64(apfs::NUM_OTHER_FSOBJECTS, s.counts.other);
b.u64(apfs::TOTAL_BLOCKS_ALLOCED, s.data_blocks);
b.bytes(apfs::VOL_UUID, &s.uuid);
b.u64(apfs::LAST_MOD_TIME, s.t);
b.u64(apfs::FS_FLAGS, s.fs_flags);
// The program that formatted it: a name, the instant, and this transaction.
b.bytes(apfs::FORMATTED_BY, b"reims-restore");
b.u64(apfs::FORMATTED_BY + 32, s.t);
b.u64(apfs::FORMATTED_BY + 40, XID);
b.bytes(apfs::VOLNAME, s.name.as_bytes());
b.u32(apfs::NEXT_DOC_ID, s.next_doc_id);
b.u16(apfs::ROLE, s.role);
b.bytes(apfs::VOLUME_GROUP_ID, &s.group);
b.u32(apfs::FEXT_TREE_TYPE, obj::PHYSICAL | obj::BTREE);
b.u32(apfs::RESERVED_TYPE, obj::PHYSICAL | obj::BTREE);
b
}
@@ -0,0 +1,335 @@
//! What the integration tests share: containers ferrosys formats, with a System volume of
//! directories, links, a large file, every compressed layout and many small files, and a sparse
//! disk in memory to write them to.
#![allow(dead_code)]
use std::collections::BTreeMap;
use std::io::{Read, Seek, SeekFrom, Write};
use std::sync::Arc;
use ferrosys::apfs::{FormatOptions, VolumeGroup, VolumeName, VolumeRequest, format_to};
use ferrosys::{CompressedFile, Darwin, EntryKind, Metadata, SourceEntry, Timestamp};
use reims_apfs::dev::Source;
pub const FRAMEWORK: &str = "/System/Library/Frameworks/Virtualization.framework";
pub const BOOTER: &str = "/System/Library/Frameworks/Virtualization.framework/Versions/A/Resources/AVPBooter.vmapple2.bin";
pub const MANY: usize = 5000;
pub fn time() -> Timestamp {
Timestamp::from_secs(1_700_000_000)
}
/// `n` bytes no compressor shrinks.
pub fn noise(n: usize, seed: u32) -> Vec<u8> {
let mut x = seed.wrapping_mul(2_654_435_761) | 1;
(0..n)
.map(|_| {
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
x as u8
})
.collect()
}
pub fn header(kind: u32, size: usize, tail: &[u8]) -> Vec<u8> {
let mut h = b"fpmc".to_vec();
h.extend_from_slice(&kind.to_le_bytes());
h.extend_from_slice(&(size as u64).to_le_bytes());
h.extend_from_slice(tail);
h
}
pub fn zlib(b: &[u8]) -> Vec<u8> {
let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
z.write_all(b).unwrap();
z.finish().unwrap()
}
/// An LZFSE stream of one uncompressed block.
pub fn lzfse_raw(b: &[u8]) -> Vec<u8> {
let mut s = b"bvx-".to_vec();
s.extend_from_slice(&(b.len() as u32).to_le_bytes());
s.extend_from_slice(b);
s.extend_from_slice(b"bvx$");
s
}
/// A resource fork of chunks behind a table of 32-bit offsets (types 8, 10 and 12).
pub fn offset_fork(chunks: &[Vec<u8>]) -> Vec<u8> {
let mut at = 4 * (chunks.len() + 1);
let mut fork = Vec::new();
for c in chunks.iter().map(Vec::len).chain([0]) {
fork.extend_from_slice(&(at as u32).to_le_bytes());
at += c;
}
for c in chunks {
fork.extend_from_slice(c);
}
fork
}
/// A classic resource fork holding one resource of chunks (type 4): the data's offset
/// (big-endian) at 0, the resource's length there, then its chunk count and each chunk's
/// offset and length from the resource's start (little-endian).
pub fn classic_fork(chunks: &[Vec<u8>]) -> Vec<u8> {
let mut res = (chunks.len() as u32).to_le_bytes().to_vec();
let mut at = 4 + 8 * chunks.len();
for c in chunks {
res.extend_from_slice(&(at as u32).to_le_bytes());
res.extend_from_slice(&(c.len() as u32).to_le_bytes());
at += c.len();
}
for c in chunks {
res.extend_from_slice(c);
}
let mut fork = 0x100u32.to_be_bytes().to_vec();
fork.resize(0x100, 0);
fork.extend_from_slice(&(res.len() as u32).to_be_bytes());
fork.extend_from_slice(&res);
fork
}
pub fn chunks_of(content: &[u8], f: impl Fn(&[u8]) -> Vec<u8>) -> Vec<Vec<u8>> {
content.chunks(64 * 1024).map(f).collect()
}
/// The compressed files: their paths, content and stored forms.
pub fn compressed() -> Vec<(&'static str, Vec<u8>, CompressedFile)> {
let text = b"the restore reads this file through its compression header ".repeat(4000);
let short = b"hello zlib, a header held in a stream ".repeat(12);
let lzvn = b"hello".to_vec();
let mut lzvn_stream = vec![0xe0 | 5];
lzvn_stream.extend_from_slice(&lzvn);
lzvn_stream.extend_from_slice(&[0x06, 0, 0, 0, 0, 0, 0, 0]);
let fork_noise = noise(150_000, 7);
vec![
(
"/c/zlib-inline",
short.clone(),
CompressedFile::new(header(3, short.len(), &zlib(&short)), None),
),
(
"/c/lzvn-inline",
lzvn.clone(),
CompressedFile::new(header(7, lzvn.len(), &lzvn_stream), None),
),
(
"/c/stored-inline",
b"abc".to_vec(),
CompressedFile::new(header(9, 3, &[0xcc, b'a', b'b', b'c']), None),
),
(
"/c/lzfse-fork",
fork_noise.clone(),
CompressedFile::new(
header(12, fork_noise.len(), &[]),
Some(offset_fork(&chunks_of(&fork_noise, lzfse_raw))),
),
),
(
"/c/zlib-fork",
text.clone(),
CompressedFile::new(
header(4, text.len(), &[]),
Some(classic_fork(&chunks_of(&text, zlib))),
),
),
(
"/c/stored-fork",
fork_noise.clone(),
CompressedFile::new(
header(10, fork_noise.len(), &[]),
Some(offset_fork(&chunks_of(&fork_noise, |c| {
[&[0xcc][..], c].concat()
}))),
),
),
(
"/c/lzvn-raw-fork",
fork_noise.clone(),
CompressedFile::new(
header(8, fork_noise.len(), &[]),
Some(offset_fork(&chunks_of(&fork_noise, |c| {
[&[0x06][..], c].concat()
}))),
),
),
]
}
pub fn dir(path: &str) -> SourceEntry {
SourceEntry::new(path, EntryKind::Directory, Metadata::new(0o755, time()))
}
pub fn file(path: &str, content: Vec<u8>) -> SourceEntry {
SourceEntry::new(
path,
EntryKind::File(content.into()),
Metadata::new(0o644, time()),
)
}
pub fn symlink(path: &str, target: &str) -> SourceEntry {
SourceEntry::new(
path,
EntryKind::Symlink(target.as_bytes().to_vec()),
Metadata::new(0o755, time()),
)
}
pub fn system_entries() -> Vec<SourceEntry> {
let mut e = vec![];
let mut p = String::new();
for c in [
"System",
"Library",
"Frameworks",
"Virtualization.framework",
"Versions",
"A",
"Resources",
] {
p = format!("{p}/{c}");
e.push(dir(&p));
}
e.push(symlink(&format!("{FRAMEWORK}/Versions/Current"), "A"));
e.push(symlink(
&format!("{FRAMEWORK}/Resources"),
"Versions/Current/Resources",
));
e.push(symlink("/abs", "/System/Library"));
e.push(symlink("/loop", "loop"));
e.push(file(BOOTER, noise(300_000, 1)));
e.push(file("/empty", Vec::new()));
e.push(dir("/c"));
for (path, content, form) in compressed() {
e.push(file(path, content).with_darwin(Darwin::new(0).compressed(form)));
}
e.push(dir("/many"));
for i in 0..MANY {
e.push(file(&format!("/many/f{i:05}"), format!("{i}").into_bytes()));
}
e
}
/// A disk image in memory that keeps only the pages written, the rest reading as zeros; writes
/// and seeks are from `base`, so a container can be written into a partition.
#[derive(Clone, Default)]
pub struct Sparse {
pub pages: BTreeMap<u64, Vec<u8>>,
pub len: u64,
pub base: u64,
pub pos: u64,
}
pub const PAGE: u64 = 4096;
impl Sparse {
pub fn new(len: u64) -> Self {
Self {
len,
..Self::default()
}
}
pub fn page(&mut self, at: u64) -> &mut Vec<u8> {
self.pages
.entry(at / PAGE)
.or_insert_with(|| vec![0; PAGE as usize])
}
pub fn get(&self, off: u64, len: usize) -> Vec<u8> {
let mut b = vec![0; len];
self.read_at(off, &mut b).unwrap();
b
}
}
impl Write for Sparse {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let at = self.base + self.pos;
let n = buf.len().min((PAGE - at % PAGE) as usize);
self.page(at)[(at % PAGE) as usize..][..n].copy_from_slice(&buf[..n]);
self.pos += n as u64;
self.len = self.len.max(self.base + self.pos);
Ok(n)
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl Read for Sparse {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let at = self.base + self.pos;
let n = buf.len().min(self.len.saturating_sub(at) as usize);
self.read_at(at, &mut buf[..n])?;
self.pos += n as u64;
Ok(n)
}
}
impl Seek for Sparse {
fn seek(&mut self, to: SeekFrom) -> std::io::Result<u64> {
self.pos = match to {
SeekFrom::Start(x) => x,
SeekFrom::End(x) => (self.len - self.base).saturating_add_signed(x),
SeekFrom::Current(x) => self.pos.saturating_add_signed(x),
};
Ok(self.pos)
}
}
impl Source for Sparse {
fn read_at(&self, off: u64, buf: &mut [u8]) -> std::io::Result<()> {
if off + buf.len() as u64 > self.len {
return Err(std::io::ErrorKind::UnexpectedEof.into());
}
for (i, b) in buf.iter_mut().enumerate() {
let at = off + i as u64;
*b = self
.pages
.get(&(at / PAGE))
.map_or(0, |p| p[(at % PAGE) as usize]);
}
Ok(())
}
fn len(&self) -> u64 {
self.len
}
}
/// The containers' size: two volumes take a container of at least 1 GiB.
pub const CONTAINER: u64 = 1 << 30;
/// Format a container of a Data volume in slot 0 and a System volume in slot 1, joined as a
/// group, into `disk` from its `base`.
pub fn format_into(disk: &mut Sparse) {
let data = VolumeRequest::new(VolumeName::new("Data").unwrap(), [0x33; 16]);
let system = VolumeRequest::new(VolumeName::new("Macintosh HD").unwrap(), [0x22; 16])
.contents(system_entries());
let options = FormatOptions::new([0x11; 16], time(), data)
.volume(system)
.volume_group(VolumeGroup::new(1, 0));
disk.pos = 0;
format_to(
&mut *disk,
vec![file("/marker", b"data".to_vec())],
CONTAINER,
options,
)
.expect("formats");
}
pub fn container() -> Sparse {
let mut disk = Sparse::new(CONTAINER);
format_into(&mut disk);
disk
}
pub fn source(b: Sparse) -> Arc<dyn Source> {
Arc::new(b)
}
+153
View File
@@ -0,0 +1,153 @@
//! Reading containers ferrosys formats: a System volume found among a volume group, files by
//! path through symbolic links and folded case, every compressed layout, a GPT disk, and the
//! refusals.
use std::sync::Arc;
use reims_apfs::ondisk::apfs;
use reims_apfs::{Error, open};
mod common;
use common::*;
#[test]
fn reads_files_by_path_from_the_system_volume() {
let image = container();
let c = open(source(image.clone())).unwrap();
assert_eq!(c.base(), 0);
let v = c.system_volume().unwrap();
assert_eq!(
(v.index, v.name(), v.role()),
(1, "Macintosh HD", apfs::ROLE_SYSTEM)
);
let want = noise(300_000, 1);
assert_eq!(v.read_file(BOOTER).unwrap(), want);
// Through the framework's links, an absolute link, `..`, and folded case.
assert_eq!(
v.read_file(&format!("{FRAMEWORK}/Resources/AVPBooter.vmapple2.bin"))
.unwrap(),
want
);
assert_eq!(
v.read_file(
"/abs/Frameworks/Virtualization.framework/Versions/A/Resources/AVPBooter.vmapple2.bin"
)
.unwrap(),
want
);
assert_eq!(v.read_file(&format!("/c/../{BOOTER}")).unwrap(), want);
assert_eq!(v.read_file(&BOOTER.to_uppercase()).unwrap(), want);
// Its extents, read from the source, are its content.
let e = v.lookup(BOOTER).unwrap();
assert!(e.is_file() && !e.is_compressed());
let mut got = Vec::new();
for x in v.extents(&e).unwrap() {
assert_eq!(x.logical, got.len() as u64);
got.extend_from_slice(&image.get(x.offset.unwrap(), x.len as usize));
}
assert_eq!(got, want);
assert_eq!(v.read_file("/empty").unwrap(), b"");
// The other volume.
let d = c.volume(0).unwrap();
assert_eq!(d.read_file("/marker").unwrap(), b"data");
assert!(d.lookup("/System").is_err());
}
#[test]
fn finds_every_name_of_a_directory_spanning_many_nodes() {
let c = open(source(container())).unwrap();
let v = c.system_volume().unwrap();
for i in [0, 1, 777, 2500, MANY - 2, MANY - 1] {
assert_eq!(
v.read_file(&format!("/many/f{i:05}")).unwrap(),
format!("{i}").into_bytes(),
"f{i:05}"
);
}
assert!(matches!(
v.lookup(&format!("/many/f{MANY:05}")),
Err(Error::Invalid(_))
));
}
#[test]
fn decodes_every_compressed_layout() {
let c = open(source(container())).unwrap();
let v = c.system_volume().unwrap();
for (path, content, _) in compressed() {
let e = v.lookup(path).unwrap();
assert!(e.is_compressed(), "{path}");
assert_eq!(v.read_file(path).unwrap(), content, "{path}");
}
}
#[test]
fn opens_the_apfs_partition_of_a_gpt_disk() {
let ss = 512u64;
let first = 2048u64;
let mut disk = Sparse::new((first + CONTAINER / ss + 2048) * ss);
let mut g = gptman::GPT::new_from(&mut disk, ss, [0x44; 16]).unwrap();
g[1] = gptman::GPTPartitionEntry {
// 7C3457EF-0000-11AA-AA11-00306543ECAC, on disk.
partition_type_guid: [
0xef, 0x57, 0x34, 0x7c, 0, 0, 0xaa, 0x11, 0xaa, 0x11, 0x00, 0x30, 0x65, 0x43, 0xec,
0xac,
],
unique_partition_guid: [0x55; 16],
starting_lba: first,
ending_lba: first + CONTAINER / ss - 1,
attribute_bits: 0,
partition_name: "Container".into(),
};
gptman::GPT::write_protective_mbr_into(&mut disk, ss).unwrap();
g.write_into(&mut disk).unwrap();
disk.base = first * ss;
format_into(&mut disk);
disk.base = 0;
let c = open(source(disk)).unwrap();
assert_eq!(c.base(), first * ss);
let v = c.system_volume().unwrap();
assert_eq!(v.read_file(BOOTER).unwrap(), noise(300_000, 1));
let e = v.lookup(BOOTER).unwrap();
assert!(
v.extents(&e)
.unwrap()
.iter()
.all(|x| x.offset.unwrap() >= first * ss)
);
}
#[test]
fn refuses_what_is_not_there_or_does_not_check() {
let image = container();
let c = open(source(image.clone())).unwrap();
let v = c.system_volume().unwrap();
assert!(matches!(
v.lookup("/System/nothing"),
Err(Error::Invalid(_))
));
assert!(matches!(
v.lookup(&format!("{BOOTER}/below")),
Err(Error::Invalid(_))
));
assert!(matches!(v.read_file("/System"), Err(Error::Invalid(_))));
assert!(matches!(v.lookup("/loop"), Err(Error::Invalid(_))));
assert!(open(Arc::new(vec![0u8; 1 << 20])).is_err());
// Every file-system tree root with one bit flipped: the lookup's first read fails its
// checksum.
let mut bad = image;
for page in bad.pages.values_mut() {
let kind = u32::from_le_bytes(page[24..28].try_into().unwrap()) & 0xffff;
let subtype = u32::from_le_bytes(page[28..32].try_into().unwrap());
if kind == 2 && subtype == 0x0e {
page[PAGE as usize - 100] ^= 1;
}
}
let c = open(source(bad)).unwrap();
let v = c.system_volume().unwrap();
assert!(
matches!(v.lookup(BOOTER), Err(Error::Checksum { .. })),
"{:?}",
v.lookup(BOOTER)
);
}
+196
View File
@@ -0,0 +1,196 @@
//! Writing containers and reading them back: a volume copied record for record from a System
//! volume ferrosys formats (every compressed layout, resource forks among them, links and many
//! files), with entries replaced by links and a file added, as a restore makes the Data volume.
use std::io::{Seek, SeekFrom, Write};
use ferrosys::EntryKind;
use reims_apfs::fs::{self, key_header};
use reims_apfs::ondisk::{apfs, rec};
use reims_apfs::write::{self, VolumeDef, copy, fsbuild};
mod common;
use common::*;
/// The copy's container: 128000 blocks, the iBoot system container's size.
const BLOCKS: u64 = 128_000;
const T: u64 = 1_793_000_000_000_000_000;
const ADDED: &[u8] = b"an added file\n";
/// Copy `image`'s System volume into a Data volume, `/many` and `/empty` made links and
/// `System/Library/added.txt` added, and write it into a sparse disk.
fn copied(image: &Sparse) -> Sparse {
let c = reims_apfs::open(source(image.clone())).expect("open the source");
let sys = c.system_volume().expect("the source's System volume");
let records = sys.fs_tree_records().expect("read its records");
let root = sys.lookup("/").expect("its root").id;
let added = [fsbuild::Item {
path: "System/Library/added.txt".into(),
kind: fsbuild::Kind::File {
len: ADDED.len() as u64,
},
mode: 0o644,
uid: 0,
gid: 0,
bsd_flags: 0,
xattrs: Vec::new(),
}];
let out = copy::copy_tree(
&records,
root,
true,
T,
&mut |p, is_dir| match (p, is_dir) {
("many", true) => copy::Replace::Link(b"../elsewhere/many/".to_vec()),
("empty", false) => copy::Replace::Link(b"gone".to_vec()),
_ => copy::Replace::Keep,
},
&added,
)
.expect("copy the tree");
let def = VolumeDef {
name: "Data",
uuid: [0x44; 16],
role: apfs::ROLE_DATA,
system: false,
group: [0; 16],
records: out.records,
streams: out.streams.clone(),
counts: out.counts,
next_obj_id: out.next_obj_id,
seal: None,
};
let formed = write::container(BLOCKS, [0x55; 16], T, vec![def]).expect("form the container");
let mut disk = Sparse::new(BLOCKS * 4096);
for (addr, b) in &formed.blocks {
disk.seek(SeekFrom::Start(addr * 4096)).unwrap();
disk.write_all(b).unwrap();
}
for ((first, src), st) in formed.stream_blocks[0]
.iter()
.zip(&out.sources)
.zip(&out.streams)
{
let bytes = match src {
copy::StreamSource::Runs(runs) => {
let mut b = Vec::new();
for r in runs {
match r.phys {
Some(p) => b.extend(image.get(p * 4096, r.len as usize)),
None => b.resize(b.len() + r.len as usize, 0),
}
}
b
}
copy::StreamSource::Added(_) => ADDED.to_vec(),
};
assert_eq!(bytes.len() as u64, st.len, "a stream's length");
disk.seek(SeekFrom::Start(first * 4096)).unwrap();
disk.write_all(&bytes).unwrap();
}
disk
}
#[test]
fn a_copied_tree_reads_back_as_its_source() {
let image = container();
let disk = copied(&image);
let src = reims_apfs::open(source(image)).unwrap();
let sys = src.system_volume().unwrap();
let c = reims_apfs::open(source(disk)).expect("open the copy");
let vols = c.volumes().unwrap();
let data = &vols[0];
// Every file the source holds reads the same from the copy, compressed ones decoded the same
// way, but those under or at the paths made links.
let mut files = 0;
for e in system_entries() {
let path = String::from_utf8(e.path.clone()).unwrap();
if path.starts_with("/many") || path == "/empty" {
continue;
}
if let EntryKind::File(_) = e.kind {
let want = sys.read_file(&path).unwrap();
let got = data
.read_file(&path)
.unwrap_or_else(|err| panic!("{path}: {err}"));
assert!(
got == want,
"{path}: {} bytes, {} in the source",
got.len(),
want.len()
);
files += 1;
}
}
assert!(
files > 5,
"the compressed files and the booter were compared"
);
// The links the source holds are copied: the booter reads through them.
assert_eq!(
data.read_file(
"/System/Library/Frameworks/Virtualization.framework/Resources/AVPBooter.vmapple2.bin"
)
.unwrap(),
sys.read_file(
"/System/Library/Frameworks/Virtualization.framework/Resources/AVPBooter.vmapple2.bin"
)
.unwrap()
);
assert_eq!(data.read_file("/System/Library/added.txt").unwrap(), ADDED);
// `/many` and `/empty` are links to the targets given, and nothing below `/many` was copied.
let recs = data.fs_tree_records().unwrap();
let child = |name: &[u8]| {
recs.iter()
.find(|(k, _)| key_header(k) == (2, rec::DIR_REC) && fs::drec_name(k) == name)
.map(|(_, v)| u64::from_le_bytes(v[0..8].try_into().unwrap()))
.unwrap()
};
for (name, target) in [
(&b"many"[..], &b"../elsewhere/many/"[..]),
(b"empty", b"gone"),
] {
let id = child(name);
let inode = recs
.iter()
.find(|(k, _)| key_header(k) == (id, rec::INODE))
.and_then(|(_, v)| fs::Inode::parse(v))
.unwrap();
// The link keeps the replaced entry's permissions, owner and flags, but compression.
let was = sys
.lookup(&format!("/{}", String::from_utf8_lossy(name)))
.unwrap()
.inode;
assert_eq!(
inode.mode,
0o120000 | (was.mode & 0o7777),
"{}",
String::from_utf8_lossy(name)
);
assert_eq!(
(inode.owner, inode.group, inode.bsd_flags),
(was.owner, was.group, was.bsd_flags & !0x20)
);
let attr = recs
.iter()
.find(|(k, _)| {
key_header(k) == (id, rec::XATTR) && fs::xattr_name(k) == b"com.apple.fs.symlink"
})
.and_then(|(_, v)| fs::parse_xattr(v))
.unwrap();
let mut want = target.to_vec();
want.push(0);
assert_eq!(attr.1, fs::XattrData::Embedded(want));
}
let inodes = recs
.iter()
.filter(|(k, _)| key_header(k).1 == rec::INODE)
.count();
assert!(
inodes < MANY,
"nothing below /many was copied ({inodes} inodes)"
);
}
+2
View File
@@ -0,0 +1,2 @@
# reims-restore's own: the repository root's bans (architecture 17.4) are the library's, whose
# threads, locks and clocks come from its platform. reims-restore links nothing of the library.
+460
View File
@@ -0,0 +1,460 @@
# reims-restore: design
reims-restore installs macOS from an IPSW onto an arm64 VM's disk, as a restore by
Virtualization.framework (VZ) does, and writes the disk itself: it reads the IPSW where it lies,
asks Apple's signing server (TSS) for the VM's tickets, and lays out the GPT, the three APFS
containers and NVRAM as a fresh VZ restore leaves them. No VM runs, and none of Apple's code: no
AVPBooter, iBoot, restore OS or ASR. It is plain file I/O and HTTPS, so it runs on any host,
arm64 Linux and macOS among them. What it copies onto the disk is the IPSW's own files (the
system volume, the boot objects, the cryptexes, BaseSystem), as an install does.
The result is the raw disk image, the auxiliary storage (`aux.img`) and the ECID. A guest boots
from them under QEMU's `vmapple` on Ambrosia.
Facts tagged **[vz]** come from guests VZ installed: a fresh 27.2.1 (26B131) restore, never
booted, and the set-up 14.6.1, 15.6.1, 26.6.2 and 27.0.1 guests, all read through APFS clones or
read-only attachments. **[ipsw]** facts come from the IPSWs' manifests, of 14.6.1 (23G93), 15.6.1
(24G90), 26.6.2 (25G83), 27.0.1 (26A434) and 27.2.1 (26B131). **[measured]** facts come from runs
on this project's hosts, named where they are. Nothing from an IPSW or a guest is committed: the
tests use inputs written from scratch.
## Not goals
- **Booting under VZ.** The auxiliary storage's firmware region, where VZ's boot ROM finds the
personalized LLB, stays empty, and the LocalPolicies are signed by our key, not Apple's
hacktivation key. VZ can't boot our disks; Ambrosia can.
- **In-guest updates that patch the system volume.** Its seal is ours, not Apple's ("The system
volume's seal"), so a delta update, which checks the running seal against Apple's, doesn't
apply.
- **Software-update zips.** Their OS comes as file archives, not an APFS image, and their
recoveryOS as another asset. IPSWs of every supported release stay on Apple's CDN.
## The steps
1. Read the IPSW's `BuildManifest.plist` and pick the virtual Mac's identities (`vma2macosap`):
`macOS Customer` for the install, `Customer Erase Install (IPSW)` for the SFR manifest.
2. Check the VM's directory and the disk's size (at least 32 GiB); once the OS image is open,
the space free.
3. Draw the VM's ECID (unless given), the AP nonce, the seven policy nonces and the disk's and
volume group's UUIDs.
4. Ask TSS for the tickets ("Tickets").
5. Write the GPT, the three containers and their volumes ("The disk"), signing the LocalPolicies
("The LocalPolicy").
6. Write NVRAM and the ean storage into the auxiliary storage ("The auxiliary storage", "The
ean storage").
7. Flush and move the files into place ("Failure handling").
## The disk
512-byte sectors, a protective MBR and a GPT of 128 entries of 128 bytes at LBA 2, with its
backup at the end. Three partitions, all attributes 0, every GUID random **[vz]**:
| # | type | name | where |
|---|---|---|---|
| 1 | `69646961-6700-11AA-AA11-00306543ECAC` | `iBootSystemContainer` | LBA 40, 500 MiB |
| 2 | `7C3457EF-0000-11AA-AA11-00306543ECAC` | `Container` | from the first's end to the third |
| 3 | `52637672-7900-11AA-AA11-00306543ECAC` | `RecoveryOSContainer` | 5 GiB less 40 KiB, ending 7 LBAs before the last usable one |
Every reference guest has this layout on its 64 GiB disk, LBA for LBA. On other sizes the first
and third partitions keep their places from each end (`gpt.rs`).
Each partition holds one APFS container (4 KiB blocks), its volumes unencrypted and
case-insensitive. A fresh restore has these, in this order **[vz]**:
- **iBootSystemContainer:** iSCPreboot (role Preboot), xART (role xART, empty), Hardware (role
Hardware) and Recovery (role Recovery, empty). iSCPreboot holds:
- `/<G>/LocalPolicy/<LPNH>.img4` and `<LPNH>.recovery.img4`, the macOS LocalPolicies ("The
LocalPolicy");
- `/3D3287DE-280D-4619-AAAB-D97469CA9C71/LocalPolicy/<RONH>.recovery.img4`, the recoveryOS
container's LocalPolicy, which TSS signs;
- `/SFR/current/` and `/SystemRecovery/<SFR hash>/`, each with the SFR manifest
(`apticket.der`), `bootcaches.plist`, `RestoreVersion.plist` and `SystemVersion.plist`.
Hardware holds the directories `FactoryData/System/Library/Caches/com.apple.factorydata` and
`MobileActivation`; VZ's restore also leaves the logs of an activation request there, which
this one doesn't make.
- **Container:** `Macintosh HD` (role System), Preboot, Recovery, Update and Data (role Data).
System and Data form the volume group G, whose UUID is the Data volume's. There is no VM volume:
the first boot makes it. For macOS 14 there is no Data volume either ("macOS 14's Data
volume").
- **The system volume** is the IPSW's OS image's volume, sealed by reims-apfs with its own
node layout, so its root hash is ours, not the one the IPSW's signed `root_hash` carries
("The system volume's seal"). Its snapshot is `com.apple.os.update-<root hash>`.
- **Preboot**, under `/<G>/`:
- `boot/active`, the boot directory's name, and `boot/<H>/`, where H is the boot manifest's
SHA-384 in upper-case hex: `System/Library/Caches/apticket.der` (the boot manifest), the
kernel collection (`System/Library/Caches/com.apple.kernelcaches/kernelcache`), and
`usr/standalone/firmware/{devicetree,root_hash,base_system_root_hash,iBoot}.img4` and
`FUD/{StaticTrustCache,BaseSystemTrustCache}.img4`, each the IPSW's IM4P stitched to the
boot manifest, except `root_hash.img4`, whose IM4P is ours ("The system volume's seal");
- `cryptex1/current/`: the cryptexes' images (`os.dmg`, its clone `os.clone.dmg`, `app.dmg`
and, where the build has it, `rosetta.dmg`) with their `.root_hash` and `.trustcache`, the
Cryptex1 ticket (`apticket.vma2macosap.<ECID>.im4m`), the IPSW's unpersonalized one beside
it, `BuildManifest.plist`, `RestoreVersion.plist` and `SystemVersion.plist`;
- `restore/`: the restore bundle, `BuildManifest.plist`, both tickets, the restore kernel,
device tree and iBoot IM4Ps, the images' `.root_hash` and `.trustcache`, the
BootabilityBundle unpacked, `RestoreVersion.plist`, `SystemVersion.plist` and
`usr/standalone/bootcaches.plist`;
- `System/Library/CoreServices/boot.efi`, empty.
The volume's root also holds empty `staging` and `Cryptexes` directories.
- **Recovery**: `/<G>/boot/<H>/` with the same stitched objects, and
`/<G>/usr/standalone/firmware/arm64eBaseSystem.dmg`, the IPSW's BaseSystem, which the boot
directory links to.
- **Update**: the directories `Firmware`, `Hardware`, `Controller` and `db`.
- **Data**: the system volume's data template, `/System/Library/Templates/Data`, copied as
it is (modes, owners, flags, extended attributes, its own links, and the times the OS image
holds before it is sealed), except where the 9 patterns of
`/System/Library/Templates/Data.symlink-patterns` match **[vz]**. Each pattern is a glob from
the template's root, `*` within one component and `**` any depth:
- one ending in `/` matches a directory, which becomes a symbolic link to
`<one ../ per component of its parent>System/Library/Templates/Data/<path>/`, the target
ending in `/`; nothing below it is copied;
- any other matches files, each a link of the same form without the final `/`
(`Library/User Pictures/**` links every file below and keeps its directories).
A link keeps the permissions, owner and flags of the entry it replaces (`SF_RESTRICTED` on
the asset directories, 0644 on the pictures), as VZ's do **[vz]**.
The volume also gets the template's receipt,
`Library/Apple/System/Library/Receipts/com.apple.files.data-template.plist` (XML, mode
0666, `SF_RESTRICTED`), listing the patterns without their final `/` (`plan::receipt`). On
27.2.1 this predicts the 12,796 entries of VZ's Data volume path for path, link for link. VZ's
restore also rewrites the template's `com.apple.files.data-template.bom` (2,944,805 bytes to
2,716,958); this restore copies the template's as it is.
- **RecoveryOSContainer:** one Recovery volume: `/3D3287DE-280D-4619-AAAB-D97469CA9C71/boot/<SFR
hash>/` with `BuildManifest.plist`, the SFR manifest, the stitched objects and
`arm64eBaseSystem.dmg`.
What Ambrosia reads of this, to boot: the GPT; the main container's system volume (for G); in
Preboot, `boot/active` and the boot directory's objects; in iSCPreboot, the one policy in
`/<G>/LocalPolicy/` that isn't the recovery one, and `/SFR/current/apticket.der`; and NVRAM.
Each of those files is written plain, with no compression: Ambrosia's reader has no decmpfs.
### Writing the containers
`reims-apfs`'s writer (`apfs/src/write/`) forms each container in one transaction, as a freshly
formatted container is before anything mounts it: one checkpoint, empty free queues, the space
manager's main device marking every block it places as used, and every other block left zero, so
a file destination stays sparse. Where the checkpoint areas, the space manager's internal pool and
its bitmap ring go follows from the block count by `newfs_apfs`'s own sizing
(`write/geometry.rs`), checked against containers `diskutil` formatted at 500 MiB, 5 GiB, 60 GiB
and 256 GiB **[measured]**. `ferrosys`, which formats containers to the same layout, is a test
oracle only: it cannot write a sealed volume, and a container holding one cannot be handed to it.
A container records the most volumes it may hold (`nx_max_file_systems`), and the size alone
gives one per 512 MiB: 1 for the 500 MiB iBootSystemContainer, which holds four. A reader takes
only that many of the superblock's volume slots (this crate's reader, given a 500 MiB container
of four volumes sized by the default, listed one **[measured]**), so the writer gives each
container at least as many slots as it holds volumes, and sizes the checkpoint data area, which
grows with that count, from the same figure.
## The system volume's seal
The kernel mounts the system volume only if its sealed root hash equals the one the boot hands it:
Ambrosia unpacks the boot directory's `root_hash.img4` and passes its payload alone, the IM4P's
contents without the manifest, as `/chosen/system-volume-auth-blob`, and names the root snapshot
`com.apple.os.update-<hex of payload bytes 16..48>` (Ambrosia's `tree.rs`). Nothing on that path
checks the payload against the boot manifest's `isys` digest. So this restore seals the volume with
reims-apfs's own node layout and writes its own `root_hash.img4`: an IM4P tagged `isys` whose
payload has the IPSW's layout (208 bytes on 27.2.1 **[ipsw]**: the `u64` 2, the `u32` 1, the
`u32` 0x20, then three 32-byte hashes each followed by 32 zero bytes), the volume's root hash
first. The boot manifest stays the one TSS signed; its `isys` digest names Apple's root hash
IM4P, not ours, which nothing reads under Ambrosia. Reproducing Apple's seal byte for byte would
need the kernel's own B-tree node builder (reims-apfs's notes); a seal of our own needs only a
valid one.
Open: what the payload's second and third hashes are, and whether the kernel reads them; and
whether the kernel's root hash validation has a check of its own beyond the payload (Ambrosia's
lane reads it).
The cost: an in-guest update that patches the system volume (a delta) checks the running seal
against Apple's root hash, so it doesn't apply to our seal; such updates fall back to a full
install at best. Ambrosia already can't re-sign the LocalPolicy in-guest (it runs no SEP).
## Tickets
TSS signs four, each bound to the ECID (`tss.rs`):
- the boot manifest, from the install identity, with the AP nonce (its `BNCH`) and VZ's SEP nonce,
20 bytes of 0xAA (`snon`);
- the SFR manifest, from the erase identity, with the same nonces;
- the Cryptex1 ticket, with the AP nonce as `Cryptex1,Nonce` in nonce domain 0. Its `cnch` equals
the boot manifest's `BNCH`, as on a fresh VZ restore **[vz]**;
- the recoveryOS container's LocalPolicy, with `Ap,NextStageIM4MHash` the SFR manifest's
SHA-384, `Ap,RecoveryOSPolicyNonceHash` the SHA-384 of the fifth policy nonce, and
`Ap,VolumeUUID` 3D3287DE-280D-4619-AAAB-D97469CA9C71.
The unpersonalized Cryptex1 and restore tickets are the IPSW's own files.
## The LocalPolicy
The macOS LocalPolicy (`policy.rs`) is the LocalPolicy IM4P (`lpol`, version `1.0`, payload one
zero byte) stitched to a manifest whose MANP holds, on a fresh VZ restore of 27.2.1 **[vz]**:
| property | value |
|---|---|
| `BORD`, `CHIP`, `SDOM`, `ECID` | the board, chip, security domain and ECID |
| `CEPO` | 1 |
| `CPRO`, `CSEC`, `lobo`, `hrlp` | true |
| `love` | the OS's version as the boot manifest's `love` carries it, e.g. `26.2.131.0.0,0` |
| `lpnh`, `rpnh` | the SHA-384 of the second and the first policy nonce |
| `nsih` | the boot manifest's SHA-384 |
| `spih` | the Cryptex1 ticket's SHA-384 |
| `stng` | 1 |
| `vuid` | the volume group's UUID, 16 bytes |
and an `lpol` object with the IM4P's SHA-384 (`DGST`) and `EKEY` true. The recoveryOS policy
beside it has `rolp` true in place of `hrlp`, `spih` and `stng`. Each is named for its `lpnh` in
upper-case hex.
VZ's restore OS signs these with a key built into Apple's restore OS, whose chain is `img4 test
secp384r1 Root Certificate Authority`, then `Hacktivation secp384r1 Intermediate Certificate`,
then `Hacktivation secp384r1 Leaf Certificate`; the manifest carries the intermediate and the leaf.
The signature is ECDSA P-384 with SHA-384 over the MANB `SET` **[vz]**. The 27.2.1 kernel checks
it at boot: a policy with one signature byte flipped panics (`boop.c:7620`) **[measured by
Ambrosia's lane]**.
That key is Apple's alone, so the restore signs with the project's own P-384 chain and has
Ambrosia swap the kernel's anchors for it (`anchors.rs`). The kernel (AppleImage4) anchors a
policy's chain on the img4 test root, which kexts of the boot kernel collection embed byte for
byte: `com.apple.security.AppleVPBootPolicy` and `com.apple.security.AppleImage4`, which runs the
check, on every release, and `com.apple.security.Image4` as well on 27.0.1 and 27.2.1, whose
collections are the first to have that kext (14.6.1, 15.6.1 and 26.6.2 don't) **[ipsw]**. The
root, intermediate and leaf are the same lengths on all five, and so is the key's offset. The
boot policy kext also
holds the Hacktivation intermediate and leaf, and a copy of the leaf's public key 84 bytes past
the leaf's end. The kexts keep these as runs of DER walked by length, so each of the project's
certificates is exactly as long as the one it stands in for (610, 833 and 825 bytes on 27.2.1
**[ipsw]**): a private, non-critical filler extension takes up the difference, and the serial is
drawn again until the signature's length lands it. The root is self-signed with `CA:TRUE`; the
intermediate and the leaf are `CA:FALSE` with digitalSignature, nonRepudiation, keyEncipherment
and dataEncipherment, and carry the guest's own img4 extension (1.2.840.113635.100.6.1.15)
verbatim. The policy's manifest keeps its MANB as it is and is signed with the project's leaf,
the intermediate and the leaf in its chain.
The restore reads all of the guest's side from the IPSW's own boot kernel collection
(`kernelcache.rs`: the install identity's `KernelCache`, decompressed, read as a Mach-O file set,
each kext by its `LC_FILESET_ENTRY`), the one Ambrosia loads from Preboot, and finds the anchors
by their shape: the one chain in the boot policy kext's `__TEXT,__const` whose two lower
certificates carry the img4 extension, and its root in each other entry that holds it. It
writes a `Kernel > Patch` entry for each anchor (six on 27, five before it) to Ambrosia's
configuration bundle beside the disks (`config.cpio`, a `newc` cpio of `config.plist`; Ambrosia
passes over other cpio forms): the boot policy kext's intermediate, leaf, leaf key and root,
then the root in each other kext, each expecting one replacement over the kext's segments but
`__LINKEDIT`, so a count that differs stops the boot.
The restore checks each count first, the key's once the leaf is replaced, and fails on any it
doesn't expect. Apple's certificates go only into that VM's bundle, as the patches' `Find`. The
kernel's two production roots, which anchor Cryptex1 tickets and firmware, are left alone: those
still need Apple's signatures. With the swap, the 27.2.1 kernel checks the policy's signature
and its bindings (`nsih`, the nonces, the Cryptex1 ticket) as it would Apple's, with SIP on
**[measured by Ambrosia's lane]**; patching out the check itself (`boop.c:7620`) proved
infeasible there.
The chain's keys are the project's (`--lp-keys`, `root.key`, `int.key`, `leaf.key`): the root and
the intermediate sign each install's certificates at its release's lengths. Whoever can write a
VM's disk can write its NVRAM and its bundle too, so a key per VM would protect nothing. Without
the keys the restore signs with the built-in chain (`keys/`) and writes no bundle.
## The auxiliary storage
`aux.img.trimmed` is the 32 MiB QEMU attaches; `aux.img` is the same behind VZ's 16 KiB header
(bytes `a5 d5 b3 fe 97 ad 1d 27`, then u32 2 at +0x8 and u32 1 at +0x10, little-endian)
**[vz]**. Its regions are listed in the device tree's `/product/util` `regions`: (id, offset,
size) triples, the same in every supported release **[ipsw]**:
| id | offset | size | what |
|---|---|---|---|
| 1 | 0 | 10 MiB | |
| 2 | 0xA00000 | 1 MiB | NVRAM |
| 3 | 0xB00000 | 5 MiB | |
| 7 | 0x1000000 | 4 KiB | |
| 4 | 0x1001000 | 5 MiB less 4 KiB | |
| 5 | 0x1500000 | 5 MiB | |
| 6 | 0x1A00000 | 6 MiB | the ean storage |
The restore writes regions 2 and 6 (`aux.rs`). In VZ's guests region 7 starts `UMPv`, u32 1,
then u32 3 (14.6.1 to 26.6.2) or 4 (27.0.1, 27.2.1) **[vz]**; the restore leaves it empty.
NVRAM is two banks of 512 KiB, each a 32-byte header (a CHRP partition header named `nvram`, then
the Adler-32 of the bank from +0x14 at +0x10, and the generation at +0x14) and two CHRP
partitions: `common` from 0x20 and `system` from 0x60000. Entries are `name=value`, NUL-ended; a
value's runs of up to 127 zero or 0xFF bytes are kept as 0xFF and the run's length, its top bit
set for 0xFF. A fresh VZ restore leaves **[vz]**:
- in `common`: `restore-perform-shutdown=SHUTDOWN`, `restore-outcome=initial_engine_success`;
- in `system`: `auto-boot=true`; `boop-storage-nonces`, seven 16-byte policy nonces (the SHA-384
of the first is the macOS policy's `rpnh`, of the second its `lpnh`, of the fifth the recoveryOS
container's policy's `ronh`); `boop-storage-misc`, 24 bytes with 1 at 0, 1 and 12;
`boot-volume`, the main partition's type and GUID (each in GPT's byte order, read as one
big-endian number) and G, joined by colons; an empty `boot-args`; `bootdelay=0`.
Both banks are written alike, the first with the higher generation.
## The ean storage
Region 6 is where the kernel's keystore keeps its xART entries: the device tree's `/defaults`
holds `ean-storage-present` and `has-xart` **[ipsw]**. A fresh VZ restore leaves in it
**[vz]**:
- a header: u32 1 at 0, 0xEAEAEAEA at 4, the number of entries at 8, the region's size
(0x600000) at 0xC, and the end of the last entry's slot at 0x10;
- entries of 0x18 bytes from 0x1EC: the tag as a little-endian fourcc (its letters reversed on
disk), the slot's offset and length, `field_0c`, the CRC-32 of the whole slot, and a zero;
- the CRC-32 of the first 0xFFC bytes at 0xFFC;
- slots from 0x1000, each whole 4 KiB pages: `aptk` (`field_0c` 1), the SFR manifest, then the
guest's `xrtP` (5) and `xrtC` (6), a page each.
The restore writes the header and `aptk`. Left empty, every write the guest makes there fails
("AppleVirtualPlatformXART failed to eanWrite proposed (e00002bc)"), the keystore never makes its
D-key ("D-key is not set yet, cant derive M-key"), and the keys it would wrap with it can't be
made **[measured]**. With `aptk` alone, 14.6.1's keystore makes the D-key and the M-key and adds
`xrtC` and `xrtP` after `aptk`, a page each, raising the count to 3 and the end to 0x5000, with
`field_0c` 8 for both **[measured]**. What `field_0c` means is not known.
## macOS 14's Data volume
macOS 14's kernel refuses an unencrypted Data volume: its first boot panics, "unencrypted data
volume is not allowed" (`apfs_vfsops.c:2276`), in the BaseSystem environment before macOS
**[measured]**. VZ's 14.6.1 restore leaves Data encrypted (fs flags 0x100, keybags), and those of
15.6.1, 26.6.2 and 27.2.1 leave it unencrypted, as this restore writes it **[vz]**. Only the
guest's keystore can make an encrypted Data volume, so for macOS 14 (`pipeline::data_by_eacs`)
the restore leaves Data out and has the first boot make it, by EACS (erase all content and
settings):
- Preboot gets `/<G>/var/db/.com.apple.eacs`, an XML plist: `MigrationMode` 2 and
`MobileObliterationOptions` {`ObliterationType` `ObliterateDataPartition`,
`PreservedVolumeGroupUUID` G, `boot-physical-store-UUID` the main container's partition GUID,
`DisplayProgressBar` true} (`plan::eacs_cookie`). At the boot, BaseSystem's
`migrationModeSwitcher` commits boot mode `eacs`, and `mobile_obliterator` runs its phases,
makes "Macintosh HD - Data" encrypted, makes the keystore's D-key and M-key in the ean storage,
and resets the VM: 84 s from the boot mode to "EACS Obliteration completed" on the M3 Max
under HVF **[measured]**.
- EACS deletes `/<G>/LocalPolicy/*` in iSCPreboot and `boop-storage-nonces` and
`boop-storage-misc` from NVRAM **[measured]**, and only the restore can sign the macOS
LocalPolicy, so Ambrosia then stops ("LocalPolicy holds no single policy").
- The restore keeps the iBoot system container's partition as it wrote it (`isc.pre-eacs`,
sparse) and the auxiliary storage (`aux.pre-eacs`). `pipeline::finish_eacs`, after that boot,
writes the partition back and puts the two NVRAM entries back into each bank, keeping what the
guest wrote (the ean storage's keys among it), then removes the copies. It refuses while the
ean storage holds only `aptk`. The next boot unwraps the D-key, unlocks Data (boot mode
`_autounlock`) and goes to Setup Assistant **[measured]**.
So a macOS 14 VM takes one boot of the guest before it is ready (`pipeline::FirstBoot::Eacs`):
reims-ctl's `create` and the CLI's `restore` end by naming that boot and the step after it,
`reims-restore finish-eacs DIR`. On a
host, that boot needs what any boot does: QEMU's `vmapple` with Ambrosia, under HVF on a Mac or
KVM on arm64 Linux. Every later release restores without booting.
## The ECID and the result
The tool writes into the VM's directory `disk.img`, `aux.img`, `aux.img.trimmed`, and
`machine-identifier.bin`: VZ's form, a binary plist `{ECID: n}`. The ECID is random unless one is
given. Every ticket and policy is bound to it. For macOS 14 it also writes `isc.pre-eacs` and
`aux.pre-eacs` until `finish_eacs`.
## Reading the IPSW
The IPSW is never unpacked to disk:
- A stored zip member is read in place, at any offset.
- A deflated member is streamed. Every member's CRC-32 is checked as it streams.
- An Apple Encrypted Archive (`*.dmg.aea`, from 15.x on) is decrypted segment by segment
(`aea.rs`). Its key comes from Apple's key service:
1. The archive's auth data names `com.apple.wkms.fcs-key-url`. This is checked to be
`https://wkms-public.apple.com/...`.
2. That URL answers a P-256 private key in PEM.
3. The key opens `com.apple.wkms.fcs-response`'s `wrapped-key` with HPKE base mode,
DHKEM(P-256), HKDF-SHA256 and AES-256-GCM, with empty info and AAD. The result is the
archive's 32-byte key (profile 1).
- A UDIF image is unpacked chunk by chunk (`udif.rs`): zero, raw, zlib, bzip2, LZFSE, LZMA and
ADC chunks.
- A system image's APFS container is its UDIF's `Apple_APFS` partition (`image.rs`).
Each image is read where it lies, as the disk is written: nothing is unpacked to a scratch file.
**Peak scratch space:** none beyond the VM's disk and aux, and a few hundred MB of RAM for caches
(UDIF chunks, AEA segments).
## Failure handling
- The disk and aux are written under temporary names, flushed, and renamed into place only once
every step has succeeded, the machine identifier last; a rename that fails takes back those
made before it. An interrupted or failed restore leaves no file that looks finished.
- Before it writes, a restore needs the space it writes free where the VM goes: the system
volume as the OS image allocates it, the images it copies whole as the IPSW stores them (the
BaseSystem twice, the Cryptex1 images), 2 GiB for the rest (the plan's own files, 86 MB on
14.6.1; the Data volume's template, 207 MB there **[measured]**; APFS's metadata), and the
auxiliary storage twice. Every file is written uncompressed, so this is more than a restore by
Virtualization.framework takes, which compresses some (a 27.2.1 restore took 25.1 GiB from a
23.8 GiB IPSW **[measured]**). The disk is at least 32 GiB.
- SIGINT or SIGTERM cancels a restore from the CLI between steps, and the temporary files are
removed. A second signal ends the process at once.
- A member that fails its CRC, an image that fails its manifest digest, or an archive segment
that fails its HMAC or checksum stops the restore with what failed. A stored member read in
place, such as the system image, has its CRC-32 checked as it is read front to back: the read
that reaches its end fails if it is wrong.
- These also stop it with clear errors: TSS refusing (build not signed), the key service
refusing, network errors after retries, a full disk, and an IPSW without a virtual Mac identity.
## Downloading IPSWs
`reims-restore download latest` (and `reims-ctl create --ipsw latest`) downloads the current
macOS's IPSW from Apple; `reims-restore list` lists it and those downloaded. Apple offers only
its current release: another is restored from an IPSW the user has.
Apple's sources, as **measured** on 2026-11-11 (macOS 27.0.1 host, 27.2.1 current):
- `https://mesu.apple.com/assets/macos/com_apple_macOSIPSW/com_apple_macOSIPSW.xml`, the
catalog `VZMacOSRestoreImage.fetchLatestSupported` reads (its answer was this catalog's
VirtualMac2,1 URL). It lists one release for each Mac and for the virtual Mac
(VirtualMac2,1): the current one, 27.2.1 (26B131), with two builds for some new Macs alone
(26B7131, 26B8132). Each release replaces the last. VirtualMac2,1's entry has the IPSW's
version, build and URL but no digest; the physical Macs' entries for the same URL give its
SHA-1 (`FirmwareSHA1`), which `catalog.rs` takes from them and `download.rs` checks.
- `https://gdmf.apple.com/v2/pmv` lists the versions and builds Apple offers each model,
the virtual Mac's (`VMA2MACOSAP`) among them, with no URLs.
- Neither the iTunes version list (`s.mzstatic.com/version`) nor the software update catalogs
list Mac IPSWs.
So no Apple catalog names the IPSWs of earlier releases: their URLs on Apple's CDN hold a UUID
and can't be derived, and the tool keeps no list of them. The owner's call (2026-11-11): the
current release is downloaded, and any other comes from an IPSW the user has.
A download (`download.rs`) goes into `<name>.part` in its directory and only ever appends to
it: it learns the file's length first (a request for its first byte), checks the space the
rest takes, continues a part by a ranged request, and starts over by unlinking the part and
making a new one, never by truncating or rewriting a file in place. A part as long as the file
is only hashed. The whole file's SHA-1 is checked against the catalog's before it is renamed to
Apple's name, so the name never holds a file that isn't whole and checked; one that doesn't
match is removed. Each download holds a lock (`.<name>.lock`), so one runs at a time, looks
for the finished file again once it holds it, and removes it after the rename. A cancel keeps
the part for the next.
## Network
The tool talks to Apple alone: TSS (`gs.apple.com`), the AEA key service
(`wkms-public.apple.com`), Apple's catalog of IPSWs (`mesu.apple.com`) and Apple's CDN for
IPSWs. Files come through one client (`http.rs`): HTTPS to those two hosts alone, no redirect
followed unless its target is one of them. Each request carries the User-Agent
`InetURL/1.0` (`USER_AGENT` in `lib.rs`), the one community restore tools send to these
endpoints, and nothing about the host, its user or this project.
## Dependencies
All are published crates under licenses the repository accepts (GPL-2.0-or-later OR
LGPL-3.0-or-later):
- `aea-tools` (MIT OR Apache-2.0), AEA decryption. Its segment index is replaced here: its
stream counts clusters from the compressed size and panics past it;
- `hpke` (MIT/Apache-2.0) and `p256` (Apache-2.0 OR MIT), the archive key;
- `zip` (MIT), the IPSW's directory;
- `flate2`, `bzip2`, `lzfse_rust` (MIT OR Apache-2.0) and `lzma-rs` (MIT), decompression.
`bzip2` decodes with `libbz2-rs-sys`, under bzip2's own license (`bzip2-1.0.6`, BSD-style), as
the C libbzip2 is;
- `plist` (MIT), `serde_json` and `base64` (MIT OR Apache-2.0);
- `ureq` (MIT OR Apache-2.0) with rustls, HTTPS. Its default roots come from `webpki-roots`
(CDLA-Permissive-2.0, Mozilla's root store as data); TSS is verified against Apple Root CA
alone (`tss.rs`);
- `sha2`, `crc32fast`, `getrandom`, `libc`, `uuid`, `anyhow`, `clap` (MIT OR Apache-2.0);
- `p384` (Apache-2.0 OR MIT), the LocalPolicies' signatures;
- `reims-apfs` (`apfs/`, written here), the APFS containers.
Written here:
- Image4 (`img4.rs`): parsing, stitching and checking tickets against components;
- the UDIF reader. The published crates read whole partitions, not random offsets, which the
system image needs to be read where it lies;
- the GPT, NVRAM and LocalPolicy writers.
@@ -0,0 +1,293 @@
//! Prints the plan of a restore of an IPSW as a listing, one line per entry, for comparing with
//! a listing of a disk Virtualization.framework restored (docs/design.md, "The disk"). Every
//! entry made from the IPSW is listed with its size and, up to 64 MiB, the first 16 hex digits of
//! its SHA-256; the VM's own values in paths are masked: the volume group as `<G>`, the recoveryOS
//! group as `<R>`, the ECID as `<ECID>` and each 96-digit hash as `<H96>`.
//!
//! Tickets and policies are placeholders unless `--tickets DIR` gives the restored disk's
//! `boot.der` (its boot manifest), `sfr.der` (its SFR manifest) and `cx1.der` (its Cryptex1
//! ticket): then the boot objects are stitched to them and compared byte for byte. The policies
//! stay placeholders, since a restore's own are signed for its own nonces.
//!
//! With `--tickets`, the ECID is the boot manifest's, and the volume group the UUID in `DIR/group`
//! where that file exists, so neither need be named on a command line.
//!
//! `--hash-all` hashes every image whole, however big. The boot directories' root hash IM4P is made
//! with Apple's root hash, where a restore makes it with its own seal's.
//!
//! Usage: cargo run --release --example plan_listing -- IPSW [--tickets DIR] [--group UUID]
//! [--ecid HEX] [--hash-all]
use std::io::Read as _;
use std::path::PathBuf;
use std::sync::Arc;
use anyhow::{Context, Result, bail};
use reims_restore::aea::AppleKeyService;
use reims_restore::image;
use reims_restore::img4;
use reims_restore::ipsw::Ipsw;
use reims_restore::manifest::{BuildManifest, VARIANT_ERASE, VARIANT_INSTALL};
use reims_restore::plan::{self, Content, Data, Node, RECOVERY_GROUP};
use sha2::Digest as _;
use uuid::Uuid;
const HASHED: u64 = 64 << 20;
struct Args {
ipsw: PathBuf,
tickets: Option<PathBuf>,
group: Uuid,
ecid: u64,
/// Hash every image whole, however big.
hash_all: bool,
}
fn args() -> Result<Args> {
let mut a = std::env::args().skip(1);
let mut out = Args {
ipsw: PathBuf::new(),
tickets: None,
group: Uuid::from_u128(0x6767_6767),
ecid: 0x1111_2222_3333_4444,
hash_all: false,
};
while let Some(x) = a.next() {
let mut val = || a.next().with_context(|| format!("{x} needs a value"));
match x.as_str() {
"--tickets" => out.tickets = Some(val()?.into()),
"--group" => out.group = val()?.parse()?,
"--ecid" => out.ecid = u64::from_str_radix(&val()?, 16)?,
"--hash-all" => out.hash_all = true,
_ if out.ipsw.as_os_str().is_empty() => out.ipsw = x.into(),
_ => bail!("usage: plan_listing IPSW [--tickets DIR] [--group UUID] [--ecid HEX]"),
}
}
if out.ipsw.as_os_str().is_empty() {
bail!("usage: plan_listing IPSW [--tickets DIR] [--group UUID] [--ecid HEX]");
}
if let Some(d) = &out.tickets {
let boot = img4::parse_im4m(&std::fs::read(d.join("boot.der"))?)?;
if let Some(e) = boot.props.get("ECID").and_then(img4::Prop::as_int) {
out.ecid = e;
}
if let Ok(g) = std::fs::read_to_string(d.join("group")) {
out.group = g.trim().parse().context("the group file")?;
}
}
Ok(out)
}
fn main() -> Result<()> {
let args = args()?;
let ipsw = Ipsw::open(&args.ipsw)?;
let bm = BuildManifest::parse(&ipsw.read("BuildManifest.plist")?)?;
let install = bm.vma2_identity(VARIANT_INSTALL)?;
let erase = bm.vma2_identity(VARIANT_ERASE)?;
let keys = AppleKeyService::default();
let os = install.component("OS")?.path().context("OS")?.to_owned();
// A stand-in for the seal's root hash: Apple's, so that a listing with a restored disk's
// tickets matches that disk's root_hash.img4 byte for byte.
let seal = img4::RootHash::parse(
&img4::parse_im4p(
&ipsw.read(
install
.component("SystemVolume")?
.path()
.context("SystemVolume")?,
)?,
)?
.payload,
)?;
let patterns = image::open_container(&ipsw, &os, &keys)?
.system_volume()?
.read_file("/System/Library/Templates/Data.symlink-patterns")?;
let b = |s: &str| -> Arc<[u8]> { s.as_bytes().into() };
let ticket = |name: &str, placeholder: &str| -> Result<Arc<[u8]>> {
Ok(match &args.tickets {
Some(d) => std::fs::read(d.join(name))
.with_context(|| format!("read {}", d.join(name).display()))?
.into(),
None => b(placeholder),
})
};
let names: Vec<String> = ipsw.names().map(str::to_owned).collect();
let has = |n: &str| ipsw.has(n);
let p = plan::plan(&plan::Inputs {
manifest: &bm,
has: &has,
names: &names,
install,
erase,
ecid: args.ecid,
group: args.group,
boot_manifest: ticket("boot.der", "boot manifest")?,
sfr_manifest: ticket("sfr.der", "sfr manifest")?,
cryptex1_ticket: ticket("cx1.der", "cryptex1 ticket")?,
policy: ("POLICY.img4".into(), b("policy")),
policy_recovery: ("POLICY.recovery.img4".into(), b("policy recovery")),
recovery_os_policy: b("recovery os policy"),
ronh: "RONH".into(),
receipt: plan::receipt(
bm.product_version()?,
bm.build_version()?,
&String::from_utf8_lossy(&patterns),
std::time::SystemTime::now(),
),
eacs_store: None,
})?;
let masks = [
(args.group.to_string().to_uppercase(), "<G>"),
(RECOVERY_GROUP.to_string().to_uppercase(), "<R>"),
(format!("{:016X}", args.ecid), "<ECID>"),
];
let mask = |s: &str| -> String {
let mut s = s.to_owned();
for (v, n) in &masks {
s = s.replace(v.as_str(), n);
}
mask_h96(&s)
};
for (container, vols) in [
("isc", &p.isc),
("main", &p.main),
("recovery", &p.recovery),
] {
for v in vols {
println!("== {container} {} {:?}", v.name, v.role);
let entries = match &v.content {
Content::Entries(e) => e,
Content::DataTemplate { image, receipt } => {
println!(
" (the data template of {image}, and a receipt of {} bytes, {})",
receipt.len(),
hex16(receipt)
);
continue;
}
other => {
println!(" ({other:?})");
continue;
}
};
let mut rows = Vec::new();
for e in entries {
let (kind, size, extra) = match &e.node {
Node::Dir => ("d", "-".to_owned(), String::new()),
Node::Symlink(t) => ("l", t.len().to_string(), format!("-> {}", mask(t))),
Node::Clone(of) => ("f", "?".into(), format!("clone of {}", mask(of))),
Node::File(d) => {
let (size, hash) = describe(&ipsw, &keys, d, args.hash_all, &seal)?;
("f", size.to_string(), hash)
}
};
rows.push((
mask(&e.path),
format!(
"{kind} {:04o} {}:{} size={size} {} {extra}",
e.mode,
e.uid,
e.gid,
mask(&e.path)
),
));
}
rows.sort();
for (_, r) in rows {
println!("{r}");
}
}
}
Ok(())
}
/// Each run of 96 upper-case hex digits as `<H96>`.
fn mask_h96(s: &str) -> String {
let b = s.as_bytes();
let mut out = String::new();
let mut at = 0;
while at < b.len() {
let run = b[at..]
.iter()
.take_while(|c| c.is_ascii_digit() || (b'A'..=b'F').contains(c))
.count();
if run >= 96 {
out.push_str(&"<H96>".repeat(run / 96));
out.push_str(&s[at + run / 96 * 96..at + run]);
at += run;
} else if run > 0 {
out.push_str(&s[at..at + run]);
at += run;
} else {
let c = s[at..].chars().next().unwrap();
out.push(c);
at += c.len_utf8();
}
}
out
}
fn hex16(b: &[u8]) -> String {
sha2::Sha256::digest(b)
.iter()
.take(8)
.map(|x| format!("{x:02x}"))
.collect()
}
fn describe(
ipsw: &Ipsw,
keys: &AppleKeyService,
d: &Data,
hash_all: bool,
seal: &img4::RootHash,
) -> Result<(u64, String)> {
Ok(match d {
Data::Bytes(b) => (b.len() as u64, hex16(b)),
Data::Member(m) => {
let size = ipsw.member(m)?.size;
let h = if size <= HASHED {
hex16(&ipsw.read(m)?)
} else {
"big".into()
};
(size, h)
}
Data::Plain(m) => {
let (len, mut r) = image::plain_stream(ipsw, m, keys)?;
if len > HASHED && !hash_all {
(len, "big".into())
} else {
let mut h = sha2::Sha256::new();
let mut buf = vec![0u8; 1 << 20];
let mut n = 0u64;
loop {
let k = r.read(&mut buf)?;
if k == 0 {
break;
}
h.update(&buf[..k]);
n += k as u64;
}
anyhow::ensure!(n == len, "{m}: {n} bytes read of {len}");
let d = h.finalize();
(len, d.iter().take(8).map(|x| format!("{x:02x}")).collect())
}
}
Data::Stitched {
component,
member,
manifest,
} => match img4::personalize(component, &ipsw.read(member)?, manifest) {
Ok(out) => (out.len() as u64, hex16(&out)),
Err(e) => (
ipsw.member(member)?.size,
format!("stitched {component} from {member}: {e:#}"),
),
},
Data::SealedRootHash { manifest } => {
let out = img4::stitch_img4(&seal.system_im4p(), manifest);
(out.len() as u64, hex16(&out))
}
})
}
+70
View File
@@ -0,0 +1,70 @@
#!/bin/bash
# Makes the LocalPolicy signer reims-restore builds in (src/policy.rs, docs/design.md "The
# LocalPolicy"): a P-384 root, an intermediate and a leaf, the intermediate and leaf shaped as
# Image4 manifest signers are: CA:FALSE, the key usage below, and the Image4 constraints
# extension (1.2.840.113635.100.6.1.15), which names the manifest properties (MANP) and object
# properties (OBJP) a manifest may carry.
#
# The intermediate is CA:FALSE, as Apple's manifest signers are, so a generic X.509 verifier
# rejects the chain; Image4 checks it its own way.
#
# Usage: keys/make.sh DIR. It writes DIR/{root,int,leaf}.key, which stay out of the repository,
# and the files to commit: policy-leaf.key and policy-{root,intermediate,leaf}.der.
set -euo pipefail
out=$1
mkdir -p "$out"
cd "$out"
# The constraints extension's DER: SET { [MANP] SEQ { "MANP", SET { [name] SEQ { name, [0] { NULL } } } },
# [OBJP] SEQ { "OBJP", SET { [DGST] SEQ { "DGST", [0] { NULL } }, [name] SEQ { name, [1] { NULL } } } } },
# each [name] a private-class constructed tag whose number is the name's four bytes.
ext=$(python3 -I - <<'PY'
def der(tag, body):
n = len(body)
ln = bytes([n]) if n < 0x80 else bytes([0x80 | ((n.bit_length() + 7) // 8)]) + n.to_bytes((n.bit_length() + 7) // 8, 'big')
return tag + ln + body
def private(name):
num = int.from_bytes(name.encode(), 'big')
groups = []
while True:
groups.append(num & 0x7f)
num >>= 7
if not num:
break
groups.reverse()
return bytes([0xff]) + bytes([g | 0x80 for g in groups[:-1]] + [groups[-1]])
def ia5(s): return der(b'\x16', s.encode())
def entry(name, kind): return der(private(name), der(b'\x30', ia5(name) + der(bytes([0xa0 | kind]), der(b'\x05', b''))))
def group(name, entries): return der(private(name), der(b'\x30', ia5(name) + der(b'\x31', b''.join(entries))))
manp = group('MANP', [entry(n, 0) for n in ['BORD', 'CEPO', 'CHIP', 'CPRO', 'CSEC', 'ECID', 'SDOM']])
objp = group('OBJP', [entry('DGST', 0)] + [entry(n, 1) for n in ['DPRO', 'DSEC', 'EPRO', 'ESEC']])
print(der(b'\x31', manp + objp).hex().upper())
PY
)
cat > ext.cnf <<CNF
[req]
distinguished_name=dn
[dn]
[root]
basicConstraints=critical,CA:TRUE
keyUsage=critical,digitalSignature,keyCertSign,cRLSign
[img4]
basicConstraints=critical,CA:FALSE
keyUsage=critical,digitalSignature,nonRepudiation,keyEncipherment,dataEncipherment
1.2.840.113635.100.6.1.15=critical,DER:$ext
CNF
for n in root int leaf; do
[ -f $n.key ] || openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:secp384r1 -out $n.key
done
dates=(-not_before 20200101000000Z -not_after 20560101000000Z)
openssl req -new -x509 -key root.key -sha384 -subj "/CN=reims-restore LocalPolicy Root/O=reims-restore" \
"${dates[@]}" -set_serial 1 -config ext.cnf -extensions root -out root.pem
for n in int:root:Intermediate leaf:int:Leaf; do
IFS=: read -r me ca cn <<< "$n"
openssl req -new -key $me.key -subj "/CN=reims-restore LocalPolicy $cn/O=reims-restore" -config ext.cnf -out $me.csr
openssl x509 -req -in $me.csr -CA $ca.pem -CAkey $ca.key -set_serial 1 -sha384 "${dates[@]}" \
-extfile ext.cnf -extensions img4 -out $me.pem 2>/dev/null
done
openssl x509 -in root.pem -outform DER -out policy-root.der
openssl x509 -in int.pem -outform DER -out policy-intermediate.der
openssl x509 -in leaf.pem -outform DER -out policy-leaf.der
openssl pkcs8 -topk8 -nocrypt -in leaf.key -out policy-leaf.key
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,6 @@
-----BEGIN PRIVATE KEY-----
MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDDPPTKF6cpdgv9/QHKy
6HxsjfXGj15JQ/fFH9DLwI9G4wno0hqknx60mJR84EbAvuGhZANiAAS6gYPQNDh5
L6OVR30r7XThxlLMWWXvPFq2YoiJ57SeOVznAzix9yFRkwRtlLNs4M90xQSiNLG6
q2v3HVVDUhUR3xKhCZNL6kmDUhknoLSbE3rfsV9Wmja03CP8ppBOXrs=
-----END PRIVATE KEY-----
Binary file not shown.
+513
View File
@@ -0,0 +1,513 @@
//! Apple Encrypted Archives (`.aea`), as IPSWs from macOS 15 on carry their larger images: the
//! key fetched from Apple's key service and unwrapped, then the archive decrypted at random
//! offsets by `aea-tools`.
//!
//! An IPSW's archive is profile 1: a symmetric key, with no signature. Its auth data names where
//! the key is: `com.apple.wkms.fcs-key-url`, an HTTPS URL on `wkms-public.apple.com` that answers a
//! P-256 private key in PEM, and `com.apple.wkms.fcs-response`, JSON whose `enc-request` (an
//! HPKE encapsulated key) and `wrapped-key` (the sealed archive key) that private key opens with
//! HPKE's base mode: DHKEM(P-256, HKDF-SHA256), HKDF-SHA256 and AES-256-GCM, with empty info
//! and associated data.
use std::collections::VecDeque;
use std::io;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use aea_tools::reader::AeaReader;
use anyhow::{Context, Result, bail, ensure};
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as B64;
use hpke::Deserializable as _;
use crate::source::{Cursor, ReadAt};
/// The host every archive key URL must be on.
pub const KEY_HOST: &str = "wkms-public.apple.com";
/// Whether `head` starts like an Apple Encrypted Archive.
pub fn is_aea(head: &[u8]) -> bool {
head.starts_with(b"AEA1")
}
/// An archive's prologue: its profile and auth data.
#[derive(Debug)]
pub struct Prologue {
/// The profile; IPSWs use 1.
pub profile: u32,
/// The auth data's fields, in order.
pub fields: Vec<(String, Vec<u8>)>,
}
impl Prologue {
/// Reads the prologue at the start of `src`.
pub fn read(src: &dyn ReadAt) -> Result<Self> {
let mut head = [0u8; 12];
src.read_exact_at(0, &mut head)
.context("read the archive's prologue")?;
ensure!(is_aea(&head), "not an Apple Encrypted Archive");
let profile = u32::from_le_bytes([head[4], head[5], head[6], 0]);
let len = u32::from_le_bytes(head[8..12].try_into().unwrap()) as usize;
ensure!(len <= 1 << 20, "the archive's auth data is {len} bytes");
let mut ad = vec![0u8; len];
src.read_exact_at(12, &mut ad)
.context("read the archive's auth data")?;
Ok(Self {
profile,
fields: parse_auth_data(&ad)?,
})
}
/// The field called `key`.
pub fn field(&self, key: &str) -> Option<&[u8]> {
self.fields
.iter()
.find(|(k, _)| k == key)
.map(|(_, v)| v.as_slice())
}
}
/// Splits auth data into its `key\0value` fields, each after a 32-bit little-endian size that
/// counts itself.
fn parse_auth_data(mut ad: &[u8]) -> Result<Vec<(String, Vec<u8>)>> {
let mut out = Vec::new();
while !ad.is_empty() {
ensure!(
ad.len() >= 4,
"the archive's auth data ends inside a field's size"
);
let n = u32::from_le_bytes(ad[..4].try_into().unwrap()) as usize;
ensure!(
n >= 4 && n <= ad.len(),
"the archive's auth data has a field of {n} bytes"
);
let e = &ad[4..n];
let nul = e
.iter()
.position(|&b| b == 0)
.context("an auth data field has no key")?;
let key = std::str::from_utf8(&e[..nul]).context("an auth data key is not UTF-8")?;
out.push((key.to_owned(), e[nul + 1..].to_vec()));
ad = &ad[n..];
}
Ok(out)
}
/// Where an archive's key is: the key service URL, and the sealed key.
#[derive(Debug, Clone)]
pub struct KeyRequest {
/// The URL that answers the private key, on [`KEY_HOST`].
pub url: String,
/// The HPKE encapsulated key.
pub enc_request: Vec<u8>,
/// The sealed archive key: 32 bytes and a 16-byte tag.
pub wrapped_key: Vec<u8>,
}
impl KeyRequest {
/// The key request an IPSW archive's prologue carries.
pub fn from_prologue(p: &Prologue) -> Result<Self> {
ensure!(
p.profile == 1,
"the archive is of profile {}, not an IPSW's 1",
p.profile
);
let url = p
.field("com.apple.wkms.fcs-key-url")
.context("the archive names no key URL (com.apple.wkms.fcs-key-url)")?;
let url = std::str::from_utf8(url)
.context("the archive's key URL is not UTF-8")?
.to_owned();
check_key_url(&url)?;
let resp = p
.field("com.apple.wkms.fcs-response")
.context("the archive carries no sealed key (com.apple.wkms.fcs-response)")?;
let v: serde_json::Value =
serde_json::from_slice(resp).context("parse the archive's fcs-response")?;
let b64 = |k: &str| -> Result<Vec<u8>> {
let s = v
.get(k)
.and_then(|x| x.as_str())
.with_context(|| format!("the fcs-response has no {k}"))?;
B64.decode(s)
.with_context(|| format!("the fcs-response's {k} is not base64"))
};
Ok(Self {
url,
enc_request: b64("enc-request")?,
wrapped_key: b64("wrapped-key")?,
})
}
}
/// Refuses a key URL that isn't HTTPS on Apple's key service: the URL comes from the IPSW.
fn check_key_url(url: &str) -> Result<()> {
let rest = url
.strip_prefix("https://")
.with_context(|| format!("the archive's key URL {url:?} is not HTTPS"))?;
let host = rest.split(['/', '?', '#']).next().unwrap_or("");
ensure!(
host == KEY_HOST,
"the archive's key URL is on {host:?}, not Apple's key service {KEY_HOST}"
);
Ok(())
}
/// Something that answers a key URL with the private key's PEM.
pub trait KeyService {
/// Fetches `url`.
fn fetch_pem(&self, url: &str) -> Result<String>;
}
/// Apple's key service over HTTPS.
pub struct AppleKeyService {
agent: ureq::Agent,
}
impl Default for AppleKeyService {
fn default() -> Self {
let agent = ureq::Agent::config_builder()
.timeout_global(Some(Duration::from_secs(60)))
.user_agent(crate::USER_AGENT)
.build()
.into();
Self { agent }
}
}
impl KeyService for AppleKeyService {
fn fetch_pem(&self, url: &str) -> Result<String> {
check_key_url(url)?;
let mut last = None;
for attempt in 0..3 {
if attempt > 0 {
std::thread::sleep(Duration::from_secs(2 << attempt));
}
match self.agent.get(url).call() {
Ok(mut r) => {
return r
.body_mut()
.with_config()
.limit(64 << 10)
.read_to_string()
.context("read the key service's answer");
}
Err(ureq::Error::StatusCode(c)) if (400..500).contains(&c) => {
bail!(
"Apple's key service refused the archive's key ({c}): the IPSW may be too new or withdrawn"
)
}
Err(e) => last = Some(e),
}
}
Err(last.unwrap())
.context("reach Apple's key service (wkms-public.apple.com) for the archive's key")
}
}
/// The archive key: `req`'s sealed key opened with the private key in `pem`.
pub fn unwrap_key(req: &KeyRequest, pem: &str) -> Result<[u8; 32]> {
use p256::pkcs8::DecodePrivateKey as _;
type Kem = hpke::kem::DhP256HkdfSha256;
let sk = p256::SecretKey::from_pkcs8_pem(pem.trim())
.context("the key service's answer is not a P-256 private key")?;
let sk = <Kem as hpke::Kem>::PrivateKey::from_bytes(&sk.to_bytes())
.map_err(|e| anyhow::anyhow!("{e:?}"))?;
let enc = <Kem as hpke::Kem>::EncappedKey::from_bytes(&req.enc_request)
.map_err(|e| anyhow::anyhow!("the archive's enc-request is not a P-256 point: {e:?}"))?;
let key = hpke::single_shot_open::<hpke::aead::AesGcm256, hpke::kdf::HkdfSha256, Kem>(
&hpke::OpModeR::Base,
&sk,
&enc,
b"",
&req.wrapped_key,
b"",
)
.map_err(|_| anyhow::anyhow!("the key service's key doesn't open the archive's key"))?;
key.as_slice()
.try_into()
.context("the archive's key is not 32 bytes")
}
/// Fetches and unwraps the key of the archive `src` holds.
pub fn archive_key(src: &dyn ReadAt, service: &dyn KeyService) -> Result<[u8; 32]> {
let req = KeyRequest::from_prologue(&Prologue::read(src)?)?;
let pem = service.fetch_pem(&req.url)?;
unwrap_key(&req, &pem)
}
/// An archive's plaintext, read at random offsets.
///
/// `aea-tools` decrypts and checks each segment (its HMAC, its size and its SHA-256); the index
/// of segments is kept here, built as reads reach further into the archive, with the clusters
/// counted from the plaintext's size. (`aea-tools`' own stream counts them from the archive's
/// compressed size, so it never indexes a compressed archive's tail.)
pub struct Aea<S: ReadAt + Unpin> {
state: Mutex<State<S>>,
len: u64,
}
/// A decrypted segment, by its cluster and index in it.
type Segment = ((u32, u32), Arc<Vec<u8>>);
struct State<S: ReadAt + Unpin> {
reader: AeaReader<Cursor<S>>,
/// Each segment's cluster, index in it, first plaintext byte and size, in order.
segments: Vec<(u32, u32, u64, u64)>,
/// The next cluster to index, and where its plaintext starts.
next_cluster: u32,
indexed: u64,
clusters: u32,
cache: VecDeque<Segment>,
}
/// How many decrypted segments are kept.
const CACHE_SEGMENTS: usize = 64;
impl<S: ReadAt + Unpin> Aea<S> {
/// Opens the archive `src` holds with its `key`; checks the key against the archive's root
/// header.
pub fn open(src: S, key: &[u8; 32]) -> Result<Self> {
let mut reader = AeaReader::new(key, Cursor::new(src)).context("read the archive")?;
let rh = reader
.get_root_header()
.context("decrypt the archive's root header: wrong key, or a damaged archive")?;
let len = u64::from_le_bytes(rh.raw_size);
let seg = u64::from(u32::from_le_bytes(rh.segment_size));
let per = u64::from(u32::from_le_bytes(rh.segments_per_cluster));
ensure!(
seg > 0 && per > 0 && seg <= 64 << 20,
"the archive's root header is damaged"
);
let clusters =
u32::try_from(len.div_ceil(seg * per)).context("the archive has too many clusters")?;
let state = State {
reader,
segments: Vec::new(),
next_cluster: 0,
indexed: 0,
clusters,
cache: VecDeque::new(),
};
Ok(Self {
state: Mutex::new(state),
len,
})
}
}
fn damaged(e: impl std::fmt::Display) -> io::Error {
io::Error::new(
io::ErrorKind::InvalidData,
format!("the archive is damaged: {e}"),
)
}
impl<S: ReadAt + Unpin> State<S> {
/// Indexes clusters until the segment holding `offset` is known.
fn index_to(&mut self, offset: u64) -> io::Result<()> {
while self.indexed <= offset {
if self.next_cluster >= self.clusters {
return Err(damaged(format!(
"its segments end at {} bytes",
self.indexed
)));
}
let c = self.next_cluster;
let h = self.reader.get_cluster_header(c).map_err(damaged)?;
for (i, info) in h.segment_info.iter().enumerate() {
let size = u64::from(info.decompressed_size);
if size > 0 {
self.segments.push((c, i as u32, self.indexed, size));
self.indexed += size;
}
}
self.next_cluster += 1;
}
Ok(())
}
fn segment(&mut self, c: u32, s: u32) -> io::Result<Arc<Vec<u8>>> {
if let Some((_, d)) = self.cache.iter().find(|(k, _)| *k == (c, s)) {
return Ok(d.clone());
}
let d = Arc::new(self.reader.get_segment(c, s).map_err(damaged)?);
if self.cache.len() >= CACHE_SEGMENTS {
self.cache.pop_front();
}
self.cache.push_back(((c, s), d.clone()));
Ok(d)
}
}
impl<S: ReadAt + Unpin> ReadAt for Aea<S> {
fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize> {
if offset >= self.len || buf.is_empty() {
return Ok(0);
}
let mut st = self.state.lock().unwrap();
st.index_to(offset)?;
let i = st
.segments
.partition_point(|&(_, _, start, _)| start <= offset)
- 1;
let (c, s, start, size) = st.segments[i];
let seg = st.segment(c, s)?;
let d: &[u8] = &seg;
if d.len() as u64 != size {
return Err(damaged("a segment's size disagrees with its header"));
}
let within = (offset - start) as usize;
let n = buf.len().min(d.len() - within);
buf[..n].copy_from_slice(&d[within..within + n]);
Ok(n)
}
fn len(&self) -> u64 {
self.len
}
}
#[cfg(test)]
mod tests {
use super::*;
use p256::pkcs8::EncodePrivateKey as _;
#[test]
fn the_key_service_is_sent_only_the_pinned_headers() {
let svc = AppleKeyService::default();
let h = crate::sent_headers::of(|url| {
svc.agent.get(url).call().unwrap();
});
crate::sent_headers::assert_pinned(&h, &[]);
}
fn ad(fields: &[(&str, &[u8])]) -> Vec<u8> {
let mut out = Vec::new();
for (k, v) in fields {
let n = 4 + k.len() + 1 + v.len();
out.extend_from_slice(&(n as u32).to_le_bytes());
out.extend_from_slice(k.as_bytes());
out.push(0);
out.extend_from_slice(v);
}
out
}
fn prologue(profile: u32, fields: &[(&str, &[u8])]) -> Vec<u8> {
let a = ad(fields);
let mut p = b"AEA1".to_vec();
p.extend_from_slice(&profile.to_le_bytes()[..3]);
p.push(0);
p.extend_from_slice(&(a.len() as u32).to_le_bytes());
p.extend_from_slice(&a);
p
}
/// Seals `key` to a fresh P-256 key as Apple's key service would; returns the PEM and the
/// fcs-response JSON.
fn sealed(key: &[u8; 32]) -> (String, String) {
type Kem = hpke::kem::DhP256HkdfSha256;
let mut seed = [0u8; 32];
getrandom::fill(&mut seed).unwrap();
let sk = p256::SecretKey::from_slice(&{
let mut s = seed;
s[0] &= 0x7f;
s[31] |= 1;
s
})
.unwrap();
let pem = sk.to_pkcs8_pem(Default::default()).unwrap().to_string();
let pk =
<Kem as hpke::Kem>::PublicKey::from_bytes(&sk.public_key().to_sec1_bytes()).unwrap();
let mut rng = rand_core_rng();
let (enc, ct) = hpke::single_shot_seal_with_rng::<
hpke::aead::AesGcm256,
hpke::kdf::HkdfSha256,
Kem,
>(&hpke::OpModeS::Base, &pk, b"", key, b"", &mut rng)
.unwrap();
use hpke::Serializable as _;
let json = format!(
"{{\"enc-request\": \"{}\", \"wrapped-key\": \"{}\"}}",
B64.encode(enc.to_bytes()),
B64.encode(ct)
);
(pem, json)
}
fn rand_core_rng() -> impl hpke::rand_core::CryptoRng {
struct R;
impl hpke::rand_core::TryRng for R {
type Error = core::convert::Infallible;
fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
let mut b = [0u8; 4];
getrandom::fill(&mut b).unwrap();
Ok(u32::from_le_bytes(b))
}
fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
let mut b = [0u8; 8];
getrandom::fill(&mut b).unwrap();
Ok(u64::from_le_bytes(b))
}
fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
getrandom::fill(dst).unwrap();
Ok(())
}
}
impl hpke::rand_core::TryCryptoRng for R {}
R
}
#[test]
fn the_key_request_comes_from_the_auth_data_and_unwraps() {
let key = [0x5au8; 32];
let (pem, json) = sealed(&key);
let url = "https://wkms-public.apple.com/fcs-keys/abc=";
let p = prologue(
1,
&[
("com.apple.wkms.url", b"x"),
("com.apple.wkms.fcs-response", json.as_bytes()),
("com.apple.wkms.fcs-key-url", url.as_bytes()),
],
);
let pr = Prologue::read(&p).unwrap();
assert_eq!(pr.profile, 1);
let req = KeyRequest::from_prologue(&pr).unwrap();
assert_eq!(req.url, url);
assert_eq!(unwrap_key(&req, &pem).unwrap(), key);
// Another private key doesn't open it.
let (other, _) = sealed(&key);
assert!(unwrap_key(&req, &other).is_err());
}
#[test]
fn a_key_url_off_apples_key_service_is_refused() {
for url in [
"http://wkms-public.apple.com/fcs-keys/a",
"https://example.com/fcs-keys/a",
"https://wkms-public.apple.com.example.com/a",
] {
let p = prologue(
1,
&[
("com.apple.wkms.fcs-response", b"{}"),
("com.apple.wkms.fcs-key-url", url.as_bytes()),
],
);
assert!(
KeyRequest::from_prologue(&Prologue::read(&p).unwrap()).is_err(),
"{url}"
);
}
}
#[test]
fn damaged_auth_data_is_refused() {
let mut p = prologue(1, &[("k", b"v")]);
p[12] = 200;
assert!(Prologue::read(&p).is_err());
assert!(Prologue::read(&b"NOPE\0\0\0\0\0\0\0\0".to_vec()).is_err());
}
}
+828
View File
@@ -0,0 +1,828 @@
//! The LocalPolicy's trust anchors, swapped for the project's (docs/design.md, "The
//! LocalPolicy"). A LocalPolicy's manifest carries a chain, leaf and intermediate, which the
//! guest's kernel (AppleImage4) anchors on the img4 test root embedded in kexts of its boot
//! kernel collection (the boot policy kext and AppleImage4, and on 27 Image4 too); the boot
//! policy kext also holds the intermediate and leaf it expects, and a copy of the leaf's public
//! key. The restore builds the project's own chain — root, intermediate and leaf, each exactly
//! as long as the guest's certificate it stands in for, since the kexts keep the anchors as one
//! run of DER walked by length — signs the LocalPolicies with its leaf, and has Ambrosia replace
//! the guest's anchors with it in memory at boot (`Kernel > Patch` entries of its configuration,
//! one per anchor in each kext). The kernel's other roots, which anchor Cryptex1 tickets and
//! firmware, are left as they are.
//!
//! Everything taken from the guest is read from the IPSW's own kernel collection at install
//! time ([`crate::kernelcache`]): the certificates, the key, and each certificate's img4
//! extension (OID 1.2.840.113635.100.6.1.15), which the project's carry over verbatim. They are
//! found by their shape, not by their bytes: the one chain, a self-signed root and two
//! certificates under it that carry the extension, in the boot policy kext's constants; and the
//! root in each other entry that holds it. Every count a patch relies on is checked, so a release
//! that holds them otherwise fails the restore rather than the boot.
use anyhow::{Context, Result, bail, ensure};
use p384::ecdsa::SigningKey;
use p384::ecdsa::signature::Signer as _;
use sha2::Digest as _;
use crate::img4::{
BOOLEAN, CONTEXT_CONSTRUCTED, Children, Class, INTEGER, OCTET_STRING, SEQUENCE, SET, Tlv,
UNIVERSAL, UNIVERSAL_CONSTRUCTED, UTF8_STRING, put, read_tlv, read_whole, seq,
};
use crate::kernelcache::FileSet;
/// The kext whose boot policy checks a LocalPolicy, which holds the whole chain.
pub const BOOT_POLICY: &str = "com.apple.security.AppleVPBootPolicy";
/// The kext that verifies a LocalPolicy's chain against the img4 test root, which it embeds.
pub const APPLE_IMAGE4: &str = "com.apple.security.AppleImage4";
const BIT_STRING: u64 = 3;
const OBJECT_IDENTIFIER: u64 = 6;
const UTC_TIME: u64 = 23;
/// 1.2.840.113635.100.6.1.15, the img4 extension.
const OID_IMG4: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x63, 0x64, 0x06, 0x01, 0x0f];
/// 2.5.29.19, 2.5.29.15, 2.5.29.14, 2.5.29.35: basic constraints, key usage, subject and
/// authority key identifiers.
const OID_BASIC_CONSTRAINTS: &[u8] = &[0x55, 0x1d, 0x13];
const OID_KEY_USAGE: &[u8] = &[0x55, 0x1d, 0x0f];
const OID_SKI: &[u8] = &[0x55, 0x1d, 0x0e];
const OID_AKI: &[u8] = &[0x55, 0x1d, 0x23];
/// A private extension that takes up the length the project's certificates differ by: a
/// UUID-derived OID (2.25.<uuid>, ITU-T X.667) of the project's, never critical, so a verifier
/// passes over it.
const OID_FILLER: &[u8] = &[
0x69, 0x83, 0xc8, 0x84, 0xbc, 0x94, 0xe5, 0x8c, 0xda, 0x92, 0xed, 0xab, 0xe7, 0x92, 0xaf, 0xd5,
0xf8, 0x9a, 0xed, 0x68,
];
/// 2.5.4.10 and 2.5.4.3: organization and common name.
const OID_O: &[u8] = &[0x55, 0x04, 0x0a];
const OID_CN: &[u8] = &[0x55, 0x04, 0x03];
/// 1.2.840.10045.2.1, 1.3.132.0.34, 1.2.840.10045.4.3.3: an EC key, P-384, ECDSA with
/// SHA-384.
const OID_EC_KEY: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01];
const OID_P384: &[u8] = &[0x2b, 0x81, 0x04, 0x00, 0x22];
const OID_ECDSA_SHA384: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x03];
/// An uncompressed P-384 point: 0x04, then X and Y.
const POINT_LEN: usize = 97;
/// The parts of a certificate the swap reads.
struct Cert<'a> {
raw: &'a [u8],
issuer: &'a [u8],
subject: &'a [u8],
/// The subject's public key, an uncompressed point.
point: &'a [u8],
/// Each extension's OID, whether it is critical, and its value.
extensions: Vec<(&'a [u8], bool, &'a [u8])>,
}
impl<'a> Cert<'a> {
fn extension(&self, oid: &[u8]) -> Option<(bool, &'a [u8])> {
self.extensions
.iter()
.find(|(o, _, _)| *o == oid)
.map(|&(_, c, v)| (c, v))
}
}
fn is(e: &Tlv<'_>, class: Class, constructed: bool, tag: u64) -> bool {
e.class == class && e.constructed == constructed && e.tag == tag
}
/// `raw` read as an X.509 certificate, or `None` where it is not one.
fn parse_cert(raw: &[u8]) -> Option<Cert<'_>> {
let top = read_whole(raw).ok()?;
if !is(&top, Class::Universal, true, SEQUENCE) {
return None;
}
let mut c = Children::new(top.value);
let tbs = c.next().ok()??;
let alg = c.next().ok()??;
let sig = c.next().ok()??;
if !is(&tbs, Class::Universal, true, SEQUENCE)
|| !is(&alg, Class::Universal, true, SEQUENCE)
|| !is(&sig, Class::Universal, false, BIT_STRING)
|| c.next().ok()?.is_some()
{
return None;
}
let mut t = Children::new(tbs.value);
let version = t.next().ok()??;
if !is(&version, Class::Context, true, 0) {
return None;
}
let serial = t.next().ok()??;
let _sig_alg = t.next().ok()??;
let issuer = t.next().ok()??;
let _validity = t.next().ok()??;
let subject = t.next().ok()??;
let spki = t.next().ok()??;
if !is(&serial, Class::Universal, false, INTEGER)
|| !is(&issuer, Class::Universal, true, SEQUENCE)
|| !is(&subject, Class::Universal, true, SEQUENCE)
|| !is(&spki, Class::Universal, true, SEQUENCE)
{
return None;
}
let mut s = Children::new(spki.value);
let _key_alg = s.next().ok()??;
let key = s.next().ok()??;
if !is(&key, Class::Universal, false, BIT_STRING) || key.value.first() != Some(&0) {
return None;
}
let mut extensions = Vec::new();
while let Some(e) = t.next().ok()? {
if !is(&e, Class::Context, true, 3) {
continue;
}
let list = read_whole(e.value).ok()?;
let mut l = Children::new(list.value);
while let Some(x) = l.next().ok()? {
let mut f = Children::new(x.value);
let oid = f.next().ok()??;
let mut v = f.next().ok()??;
let mut critical = false;
if is(&v, Class::Universal, false, BOOLEAN) {
critical = v.value == [0xff];
v = f.next().ok()??;
}
if !is(&oid, Class::Universal, false, OBJECT_IDENTIFIER)
|| !is(&v, Class::Universal, false, OCTET_STRING)
{
return None;
}
extensions.push((oid.value, critical, v.value));
}
}
Some(Cert {
raw,
issuer: issuer.raw,
subject: subject.raw,
point: &key.value[1..],
extensions,
})
}
/// Every certificate in `b`, at the offsets where one starts, scanning past each found.
fn certs_in(b: &[u8]) -> Vec<Cert<'_>> {
let mut out = Vec::new();
let mut i = 0;
while i + 4 <= b.len() {
if b[i] == 0x30
&& b[i + 1] == 0x82
&& let Ok((e, _)) = read_tlv(&b[i..])
&& let Some(c) = parse_cert(e.raw)
{
i += c.raw.len();
out.push(c);
continue;
}
i += 1;
}
out
}
/// How often `needle` occurs in `hay`, overlaps counted.
fn count(hay: &[u8], needle: &[u8]) -> usize {
if needle.is_empty() || hay.len() < needle.len() {
return 0;
}
hay.windows(needle.len()).filter(|w| *w == needle).count()
}
/// The guest's anchors, as its kernel collection holds them.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Guest {
pub root: Vec<u8>,
pub intermediate: Vec<u8>,
pub leaf: Vec<u8>,
/// The leaf's public key, which the boot policy kext also keeps on its own.
pub point: Vec<u8>,
/// The intermediate's and the leaf's img4 extension values.
pub intermediate_img4: Vec<u8>,
pub leaf_img4: Vec<u8>,
/// The entries other than the boot policy kext that embed the root, in the collection's
/// order: [`APPLE_IMAGE4`] among them.
pub root_kexts: Vec<String>,
}
/// Each kext's segments that Ambrosia patches: all but `__LINKEDIT`, which the whole collection
/// shares.
fn patched_segments<'a>(fs: &FileSet<'a>, id: &str) -> Result<Vec<&'a [u8]>> {
Ok(fs
.segments(id)?
.into_iter()
.filter(|(n, _)| n != "__LINKEDIT")
.map(|(_, b)| b)
.collect())
}
fn count_in(segments: &[&[u8]], needle: &[u8]) -> usize {
segments.iter().map(|s| count(s, needle)).sum()
}
/// Find the guest's anchors in kernel collection `fs`, checking every count the patches rely
/// on.
///
/// # Errors
///
/// A kext is missing, the boot policy kext holds no chain or more than one, or a count differs
/// from what the patches expect.
pub fn guest(fs: &FileSet) -> Result<Guest> {
let consts = fs.section(BOOT_POLICY, "__TEXT", "__const")?;
let certs = certs_in(consts);
let mut chains = Vec::new();
for leaf in &certs {
for inter in certs
.iter()
.filter(|c| c.subject == leaf.issuer && c.raw != leaf.raw)
{
for root in certs
.iter()
.filter(|c| c.subject == inter.issuer && c.issuer == c.subject)
{
if leaf.extension(OID_IMG4).is_some() && inter.extension(OID_IMG4).is_some() {
chains.push((root, inter, leaf));
}
}
}
}
ensure!(
chains.len() == 1,
"{BOOT_POLICY} holds {} LocalPolicy chains among its {} certificates, not one",
chains.len(),
certs.len()
);
let (root, inter, leaf) = chains[0];
ensure!(
leaf.point.len() == POINT_LEN && leaf.point[0] == 4,
"the LocalPolicy leaf's key is not an uncompressed P-384 point"
);
let mut g = Guest {
root: root.raw.to_vec(),
intermediate: inter.raw.to_vec(),
leaf: leaf.raw.to_vec(),
point: leaf.point.to_vec(),
intermediate_img4: inter.extension(OID_IMG4).unwrap().1.to_vec(),
leaf_img4: leaf.extension(OID_IMG4).unwrap().1.to_vec(),
root_kexts: Vec::new(),
};
// Each patch replaces exactly one occurrence: the root once in each entry that embeds it,
// the intermediate and leaf once in the boot policy kext, and the key once more there on
// its own, outside the leaf certificate the patch before it replaces.
let bp = patched_segments(fs, BOOT_POLICY)?;
for (what, n) in [
("intermediate", count_in(&bp, &g.intermediate)),
("leaf", count_in(&bp, &g.leaf)),
("root", count_in(&bp, &g.root)),
(
"leaf key outside the leaf",
count_in(&bp, &g.point)
.saturating_sub(count_in(&bp, &g.leaf) * count(&g.leaf, &g.point)),
),
] {
ensure!(
n == 1,
"{BOOT_POLICY} holds the LocalPolicy {what} {n} times, not once"
);
}
for id in fs.ids().filter(|id| *id != BOOT_POLICY) {
let n = count_in(&patched_segments(fs, id)?, &g.root);
ensure!(n <= 1, "{id} holds the img4 test root {n} times, not once");
if n == 1 {
g.root_kexts.push(id.to_owned());
}
}
ensure!(
g.root_kexts.iter().any(|id| id == APPLE_IMAGE4),
"{APPLE_IMAGE4} does not hold the img4 test root"
);
Ok(g)
}
/// The project's keys: its root's, its intermediate's and its leaf's, which signs the
/// LocalPolicies.
pub struct Keys {
pub root: SigningKey,
pub intermediate: SigningKey,
pub leaf: SigningKey,
}
impl Keys {
/// The keys in `dir`: `root.key`, `int.key` and `leaf.key`, each a P-384 private key in PEM
/// (PKCS#8 or SEC1).
///
/// # Errors
///
/// A file is missing or not such a key.
pub fn load(dir: &std::path::Path) -> Result<Self> {
let key = |name: &str| -> Result<SigningKey> {
use p384::pkcs8::DecodePrivateKey as _;
let p = dir.join(name);
let pem =
std::fs::read_to_string(&p).with_context(|| format!("read {}", p.display()))?;
let k = p384::SecretKey::from_pkcs8_pem(&pem)
.or_else(|_| p384::SecretKey::from_sec1_pem(&pem))
.with_context(|| format!("{} is not a P-384 private key in PEM", p.display()))?;
Ok(SigningKey::from(k))
};
Ok(Self {
root: key("root.key")?,
intermediate: key("int.key")?,
leaf: key("leaf.key")?,
})
}
}
/// The project's chain, each certificate as long as the guest's it stands in for.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Chain {
pub root: Vec<u8>,
pub intermediate: Vec<u8>,
pub leaf: Vec<u8>,
/// The leaf's public key, an uncompressed point.
pub point: Vec<u8>,
}
fn oid(o: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
put(&mut out, UNIVERSAL, OBJECT_IDENTIFIER, o);
out
}
fn octets(v: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
put(&mut out, UNIVERSAL, OCTET_STRING, v);
out
}
fn bits(unused: u8, v: &[u8]) -> Vec<u8> {
let mut b = vec![unused];
b.extend_from_slice(v);
let mut out = Vec::new();
put(&mut out, UNIVERSAL, BIT_STRING, &b);
out
}
/// A name of organization `reims-restore` and common name `cn`.
fn name(cn: &str) -> Vec<u8> {
let rdn = |o: &[u8], v: &str| {
let mut s = Vec::new();
put(&mut s, UNIVERSAL, UTF8_STRING, v.as_bytes());
let mut set = Vec::new();
put(&mut set, UNIVERSAL_CONSTRUCTED, SET, &seq(&[&oid(o), &s]));
set
};
seq(&[&rdn(OID_O, "reims-restore"), &rdn(OID_CN, cn)])
}
fn extension(o: &[u8], critical: bool, value: &[u8]) -> Vec<u8> {
let mut crit = Vec::new();
if critical {
put(&mut crit, UNIVERSAL, BOOLEAN, &[0xff]);
}
seq(&[&oid(o), &crit, &octets(value)])
}
fn point_of(k: &SigningKey) -> Vec<u8> {
k.verifying_key().to_sec1_point(false).as_bytes().to_vec()
}
/// What a certificate of the chain is.
struct Spec<'a> {
subject: &'a str,
issuer: &'a str,
key: &'a SigningKey,
signer: &'a SigningKey,
/// The root's extensions, or a certificate under it carrying this img4 extension value.
img4: Option<&'a [u8]>,
len: usize,
}
/// A certificate of `spec` exactly `spec.len` bytes long: the filler extension sized to make
/// up the difference, and the serial drawn again until the signature's DER length lands it.
fn certificate(spec: &Spec) -> Result<Vec<u8>> {
let point = point_of(spec.key);
let sha = sha2::Sha256::digest(&point);
let key_id = &sha[..20];
let alg = seq(&[&oid(OID_ECDSA_SHA384)]);
let spki = seq(&[&seq(&[&oid(OID_EC_KEY), &oid(OID_P384)]), &bits(0, &point)]);
let utc = |s: &str| {
let mut out = Vec::new();
put(&mut out, UNIVERSAL, UTC_TIME, s.as_bytes());
out
};
let validity = seq(&[&utc("260101000000Z"), &utc("491231235959Z")]);
let mut fixed: Vec<Vec<u8>> = Vec::new();
match spec.img4 {
None => {
let mut ca = Vec::new();
put(&mut ca, UNIVERSAL, BOOLEAN, &[0xff]);
fixed.push(extension(OID_BASIC_CONSTRAINTS, true, &seq(&[&ca])));
// digitalSignature, keyCertSign, cRLSign.
fixed.push(extension(OID_KEY_USAGE, true, &bits(1, &[0x86])));
fixed.push(extension(OID_SKI, false, &octets(key_id)));
let mut aki = Vec::new();
put(&mut aki, 0x80, 0, key_id);
fixed.push(extension(OID_AKI, false, &seq(&[&aki])));
}
Some(img4) => {
fixed.push(extension(OID_BASIC_CONSTRAINTS, true, &seq(&[])));
// digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment.
fixed.push(extension(OID_KEY_USAGE, true, &bits(4, &[0xf0])));
fixed.push(extension(OID_IMG4, true, img4));
}
}
let mut filler = 0usize;
for attempt in 0u64..4096 {
// An eight-byte serial, its top bit clear and its top byte not zero, so its encoding's
// length never changes.
let mut s = [0u8; 8];
getrandom::fill(&mut s)
.map_err(|e| anyhow::anyhow!("no random bytes for a serial: {e}"))?;
s[0] = (s[0] & 0x7f).max(1);
let mut serial = Vec::new();
put(&mut serial, UNIVERSAL, INTEGER, &s);
let mut exts = fixed.clone();
exts.push(extension(OID_FILLER, false, &octets(&vec![0u8; filler])));
let mut ext_list = Vec::new();
put(
&mut ext_list,
CONTEXT_CONSTRUCTED,
3,
&seq(&exts.iter().map(Vec::as_slice).collect::<Vec<_>>()),
);
let mut version = Vec::new();
put(&mut version, CONTEXT_CONSTRUCTED, 0, &[0x02, 0x01, 0x02]);
let tbs = seq(&[
&version,
&serial,
&alg,
&name(spec.issuer),
&validity,
&name(spec.subject),
&spki,
&ext_list,
]);
let sig: p384::ecdsa::Signature = spec.signer.sign(&tbs);
let cert = seq(&[&tbs, &alg, &bits(0, sig.to_der().as_bytes())]);
if cert.len() == spec.len {
return Ok(cert);
}
// Grow or shrink the filler by the difference, but keep drawing once it is near: the
// signature's length varies by a byte or two from one serial to the next.
let want = (filler as i64 + spec.len as i64 - cert.len() as i64).max(0) as usize;
if want != filler && attempt % 8 == 0 {
filler = want;
}
}
bail!("no certificate of {} bytes for {}", spec.len, spec.subject)
}
/// The project's chain for `guest`, from `keys`.
///
/// # Errors
///
/// No certificate of a guest's length can be made (one shorter than the fixed parts).
pub fn chain(guest: &Guest, keys: &Keys) -> Result<Chain> {
let (root_n, inter_n, leaf_n) = (
"reims-restore secp384r1 Root",
"reims-restore secp384r1 Intermediate",
"reims-restore secp384r1 Leaf",
);
let root = certificate(&Spec {
subject: root_n,
issuer: root_n,
key: &keys.root,
signer: &keys.root,
img4: None,
len: guest.root.len(),
})?;
let intermediate = certificate(&Spec {
subject: inter_n,
issuer: root_n,
key: &keys.intermediate,
signer: &keys.root,
img4: Some(&guest.intermediate_img4),
len: guest.intermediate.len(),
})?;
let leaf = certificate(&Spec {
subject: leaf_n,
issuer: inter_n,
key: &keys.leaf,
signer: &keys.intermediate,
img4: Some(&guest.leaf_img4),
len: guest.leaf.len(),
})?;
Ok(Chain {
root,
intermediate,
leaf,
point: point_of(&keys.leaf),
})
}
/// Ambrosia's `Kernel > Patch` entries that swap `guest`'s anchors for `chain`'s, in the order
/// they apply: the boot policy kext's intermediate, leaf, leaf key (the copy outside the leaf,
/// the one left once the leaf is replaced) and root, then the root in each other kext. Each
/// expects one replacement, so a count that differs stops the boot.
#[must_use]
pub fn patches(guest: &Guest, chain: &Chain) -> plist::Value {
let entry = |id: &str, find: &[u8], replace: &[u8]| {
let mut d = plist::Dictionary::new();
d.insert("Identifier".into(), plist::Value::String(id.into()));
d.insert("Find".into(), plist::Value::Data(find.to_vec()));
d.insert("Replace".into(), plist::Value::Data(replace.to_vec()));
d.insert("Expect".into(), plist::Value::Integer(1.into()));
plist::Value::Dictionary(d)
};
let mut list = vec![
entry(BOOT_POLICY, &guest.intermediate, &chain.intermediate),
entry(BOOT_POLICY, &guest.leaf, &chain.leaf),
entry(BOOT_POLICY, &guest.point, &chain.point),
entry(BOOT_POLICY, &guest.root, &chain.root),
];
for id in &guest.root_kexts {
list.push(entry(id, &guest.root, &chain.root));
}
plist::Value::Array(list)
}
/// Ambrosia's configuration bundle of `config`: a `newc` cpio archive (magic `070701`, the
/// form Ambrosia reads) of one file, `config.plist`, in XML.
///
/// # Errors
///
/// The plist does not serialise.
pub fn config_bundle(config: &plist::Dictionary) -> Result<Vec<u8>> {
let mut xml = Vec::new();
plist::Value::Dictionary(config.clone())
.to_writer_xml(&mut xml)
.context("write the configuration's plist")?;
let mut out = Vec::new();
newc_entry(&mut out, 1, 0o100644, "config.plist", &xml);
newc_entry(&mut out, 0, 0, "TRAILER!!!", &[]);
Ok(out)
}
/// One `newc` entry: its header's thirteen 8-digit hex fields, its name with its NUL, and its
/// data, each padded to four bytes.
fn newc_entry(out: &mut Vec<u8>, ino: u32, mode: u32, name: &str, data: &[u8]) {
let fields = [
ino,
mode,
0,
0,
u32::from(mode != 0),
0,
data.len() as u32,
0,
0,
0,
0,
name.len() as u32 + 1,
0,
];
out.extend_from_slice(b"070701");
for f in fields {
out.extend_from_slice(format!("{f:08X}").as_bytes());
}
out.extend_from_slice(name.as_bytes());
out.push(0);
while out.len() % 4 != 0 {
out.push(0);
}
out.extend_from_slice(data);
while out.len() % 4 != 0 {
out.push(0);
}
}
/// The configuration of a VM's anchors: `Kernel > Patch` of [`patches`].
#[must_use]
pub fn config(guest: &Guest, chain: &Chain) -> plist::Dictionary {
let mut kernel = plist::Dictionary::new();
kernel.insert("Patch".into(), patches(guest, chain));
let mut d = plist::Dictionary::new();
d.insert("Kernel".into(), plist::Value::Dictionary(kernel));
d
}
#[cfg(test)]
mod tests {
use super::*;
use crate::kernelcache::tests::fileset;
const IMAGE4: &str = "com.apple.security.Image4";
fn key(n: u8) -> SigningKey {
SigningKey::from(p384::SecretKey::from_slice(&[n; 48]).unwrap())
}
// A guest's chain made here, of its own keys and an img4 extension of made-up bytes, at
// lengths of its own: the root self-signed, the two under it with the extension.
fn guest_chain() -> (Chain, Vec<u8>, Vec<u8>) {
let keys = Keys {
root: key(1),
intermediate: key(2),
leaf: key(3),
};
let img4_i = seq(&[&octets(b"an intermediate's made-up img4 properties")]);
let img4_l = seq(&[&octets(b"a leaf's made-up img4 properties")]);
let g = Guest {
root: vec![0; 600],
intermediate: vec![0; 820],
leaf: vec![0; 810],
point: Vec::new(),
intermediate_img4: img4_i.clone(),
leaf_img4: img4_l.clone(),
root_kexts: Vec::new(),
};
(chain(&g, &keys).unwrap(), img4_i, img4_l)
}
#[test]
fn a_chain_is_built_at_the_guests_lengths_and_verifies() {
let (c, img4_i, _) = guest_chain();
assert_eq!(
(c.root.len(), c.intermediate.len(), c.leaf.len()),
(600, 820, 810)
);
let root = parse_cert(&c.root).unwrap();
let inter = parse_cert(&c.intermediate).unwrap();
let leaf = parse_cert(&c.leaf).unwrap();
assert_eq!(root.issuer, root.subject);
assert_eq!(inter.issuer, root.subject);
assert_eq!(leaf.issuer, inter.subject);
assert_eq!(leaf.point, c.point);
assert_eq!(inter.extension(OID_IMG4), Some((true, &img4_i[..])));
assert!(root.extension(OID_IMG4).is_none());
// Each signature verifies under its issuer's key.
use p384::ecdsa::signature::Verifier as _;
for (cert, issuer) in [
(&c.root, &root),
(&c.intermediate, &root),
(&c.leaf, &inter),
] {
let top = read_whole(cert).unwrap();
let mut ch = Children::new(top.value);
let tbs = ch.next().unwrap().unwrap();
ch.next().unwrap();
let sig = ch.next().unwrap().unwrap();
let vk = p384::ecdsa::VerifyingKey::from_sec1_bytes(issuer.point).unwrap();
let s = p384::ecdsa::Signature::from_der(&sig.value[1..]).unwrap();
vk.verify(tbs.raw, &s).unwrap();
}
}
/// A boot policy kext's constants as the guest's hold them, made here: other data, the
/// chain, the leaf's key on its own, and an unrelated self-signed certificate.
fn kernel(g: &Chain, other: &[u8]) -> Vec<u8> {
let mut bp = b"some constants before".to_vec();
bp.extend_from_slice(&g.root);
bp.extend_from_slice(&g.intermediate);
bp.extend_from_slice(&g.leaf);
bp.extend_from_slice(&[0x5a; 84]);
bp.extend_from_slice(&g.point);
bp.extend_from_slice(other);
let mut i4 = b"image4's constants".to_vec();
i4.extend_from_slice(&g.root);
let mut a4 = other.to_vec();
a4.extend_from_slice(&g.root);
fileset(&[
("com.apple.kernel", b"the kernel"),
(BOOT_POLICY, &bp),
(APPLE_IMAGE4, &a4),
(IMAGE4, &i4),
])
}
#[test]
fn the_guests_anchors_are_found_by_their_shape() {
let (g, img4_i, img4_l) = guest_chain();
// A self-signed certificate that anchors nothing here, as the production roots don't.
let other = certificate(&Spec {
subject: "another root",
issuer: "another root",
key: &key(9),
signer: &key(9),
img4: None,
len: 640,
})
.unwrap();
let kc = kernel(&g, &other);
let fs = FileSet::parse(&kc).unwrap();
let found = guest(&fs).unwrap();
assert_eq!(found.root, g.root);
assert_eq!(found.intermediate, g.intermediate);
assert_eq!(found.leaf, g.leaf);
assert_eq!(found.point, g.point);
assert_eq!(
(&found.intermediate_img4, &found.leaf_img4),
(&img4_i, &img4_l)
);
// The project's chain at those lengths, and the six patches in order.
let ours = chain(
&found,
&Keys {
root: key(4),
intermediate: key(5),
leaf: key(6),
},
)
.unwrap();
let p = patches(&found, &ours);
let list = p.as_array().unwrap();
assert_eq!(list.len(), 6);
let field = |i: usize, k: &str| list[i].as_dictionary().unwrap()[k].clone();
assert_eq!(field(2, "Find").as_data().unwrap(), &g.point[..]);
assert_eq!(field(2, "Replace").as_data().unwrap(), &ours.point[..]);
assert_eq!(found.root_kexts, [APPLE_IMAGE4, IMAGE4]);
assert_eq!(field(4, "Identifier").as_string(), Some(APPLE_IMAGE4));
assert_eq!(field(5, "Identifier").as_string(), Some(IMAGE4));
for i in 0..6 {
assert_eq!(
field(i, "Find").as_data().unwrap().len(),
field(i, "Replace").as_data().unwrap().len()
);
assert_eq!(field(i, "Expect").as_unsigned_integer(), Some(1));
}
}
#[test]
fn a_count_the_patches_dont_expect_fails() {
let (g, _, _) = guest_chain();
// The root twice in Image4: its patch would replace two.
let mut i4 = g.root.clone();
i4.extend_from_slice(&g.root);
let mut bp = g.root.clone();
bp.extend_from_slice(&g.intermediate);
bp.extend_from_slice(&g.leaf);
bp.extend_from_slice(&g.point);
let kc = fileset(&[(BOOT_POLICY, &bp), (APPLE_IMAGE4, &g.root), (IMAGE4, &i4)]);
let e = guest(&FileSet::parse(&kc).unwrap()).unwrap_err();
assert!(format!("{e}").contains("2 times"), "{e}");
// No standalone copy of the leaf's key.
let mut bp = g.root.clone();
bp.extend_from_slice(&g.intermediate);
bp.extend_from_slice(&g.leaf);
let kc = fileset(&[
(BOOT_POLICY, &bp),
(APPLE_IMAGE4, &g.root),
(IMAGE4, &g.root),
]);
assert!(guest(&FileSet::parse(&kc).unwrap()).is_err());
}
#[test]
fn the_root_is_swapped_in_each_kext_that_holds_it() {
let (g, _, _) = guest_chain();
let mut bp = g.root.clone();
bp.extend_from_slice(&g.intermediate);
bp.extend_from_slice(&g.leaf);
bp.extend_from_slice(&g.point);
// AppleImage4 alone, with no Image4 in the collection: five patches.
let kc = fileset(&[(BOOT_POLICY, &bp), (APPLE_IMAGE4, &g.root)]);
let found = guest(&FileSet::parse(&kc).unwrap()).unwrap();
assert_eq!(found.root_kexts, [APPLE_IMAGE4]);
let ours = chain(
&found,
&Keys {
root: key(4),
intermediate: key(5),
leaf: key(6),
},
)
.unwrap();
assert_eq!(patches(&found, &ours).as_array().unwrap().len(), 5);
// A root in another kext, and in no AppleImage4: the kext that verifies is unpatched.
let kc = fileset(&[
(BOOT_POLICY, &bp),
(APPLE_IMAGE4, b"no root"),
(IMAGE4, &g.root),
]);
let e = guest(&FileSet::parse(&kc).unwrap()).unwrap_err();
assert!(format!("{e}").contains("does not hold"), "{e}");
}
#[test]
fn the_bundle_is_a_newc_archive_of_the_config() {
let mut d = plist::Dictionary::new();
d.insert(
"Kernel".into(),
plist::Value::Dictionary(plist::Dictionary::new()),
);
let b = config_bundle(&d).unwrap();
assert_eq!(&b[..6], b"070701");
assert_eq!(b.len() % 4, 0);
let name_at = 110;
assert_eq!(&b[name_at..name_at + 13], b"config.plist\0");
let size = usize::from_str_radix(std::str::from_utf8(&b[54..62]).unwrap(), 16).unwrap();
let data_at = (name_at + 13).div_ceil(4) * 4;
let back = plist::Value::from_reader_xml(&b[data_at..data_at + size]).unwrap();
assert_eq!(back, plist::Value::Dictionary(d));
assert!(b.windows(10).any(|w| w == b"TRAILER!!!"));
}
}
@@ -0,0 +1,31 @@
# Apple Root CA, the root of gs.apple.com's TLS chain (Apple Server Authentication CA under it):
# a public certificate, as Apple publishes it. SHA-256 of its DER:
# B0B1730ECBC7FF4505142C49F1295E6EDA6BCAED7E2C68C5BE91B5A11001F024 (tss.rs checks it).
-----BEGIN CERTIFICATE-----
MIIEuzCCA6OgAwIBAgIBAjANBgkqhkiG9w0BAQUFADBiMQswCQYDVQQGEwJVUzET
MBEGA1UEChMKQXBwbGUgSW5jLjEmMCQGA1UECxMdQXBwbGUgQ2VydGlmaWNhdGlv
biBBdXRob3JpdHkxFjAUBgNVBAMTDUFwcGxlIFJvb3QgQ0EwHhcNMDYwNDI1MjE0
MDM2WhcNMzUwMjA5MjE0MDM2WjBiMQswCQYDVQQGEwJVUzETMBEGA1UEChMKQXBw
bGUgSW5jLjEmMCQGA1UECxMdQXBwbGUgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkx
FjAUBgNVBAMTDUFwcGxlIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
ggEKAoIBAQDkkakJH5HbHkdQ6wXtXnmELes2oldMVeyLGYne+Uts9QerIjAC6Bg+
+FAJ039BqJj50cpmnCRrEdCju+QbKsMflZ56DKRHi1vUFjczy8QPTc4UadHJGXL1
XQ7Vf1+b8iUDulWPTV0N8WQ1IxVLFVkds5T39pyez1C6wVhQZ48ItCD3y6wsIG9w
tj8BMIy3Q88PnT3zK0koGsj+zrW5DtleHNbLPbU6rfQPDgCSC7EhFi501TwN22IW
q6NxkkdTVcGvL0Gz+PvjcM3mo0xFfh9Ma1CWQYnEdGILEINBhzOKgbEwWOxaBDKM
aLOPHd5lc/9nXmW8Sdh2nzMUZaF3lMktAgMBAAGjggF6MIIBdjAOBgNVHQ8BAf8E
BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUK9BpR5R2Cf70a40uQKb3
R01/CF4wHwYDVR0jBBgwFoAUK9BpR5R2Cf70a40uQKb3R01/CF4wggERBgNVHSAE
ggEIMIIBBDCCAQAGCSqGSIb3Y2QFATCB8jAqBggrBgEFBQcCARYeaHR0cHM6Ly93
d3cuYXBwbGUuY29tL2FwcGxlY2EvMIHDBggrBgEFBQcCAjCBthqBs1JlbGlhbmNl
IG9uIHRoaXMgY2VydGlmaWNhdGUgYnkgYW55IHBhcnR5IGFzc3VtZXMgYWNjZXB0
YW5jZSBvZiB0aGUgdGhlbiBhcHBsaWNhYmxlIHN0YW5kYXJkIHRlcm1zIGFuZCBj
b25kaXRpb25zIG9mIHVzZSwgY2VydGlmaWNhdGUgcG9saWN5IGFuZCBjZXJ0aWZp
Y2F0aW9uIHByYWN0aWNlIHN0YXRlbWVudHMuMA0GCSqGSIb3DQEBBQUAA4IBAQBc
NplMLXi37Yyb3PN3m/J20ncwT8EfhYOFG5k9RzfyqZtAjizUsZAS2L70c5vu0mQP
y3lPNNiiPvl4/2vIB+x9OYOLUyDTOMSxv5pPCmv/K/xZpwUJfBdAVhEedNO3iyM7
R6PVbyTi69G3cN8PReEnyvFteO3ntRcXqNx+IjXKJdXZD9Zr1KIkIxH3oayPc4Fg
xhtbCS+SsvhESPBgOJ4V9T0mZyCKM2r3DYLP3uujL/lTaltkwGMzd/c6ByxW69oP
IQ7aunMZT7XZNn/Bh1XZp5m5MkL72NVxnn6hUrcbvZNCJBIqxw8dtk2cXmPIS4AX
UKqK1drk/NAJBzewdXUh
-----END CERTIFICATE-----
+692
View File
@@ -0,0 +1,692 @@
//! The VM's auxiliary storage: 32 MiB QEMU attaches as `aux.img.trimmed`, and the same behind
//! Virtualization.framework's 16 KiB header as `aux.img` (docs/design.md, "The auxiliary
//! storage"). A restore writes two regions of it, NVRAM and the ean storage; the firmware's own
//! regions stay empty.
use anyhow::{Result, ensure};
use uuid::Uuid;
use crate::gpt;
/// The auxiliary storage's size as QEMU attaches it.
pub const SIZE: usize = 32 << 20;
/// Virtualization.framework's header before it in `aux.img`: its magic, version 2 at 0x8, a 1
/// at 0x10, then zeroes to 16 KiB **[vz]**.
pub const HEADER_LEN: usize = 16 << 10;
const MAGIC: [u8; 8] = [0xa5, 0xd5, 0xb3, 0xfe, 0x97, 0xad, 0x1d, 0x27];
/// NVRAM's region (region 2 of the device tree's `/product/util` `regions`): 1 MiB at 0xA00000,
/// two banks of 512 KiB **[ipsw]**.
pub const NVRAM_AT: usize = 0xa0_0000;
const BANK: usize = 0x8_0000;
/// The banks' partitions: `common` from 0x20, `system` from 0x60000, to the bank's end
/// **[vz]**.
const COMMON_AT: usize = 0x20;
const SYSTEM_AT: usize = 0x6_0000;
/// The ean storage (region 6 of `regions`): 6 MiB at 0x1A00000 **[ipsw]**, where the kernel's
/// keystore keeps its xART entries (`/defaults` holds `ean-storage-present` and `has-xart`
/// **[ipsw]**). A fresh VZ restore leaves the SFR manifest in it as `aptk`, and the guest's own
/// `xrtP` and `xrtC` **[vz]**. Left empty, every write the guest makes to it fails ("failed to
/// eanWrite proposed (e00002bc)"), so the keystore never makes its D-key ("D-key is not set
/// yet") **[measured]**; with `aptk` alone, it makes the D-key and the M-key and saves them there
/// as two more entries **[measured]** (docs/design.md, "The ean storage").
pub const EAN_AT: usize = 0x1a0_0000;
const EAN_LEN: usize = 0x60_0000;
/// Its header: u32 1 at 0, 0xEAEAEAEA at 4, the number of entries at 8, the region's size at
/// 0xC, the end of the last entry's slot at 0x10 **[vz]**: the guest raises the last two as it
/// adds entries **[measured]**.
const EAN_MAGIC: u32 = 0xeaea_eaea;
/// Its entries, of 0x18 bytes from 0x1EC: the tag, its letters reversed (a little-endian
/// fourcc), the slot's offset and length, `field_0c`, the CRC-32 of the whole slot, and a zero
/// **[vz]**. `field_0c` is 1 for `aptk`, 5 for `xrtP` and 6 for `xrtC` in VZ's restores, 8 for
/// both of those a guest adds itself **[measured]**; what it means is not known.
const EAN_ENTRIES_AT: usize = 0x1ec;
/// The CRC-32 of the first 0xFFC bytes, at 0xFFC **[vz]**.
const EAN_HEADER_CRC_AT: usize = 0xffc;
/// Slots start at 0x1000 and take whole 4 KiB pages **[vz]**.
const EAN_PAGE: usize = 0x1000;
/// `aptk`'s `field_0c` **[vz]**.
const APTK_FIELD_0C: u32 = 1;
/// What a restore leaves in NVRAM: the values a fresh restore by Virtualization.framework
/// leaves, with this VM's own (docs/design.md, "NVRAM").
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Nvram {
/// The policy nonces, `boop-storage-nonces`: seven of 16 bytes. The macOS LocalPolicy's
/// `rpnh` and `lpnh` are the SHA-384 of the first and the second, the recoveryOS
/// LocalPolicy's `ronh` of the fifth **[vz]**.
pub policy_nonces: [[u8; 16]; 7],
/// The main container's partition GUID.
pub container: Uuid,
/// The volume group's UUID, the Data volume's.
pub group: Uuid,
}
/// `boop-storage-misc` as a fresh restore leaves it: 24 bytes, 1 at 0, 1 and 12 **[vz]**. What
/// they mean is not known.
const BOOP_STORAGE_MISC: [u8; 24] = {
let mut m = [0u8; 24];
m[0] = 1;
m[1] = 1;
m[12] = 1;
m
};
impl Nvram {
/// The policy nonce whose SHA-384 is the macOS LocalPolicy's `rpnh`.
pub fn remote_policy_nonce(&self) -> &[u8; 16] {
&self.policy_nonces[0]
}
/// The policy nonce whose SHA-384 is the macOS LocalPolicy's `lpnh`, and its file name.
pub fn local_policy_nonce(&self) -> &[u8; 16] {
&self.policy_nonces[1]
}
/// The policy nonce whose SHA-384 is the recoveryOS LocalPolicy's `ronh`.
pub fn recovery_policy_nonce(&self) -> &[u8; 16] {
&self.policy_nonces[4]
}
/// `boot-volume`: the main container's partition type and GUID, each in GPT's byte order
/// read as one big-endian number, and the volume group, as a fresh restore writes it
/// **[vz]**.
pub fn boot_volume(&self) -> String {
let as_stored = |u: Uuid| {
Uuid::from_bytes(gpt::guid_bytes(u))
.to_string()
.to_uppercase()
};
format!(
"{}:{}:{}",
as_stored(gpt::APFS_TYPE),
as_stored(self.container),
self.group.to_string().to_uppercase()
)
}
/// The `common` partition's entries, in order.
fn common(&self) -> Vec<(&'static str, Vec<u8>)> {
vec![
("restore-perform-shutdown", b"SHUTDOWN".to_vec()),
("restore-outcome", b"initial_engine_success".to_vec()),
]
}
/// The `system` partition's entries, in order.
fn system(&self) -> Vec<(&'static str, Vec<u8>)> {
vec![
("auto-boot", b"true".to_vec()),
("boop-storage-nonces", self.policy_nonces.concat()),
("boop-storage-misc", BOOP_STORAGE_MISC.to_vec()),
("boot-volume", self.boot_volume().into_bytes()),
("boot-args", Vec::new()),
("bootdelay", b"0".to_vec()),
]
}
/// One bank, of `generation`.
fn bank(&self, generation: u32) -> Vec<u8> {
let mut b = vec![0u8; BANK];
b[..16].copy_from_slice(&chrp_header(0x5a, "nvram", 0x20));
partition(&mut b[COMMON_AT..SYSTEM_AT], 0x71, "common", &self.common());
partition(&mut b[SYSTEM_AT..], 0x70, "system", &self.system());
b[0x14..0x18].copy_from_slice(&generation.to_le_bytes());
let sum = adler32(&b[0x14..]);
b[0x10..0x14].copy_from_slice(&sum.to_le_bytes());
b
}
}
/// The auxiliary storage as QEMU attaches it (`aux.img.trimmed`): NVRAM's two banks alike, the
/// first the newer, and the ean storage holding `sfr_manifest`.
pub fn trimmed(nvram: &Nvram, sfr_manifest: &[u8]) -> Result<Vec<u8>> {
let mut a = vec![0u8; SIZE];
a[NVRAM_AT..NVRAM_AT + BANK].copy_from_slice(&nvram.bank(2));
a[NVRAM_AT + BANK..NVRAM_AT + 2 * BANK].copy_from_slice(&nvram.bank(1));
let e = ean(sfr_manifest)?;
a[EAN_AT..EAN_AT + e.len()].copy_from_slice(&e);
Ok(a)
}
/// The ean storage's used bytes as a restore leaves them: its header, and one entry, `aptk`,
/// whose slot holds `sfr_manifest`. The rest of the region stays zero.
pub fn ean(sfr_manifest: &[u8]) -> Result<Vec<u8>> {
let slot = sfr_manifest.len().div_ceil(EAN_PAGE) * EAN_PAGE;
ensure!(
slot > 0 && EAN_PAGE + slot <= EAN_LEN,
"an SFR manifest of {} bytes doesn't fit the ean storage",
sfr_manifest.len()
);
let end = EAN_PAGE + slot;
let mut e = vec![0u8; end];
e[EAN_PAGE..EAN_PAGE + sfr_manifest.len()].copy_from_slice(sfr_manifest);
let words = |e: &mut [u8], at: usize, w: &[u32]| {
for (i, x) in w.iter().enumerate() {
e[at + 4 * i..at + 4 * i + 4].copy_from_slice(&x.to_le_bytes());
}
};
let as_u32 = |n: usize| u32::try_from(n).expect("the ean storage is 6 MiB");
words(&mut e, 0, &[1, EAN_MAGIC, 1, as_u32(EAN_LEN), as_u32(end)]);
let crc = crc32fast::hash(&e[EAN_PAGE..end]);
words(
&mut e,
EAN_ENTRIES_AT,
&[
u32::from_be_bytes(*b"aptk"),
as_u32(EAN_PAGE),
as_u32(slot),
APTK_FIELD_0C,
crc,
0,
],
);
let header = crc32fast::hash(&e[..EAN_HEADER_CRC_AT]);
words(&mut e, EAN_HEADER_CRC_AT, &[header]);
Ok(e)
}
/// The number of entries in the ean storage `region` (from [`EAN_AT`]), where its header checks:
/// the restore writes one, and the guest's keystore adds its own as it makes its keys.
pub fn ean_entries(region: &[u8]) -> Option<u32> {
let word = |at: usize| Some(u32::from_le_bytes(region.get(at..at + 4)?.try_into().ok()?));
let crc = crc32fast::hash(region.get(..EAN_HEADER_CRC_AT)?);
(word(0)? == 1 && word(4)? == EAN_MAGIC && word(EAN_HEADER_CRC_AT)? == crc).then(|| word(8))?
}
/// The NVRAM entries a guest's EACS boot deletes that the restore's LocalPolicies are bound to:
/// it leaves `system` without them **[measured]**.
pub const POLICY_ENTRIES: [&str; 2] = ["boop-storage-nonces", "boop-storage-misc"];
/// Puts [`POLICY_ENTRIES`] from the newest valid bank of `restored` (the auxiliary storage as
/// the restore wrote it) back into the `system` partition of each valid bank of `aux` (as the
/// guest left it), keeping the guest's other entries, and checksums each bank again. Refuses
/// where `restored` has no valid bank holding them, or `aux` none at all.
pub fn put_back_policy_entries(aux: &mut [u8], restored: &[u8]) -> Result<()> {
ensure!(
aux.len() == SIZE && restored.len() == SIZE,
"an auxiliary storage is {} bytes",
SIZE
);
let newest = (0..2)
.filter_map(|i| {
let b = &restored[NVRAM_AT + i * BANK..NVRAM_AT + (i + 1) * BANK];
Some((
u32::from_le_bytes(b[0x14..0x18].try_into().ok()?),
read_bank(b)?,
))
})
.max_by_key(|(g, _)| *g)
.map(|(_, p)| p);
let wanted: Vec<(String, Vec<u8>)> = newest
.iter()
.flatten()
.filter(|(n, _)| n == "system")
.flat_map(|(_, e)| e.iter().cloned())
.filter(|(k, _)| POLICY_ENTRIES.contains(&k.as_str()))
.collect();
ensure!(
wanted.len() == POLICY_ENTRIES.len(),
"the restore's NVRAM holds no {}",
POLICY_ENTRIES.join(" or ")
);
let mut put = 0;
for i in 0..2 {
let bank = &mut aux[NVRAM_AT + i * BANK..NVRAM_AT + (i + 1) * BANK];
let Some(parts) = read_bank(bank) else {
continue;
};
let mut o = 0x20;
for (name, entries) in parts {
let len = usize::from(u16::from_le_bytes([bank[o + 2], bank[o + 3]])) * 16;
if name == "system" {
let sig = bank[o];
let mut kept: Vec<(String, Vec<u8>)> = entries
.into_iter()
.filter(|(k, _)| !POLICY_ENTRIES.contains(&k.as_str()))
.collect();
kept.extend(wanted.iter().cloned());
let need: usize = 16
+ kept
.iter()
.map(|(k, v)| k.len() + 2 + escape(v).len())
.sum::<usize>();
ensure!(
need <= len,
"NVRAM's system partition has no room for its entries"
);
let at = &mut bank[o..o + len];
at.fill(0);
let refs: Vec<(&str, Vec<u8>)> =
kept.iter().map(|(k, v)| (k.as_str(), v.clone())).collect();
partition(at, sig, "system", &refs);
put += 1;
}
o += len;
}
let sum = adler32(&bank[0x14..]);
bank[0x10..0x14].copy_from_slice(&sum.to_le_bytes());
}
ensure!(
put > 0,
"the VM's NVRAM has no valid bank with a system partition"
);
Ok(())
}
/// Virtualization.framework's header for `aux.img`.
pub fn vz_header() -> Vec<u8> {
let mut h = vec![0u8; HEADER_LEN];
h[..8].copy_from_slice(&MAGIC);
h[8..12].copy_from_slice(&2u32.to_le_bytes());
h[0x10..0x14].copy_from_slice(&1u32.to_le_bytes());
h
}
/// A 16-byte CHRP partition header: signature, checksum, length in 16-byte units
/// (little-endian), name.
fn chrp_header(sig: u8, name: &str, len: usize) -> [u8; 16] {
let mut h = [0u8; 16];
h[0] = sig;
h[2..4].copy_from_slice(&u16::try_from(len / 16).unwrap_or(u16::MAX).to_le_bytes());
h[4..4 + name.len()].copy_from_slice(name.as_bytes());
let mut s = u32::from(h[0]);
for x in &h[2..] {
s += u32::from(*x);
s = (s & 0xff) + (s >> 8);
}
h[1] = s as u8;
h
}
/// Fills `at` (the whole partition) with its header and its `name=value` entries, each
/// NUL-terminated, values escaped.
fn partition(at: &mut [u8], sig: u8, name: &str, entries: &[(&str, Vec<u8>)]) {
let len = at.len();
at[..16].copy_from_slice(&chrp_header(sig, name, len));
let mut o = 16;
for (k, v) in entries {
let mut e = k.as_bytes().to_vec();
e.push(b'=');
e.extend(escape(v));
e.push(0);
at[o..o + e.len()].copy_from_slice(&e);
o += e.len();
}
}
/// A value as NVRAM keeps it: a run of up to 127 zero or 0xFF bytes becomes 0xFF and its count,
/// with the top bit set for 0xFF; every other byte stays.
pub fn escape(v: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(v.len());
let mut i = 0;
while i < v.len() {
let b = v[i];
if b == 0 || b == 0xff {
let mut n = 1;
while i + n < v.len() && v[i + n] == b && n < 0x7f {
n += 1;
}
out.push(0xff);
out.push(n as u8 | if b == 0xff { 0x80 } else { 0 });
i += n;
} else {
out.push(b);
i += 1;
}
}
out
}
/// The inverse of [`escape`].
pub fn unescape(v: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(v.len());
let mut i = 0;
while i < v.len() {
if v[i] == 0xff && i + 1 < v.len() {
let fill = if v[i + 1] & 0x80 != 0 { 0xff } else { 0 };
out.extend(std::iter::repeat_n(fill, usize::from(v[i + 1] & 0x7f)));
i += 2;
} else {
out.push(v[i]);
i += 1;
}
}
out
}
/// Adler-32.
fn adler32(d: &[u8]) -> u32 {
let (mut a, mut b) = (1u32, 0u32);
for chunk in d.chunks(5552) {
for x in chunk {
a += u32::from(*x);
b += a;
}
a %= 65521;
b %= 65521;
}
(b << 16) | a
}
/// A partition read back: its name and its `name=value` entries, values unescaped.
pub type Partition = (String, Vec<(String, Vec<u8>)>);
/// A bank's entries, `partition -> [(name, value)]`, values unescaped: what the tests and
/// `inspect` read back.
pub fn read_bank(bank: &[u8]) -> Option<Vec<Partition>> {
if bank.len() < 0x20
|| adler32(&bank[0x14..]) != u32::from_le_bytes(bank[0x10..0x14].try_into().ok()?)
{
return None;
}
let mut parts = Vec::new();
let mut o = 0x20;
while o + 16 <= bank.len() {
let len = usize::from(u16::from_le_bytes([bank[o + 2], bank[o + 3]])) * 16;
if bank[o] == 0 || len < 16 || o + len > bank.len() {
break;
}
let name = String::from_utf8_lossy(&bank[o + 4..o + 16])
.trim_end_matches('\0')
.to_owned();
let mut entries = Vec::new();
for e in bank[o + 16..o + len]
.split(|b| *b == 0)
.filter(|e| !e.is_empty())
{
let at = e.iter().position(|b| *b == b'=').unwrap_or(e.len());
let v = e.get(at + 1..).unwrap_or_default();
entries.push((String::from_utf8_lossy(&e[..at]).into_owned(), unescape(v)));
}
parts.push((name, entries));
o += len;
}
Some(parts)
}
#[cfg(test)]
mod tests {
use super::*;
fn nvram() -> Nvram {
let mut n = [[0u8; 16]; 7];
for (i, x) in n.iter_mut().enumerate() {
x.fill(i as u8 * 0x11);
}
n[3] = [0xff; 16];
Nvram {
policy_nonces: n,
container: Uuid::from_u128(0x24712d74_0861_48b6_96ce_8cf31423da73),
group: Uuid::from_u128(0xbf304653_4074_415b_8d52_3b779d769491),
}
}
/// An SFR manifest of the tests' own: 5000 bytes, none of them Apple's.
fn ticket() -> Vec<u8> {
(0..5000u32).map(|i| (i * 7 + 3) as u8).collect()
}
fn word(b: &[u8], at: usize) -> u32 {
u32::from_le_bytes(b[at..at + 4].try_into().unwrap())
}
/// The layout a fresh VZ restore leaves **[vz]**, with a manifest of the tests' own: the
/// header, `aptk`'s entry and its slot, each CRC-32 over what the guest checks.
#[test]
fn the_ean_storage_holds_the_sfr_manifest_as_aptk() {
assert_eq!(
crc32fast::hash(b"123456789"),
0xcbf4_3926,
"CRC-32 (ISO-HDLC)"
);
let t = ticket();
let e = ean(&t).unwrap();
assert_eq!(e.len(), 0x3000, "the header page and two pages of slot");
assert_eq!(
(0..5).map(|i| word(&e, 4 * i)).collect::<Vec<_>>(),
[1, 0xeaea_eaea, 1, 0x60_0000, 0x3000]
);
assert!(e[0x14..0x1ec].iter().all(|b| *b == 0));
assert_eq!(&e[0x1ec..0x1f0], b"ktpa", "the tag's letters reversed");
assert_eq!(
(0..5).map(|i| word(&e, 0x1f0 + 4 * i)).collect::<Vec<_>>(),
[0x1000, 0x2000, 1, crc32fast::hash(&e[0x1000..0x3000]), 0]
);
assert!(e[0x204..0xffc].iter().all(|b| *b == 0), "one entry");
assert_eq!(word(&e, 0xffc), crc32fast::hash(&e[..0xffc]));
assert_eq!(&e[0x1000..0x1000 + t.len()], &t[..]);
assert!(e[0x1000 + t.len()..].iter().all(|b| *b == 0));
}
#[test]
fn aptks_slot_takes_whole_pages() {
for (len, slot) in [(1, 0x1000), (0x1000, 0x1000), (0x1001, 0x2000)] {
let e = ean(&vec![0x5a; len]).unwrap();
assert_eq!(e.len(), 0x1000 + slot, "{len}");
assert_eq!(word(&e, 0x10), 0x1000 + slot as u32);
assert_eq!(word(&e, 0x1f4), slot as u32);
}
}
#[test]
fn a_manifest_the_ean_storage_cant_hold_is_refused() {
assert!(ean(&[]).is_err());
assert!(ean(&vec![1; 0x60_0000 - 0x1000]).is_ok());
assert!(ean(&vec![1; 0x60_0000 - 0x1000 + 1]).is_err());
}
/// The guest adds its entries after the restore's, raising the count; a header whose CRC-32
/// fails doesn't count.
#[test]
fn the_ean_storage_counts_its_entries_where_its_header_checks() {
let mut e = ean(&ticket()).unwrap();
assert_eq!(ean_entries(&e), Some(1));
for (k, tag) in [(1usize, *b"xrtC"), (2, *b"xrtP")] {
let at = 0x1ec + 0x18 * k;
e[at..at + 4].copy_from_slice(&u32::from_be_bytes(tag).to_le_bytes());
}
e[8..12].copy_from_slice(&3u32.to_le_bytes());
let crc = crc32fast::hash(&e[..0xffc]);
e[0xffc..0x1000].copy_from_slice(&crc.to_le_bytes());
assert_eq!(ean_entries(&e), Some(3));
e[0x20] ^= 1;
assert_eq!(ean_entries(&e), None);
assert_eq!(ean_entries(&[0u8; 0x1000]), None, "an empty region");
assert_eq!(ean_entries(&[]), None);
}
/// The guest's EACS boot leaves `system` without the policy entries and with entries of its
/// own; putting them back keeps the guest's, in both banks, each checksummed again.
#[test]
fn the_policy_entries_go_back_beside_the_guests() {
let n = nvram();
let restored = trimmed(&n, &ticket()).unwrap();
let mut after = restored.clone();
for i in 0..2 {
let bank = &mut after[NVRAM_AT + i * BANK..NVRAM_AT + (i + 1) * BANK];
let at = &mut bank[SYSTEM_AT..];
at.fill(0);
partition(
at,
0x70,
"system",
&[
("auto-boot", b"true".to_vec()),
("guest-own", vec![0, 0, 7, 0xff]),
],
);
let sum = adler32(&bank[0x14..]);
bank[0x10..0x14].copy_from_slice(&sum.to_le_bytes());
}
let common_before = after[NVRAM_AT + COMMON_AT..NVRAM_AT + SYSTEM_AT].to_vec();
put_back_policy_entries(&mut after, &restored).unwrap();
for i in 0..2 {
let bank = &after[NVRAM_AT + i * BANK..NVRAM_AT + (i + 1) * BANK];
let parts = read_bank(bank).expect("the bank checks again");
let system = &parts.iter().find(|(p, _)| p == "system").unwrap().1;
let names: Vec<&str> = system.iter().map(|(k, _)| k.as_str()).collect();
assert_eq!(
names,
[
"auto-boot",
"guest-own",
"boop-storage-nonces",
"boop-storage-misc"
]
);
assert_eq!(system[1].1, [0, 0, 7, 0xff]);
assert_eq!(system[2].1, n.policy_nonces.concat());
assert_eq!(system[3].1, BOOP_STORAGE_MISC);
}
assert_eq!(
&after[NVRAM_AT + COMMON_AT..NVRAM_AT + SYSTEM_AT],
&common_before[..],
"common stays"
);
assert_eq!(
&after[EAN_AT..],
&restored[EAN_AT..],
"the ean storage stays"
);
// Again changes nothing.
let once = after.clone();
put_back_policy_entries(&mut after, &restored).unwrap();
assert_eq!(after, once);
}
#[test]
fn policy_entries_the_restore_never_wrote_are_refused() {
let mut a = trimmed(&nvram(), &ticket()).unwrap();
let blank = vec![0u8; SIZE];
assert!(put_back_policy_entries(&mut a, &blank).is_err());
let mut blank2 = vec![0u8; SIZE];
let restored = trimmed(&nvram(), &ticket()).unwrap();
assert!(put_back_policy_entries(&mut blank2, &restored).is_err());
}
/// The form a fresh restore writes **[vz]**, with UUIDs of the tests' own.
#[test]
fn boot_volume_names_the_container_as_gpt_stores_it() {
assert_eq!(
nvram().boot_volume(),
"EF57347C-0000-AA11-AA11-00306543ECAC:742D7124-6108-B648-96CE-8CF31423DA73:\
BF304653-4074-415B-8D52-3B779D769491"
);
}
#[test]
fn values_escape_their_zero_and_ff_runs() {
let v = [
1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
assert_eq!(escape(&v), [1, 1, 0xff, 10, 1, 0xff, 11]);
let long = [0xffu8; 200];
assert_eq!(escape(&long), [0xff, 0xff, 0xff, 0x80 | 73]);
for v in [&v[..], &long[..], b"plain", &[]] {
assert_eq!(unescape(&escape(v)), v);
}
assert!(!escape(&nvram().policy_nonces.concat()).contains(&0));
}
#[test]
fn both_banks_read_back_with_the_restores_values() {
let a = trimmed(&nvram(), &ticket()).unwrap();
assert_eq!(a.len(), SIZE);
for (i, generation) in [(0, 2u32), (1, 1)] {
let bank = &a[NVRAM_AT + i * BANK..NVRAM_AT + (i + 1) * BANK];
assert_eq!(&bank[..16], b"\x5a\x82\x02\x00nvram\0\0\0\0\0\0\0");
assert_eq!(
u32::from_le_bytes(bank[0x14..0x18].try_into().unwrap()),
generation
);
let parts = read_bank(bank).expect("the bank checks");
let names: Vec<&str> = parts.iter().map(|(n, _)| n.as_str()).collect();
assert_eq!(names, ["common", "system"]);
let system: Vec<&str> = parts[1].1.iter().map(|(k, _)| k.as_str()).collect();
assert_eq!(
system,
[
"auto-boot",
"boop-storage-nonces",
"boop-storage-misc",
"boot-volume",
"boot-args",
"bootdelay"
]
);
assert_eq!(parts[1].1[1].1, nvram().policy_nonces.concat());
assert_eq!(parts[1].1[2].1, BOOP_STORAGE_MISC);
assert_eq!(
parts[0].1[1],
("restore-outcome".into(), b"initial_engine_success".to_vec())
);
}
// The partitions' headers carry the checksums a fresh restore's do **[vz]**.
assert_eq!(
&a[NVRAM_AT + COMMON_AT..NVRAM_AT + COMMON_AT + 4],
&[0x71, 0x5b, 0xfe, 0x5f]
);
assert_eq!(
&a[NVRAM_AT + SYSTEM_AT..NVRAM_AT + SYSTEM_AT + 4],
&[0x70, 0x38, 0x00, 0x20]
);
// Nothing outside NVRAM and the ean storage's header and `aptk` is written.
assert!(a[..NVRAM_AT].iter().all(|b| *b == 0));
assert!(a[NVRAM_AT + 2 * BANK..EAN_AT].iter().all(|b| *b == 0));
assert_eq!(&a[EAN_AT..EAN_AT + 0x3000], &ean(&ticket()).unwrap()[..]);
assert!(a[EAN_AT + 0x3000..].iter().all(|b| *b == 0));
}
// Ambrosia boots from the valid bank of the highest generation, a bank valid where it opens
// with 0x5a and `nvram` and its Adler-32 at 0x10 covers it from 0x14 (its `nvram.rs`); with
// no valid bank it stops before the kernel. Both banks the restore writes pass that check,
// the first current, and each carries the policy nonces the LocalPolicies are bound to.
#[test]
fn both_banks_pass_the_firmwares_check() {
let n = nvram();
let a = trimmed(&n, &ticket()).unwrap();
let valid = |b: &[u8]| {
b[0] == 0x5a
&& &b[4..9] == b"nvram"
&& adler32(&b[0x14..]) == u32::from_le_bytes(b[0x10..0x14].try_into().unwrap())
};
let banks: Vec<&[u8]> = (0..2)
.map(|i| &a[NVRAM_AT + i * BANK..NVRAM_AT + (i + 1) * BANK])
.collect();
assert!(banks.iter().all(|b| valid(b)));
let current = (0..2)
.max_by_key(|&i| u32::from_le_bytes(banks[i][0x14..0x18].try_into().unwrap()))
.unwrap();
assert_eq!(current, 0);
for b in banks {
let parts = read_bank(b).unwrap();
let nonces = &parts[1]
.1
.iter()
.find(|(k, _)| k == "boop-storage-nonces")
.unwrap()
.1;
assert_eq!(&nonces[..16], n.remote_policy_nonce());
assert_eq!(&nonces[16..32], n.local_policy_nonce());
}
}
#[test]
fn a_damaged_bank_does_not_read() {
let mut a = trimmed(&nvram(), &ticket()).unwrap();
a[NVRAM_AT + 0x100] ^= 1;
assert!(read_bank(&a[NVRAM_AT..NVRAM_AT + BANK]).is_none());
}
#[test]
fn the_vz_header_is_magic_version_and_one() {
let h = vz_header();
assert_eq!(
&h[..0x14],
b"\xa5\xd5\xb3\xfe\x97\xad\x1d\x27\x02\0\0\0\0\0\0\0\x01\0\0\0"
);
assert!(h[0x14..].iter().all(|b| *b == 0));
}
}
+504
View File
@@ -0,0 +1,504 @@
//! Where IPSWs come from: Apple's catalog of macOS IPSWs, and the IPSWs already on disk
//! (docs/design.md, "Downloading IPSWs").
//!
//! Apple's catalog ([`URL`]) is the one Virtualization.framework's
//! `VZMacOSRestoreImage.fetchLatestSupported` reads (measured: on macOS 27.0.1 it answered the
//! catalog's VirtualMac2,1 URL). It lists one release, the current one, for each Mac and for the
//! virtual Mac (VirtualMac2,1), and each release replaces the last. VirtualMac2,1's entry gives
//! the IPSW's version, build and URL but no digest; the physical Macs' entries for the same URL
//! give its SHA-1, which [`parse`] takes from them. Another release is restored from an IPSW the
//! user has: one on disk is known by Apple's file name for it,
//! `UniversalMac_<version>_<build>_Restore.ipsw` ([`on_disk`]).
use std::collections::BTreeMap;
use std::path::PathBuf;
use anyhow::{Context, Result, bail};
use plist::Value;
use crate::http::Client;
/// Apple's catalog of macOS IPSWs.
pub const URL: &str =
"https://mesu.apple.com/assets/macos/com_apple_macOSIPSW/com_apple_macOSIPSW.xml";
/// The virtual Mac's model in Apple's catalog.
pub const DEVICE: &str = "VirtualMac2,1";
/// An IPSW Apple's catalog lists for the virtual Mac.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Entry {
/// macOS's version, such as 27.2.1.
pub version: String,
/// Its build, such as 26B131.
pub build: String,
pub url: String,
/// The IPSW's SHA-1, in lowercase hex, where the catalog gives one.
pub sha1: Option<String>,
}
impl Entry {
/// The IPSW's file name: the URL's last part, Apple's own name for it.
pub fn file_name(&self) -> &str {
self.url.rsplit('/').next().unwrap_or_default()
}
}
/// The virtual Mac's entries in the catalog `xml`.
pub fn parse(xml: &[u8]) -> Result<Vec<Entry>> {
let root = Value::from_reader_xml(xml).context("Apple's IPSW catalog is not a plist")?;
let mut digests = BTreeMap::new();
collect_digests(&root, &mut digests);
let by_version = root
.as_dictionary()
.and_then(|d| d.get("MobileDeviceSoftwareVersionsByVersion"))
.and_then(Value::as_dictionary)
.context("Apple's IPSW catalog has no MobileDeviceSoftwareVersionsByVersion")?;
let mut out = Vec::new();
for v in by_version.values() {
let Some(builds) = v
.as_dictionary()
.and_then(|d| d.get("MobileDeviceSoftwareVersions"))
.and_then(Value::as_dictionary)
.and_then(|d| d.get(DEVICE))
.and_then(Value::as_dictionary)
else {
continue;
};
for b in builds.values() {
let Some(r) = b
.as_dictionary()
.and_then(|d| d.get("Restore"))
.and_then(Value::as_dictionary)
else {
continue;
};
let s = |k: &str| r.get(k).and_then(Value::as_string).map(str::to_owned);
let (Some(version), Some(build), Some(url)) =
(s("ProductVersion"), s("BuildVersion"), s("FirmwareURL"))
else {
continue;
};
let sha1 = s("FirmwareSHA1")
.or_else(|| digests.get(&url).cloned())
.map(|d| d.to_ascii_lowercase());
let e = Entry {
version,
build,
url,
sha1,
};
if !out.contains(&e) {
out.push(e);
}
}
}
sort(&mut out);
Ok(out)
}
/// Every FirmwareURL in `v` with its FirmwareSHA1, by URL.
fn collect_digests(v: &Value, out: &mut BTreeMap<String, String>) {
match v {
Value::Dictionary(d) => {
if let (Some(u), Some(s)) = (
d.get("FirmwareURL").and_then(Value::as_string),
d.get("FirmwareSHA1").and_then(Value::as_string),
) && !s.is_empty()
{
out.insert(u.to_owned(), s.to_owned());
}
d.values().for_each(|v| collect_digests(v, out));
}
Value::Array(a) => a.iter().for_each(|v| collect_digests(v, out)),
_ => {}
}
}
/// Fetches Apple's catalog and the virtual Mac's entries in it.
pub fn fetch(client: &Client, url: &str) -> Result<Vec<Entry>> {
let (_, mut r) = client.get(url, None)?;
if r.status() != 200 {
bail!("Apple's IPSW catalog answered {}", r.status());
}
let body = r
.body_mut()
.with_config()
.limit(16 << 20)
.read_to_vec()
.context("read Apple's IPSW catalog")?;
let entries = parse(&body)?;
if entries.is_empty() {
bail!("Apple's IPSW catalog lists no IPSW for the virtual Mac ({DEVICE})");
}
Ok(entries)
}
// ------------------------------------------------------------------ IPSWs on disk
/// An IPSW on disk, known by Apple's file name for it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OnDisk {
pub version: String,
pub build: String,
pub path: PathBuf,
pub size: u64,
}
/// The version and build in Apple's name for an IPSW, `UniversalMac_<version>_<build>_Restore.ipsw`.
pub fn name_parts(name: &str) -> Option<(String, String)> {
let mid = name
.strip_prefix("UniversalMac_")?
.strip_suffix("_Restore.ipsw")?;
let (version, build) = mid.split_once('_')?;
(is_version(version) && is_build(build)).then(|| (version.to_owned(), build.to_owned()))
}
/// The IPSWs in `dirs`, newest first; a directory that doesn't exist has none.
pub fn on_disk(dirs: &[PathBuf]) -> Vec<OnDisk> {
let mut out: Vec<OnDisk> = Vec::new();
for d in dirs {
let Ok(rd) = std::fs::read_dir(d) else {
continue;
};
for e in rd.flatten() {
let name = e.file_name().to_string_lossy().to_string();
let Some((version, build)) = name_parts(&name) else {
continue;
};
let Ok(m) = e.metadata() else { continue };
if m.is_file() && !out.iter().any(|o| o.build == build) {
out.push(OnDisk {
version,
build,
path: e.path(),
size: m.len(),
});
}
}
}
out.sort_by(|a, b| newer(&b.version, &b.build, &a.version, &a.build));
out
}
// ------------------------------------------------------------------ choosing one
/// What a name of a release ([`pick`]) found.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Found {
/// An IPSW on disk.
OnDisk(OnDisk),
/// One to download.
Download(Entry),
}
/// The IPSW `want` names, from those on disk and those Apple's catalog lists:
/// `latest`, the newest of them all; a build (26B131); or a version: the one of that version
/// (27.2.1), else the newest of those it begins (27.2, 27). One on disk is taken over a download
/// of the same build.
pub fn pick(want: &str, on_disk: &[OnDisk], listed: &[Entry]) -> Result<Found> {
let want = want.trim();
let mut all: Vec<(&str, &str)> = on_disk
.iter()
.map(|o| (o.version.as_str(), o.build.as_str()))
.chain(
listed
.iter()
.map(|e| (e.version.as_str(), e.build.as_str())),
)
.collect();
all.sort_by(|a, b| newer(b.0, b.1, a.0, a.1));
let chosen = if want.eq_ignore_ascii_case("latest") {
all.first().copied()
} else if is_build(&build_case(want)) {
all.iter()
.copied()
.find(|(_, b)| b.eq_ignore_ascii_case(want))
} else if is_version(want) {
all.iter()
.copied()
.find(|(v, _)| *v == want)
.or_else(|| all.iter().copied().find(|(v, _)| begins(v, want)))
} else {
bail!("{want:?} is not a macOS version (27.2.1), a build (26B131) or latest");
};
let Some((_, build)) = chosen else {
bail!("{}", missing(want, on_disk, listed));
};
if let Some(o) = on_disk.iter().find(|o| o.build == build) {
return Ok(Found::OnDisk(o.clone()));
}
let e = listed.iter().find(|e| e.build == build).unwrap();
Ok(Found::Download(e.clone()))
}
/// Says that no IPSW of `want` is known: Apple's catalog lists only the current release, so
/// another is given by its IPSW's path.
fn missing(want: &str, on_disk: &[OnDisk], listed: &[Entry]) -> String {
let names = |v: Vec<String>| v.join(", ");
if want.eq_ignore_ascii_case("latest") {
return "Apple's catalog of IPSWs couldn't be read, and there's no IPSW here: try again \
when it can be reached, or give an IPSW's path"
.to_owned();
}
let mut s = if listed.is_empty() {
format!("there's no macOS {want} IPSW here, and Apple's catalog couldn't be read")
} else {
format!(
"Apple offers only the current macOS, {}, to download",
names(
listed
.iter()
.map(|e| format!("{} ({})", e.version, e.build))
.collect()
)
)
};
if !on_disk.is_empty() {
s.push_str(&format!(
", and the IPSWs here are {}",
names(
on_disk
.iter()
.map(|o| format!("{} ({})", o.version, o.build))
.collect()
)
));
}
s.push_str(&format!(": for macOS {want}, give its IPSW's path"));
s
}
/// A macOS version: numbers and dots, such as 27, 27.2 or 27.2.1.
pub fn is_version(s: &str) -> bool {
!s.is_empty()
&& !s.starts_with('.')
&& !s.ends_with('.')
&& !s.contains("..")
&& s.chars().all(|c| c.is_ascii_digit() || c == '.')
}
/// A macOS build: two digits, an uppercase letter, then digits and perhaps a lowercase letter
/// (26B131, 25D771280a).
pub fn is_build(s: &str) -> bool {
let b = s.as_bytes();
b.len() >= 4
&& b[..2].iter().all(u8::is_ascii_digit)
&& b[2].is_ascii_uppercase()
&& b[3].is_ascii_digit()
&& b[3..]
.iter()
.enumerate()
.all(|(i, c)| c.is_ascii_digit() || (i == b.len() - 4 && c.is_ascii_lowercase()))
}
/// `s` with its third character, a build's train letter, in upper case: 23g93 as 23G93.
fn build_case(s: &str) -> String {
s.char_indices()
.map(|(i, c)| if i == 2 { c.to_ascii_uppercase() } else { c })
.collect()
}
/// Whether version `v` begins with `prefix`'s numbers (27.2.1 begins 27.2 and 27, not 27.20).
fn begins(v: &str, prefix: &str) -> bool {
let (v, p) = (numbers(v), numbers(prefix));
v.len() >= p.len() && v[..p.len()] == p[..]
}
fn numbers(v: &str) -> Vec<u32> {
v.split('.').map(|n| n.parse().unwrap_or(0)).collect()
}
/// Orders (version, build) pairs, newer first, as `Ordering` of the second against the first.
fn newer(av: &str, ab: &str, bv: &str, bb: &str) -> std::cmp::Ordering {
let (a, b) = (numbers(av), numbers(bv));
a.cmp(&b).then_with(|| build_key(ab).cmp(&build_key(bb)))
}
/// A build as something to order: its train (26B), then its number.
fn build_key(b: &str) -> (String, u64) {
let split = b
.find(|c: char| c.is_ascii_uppercase())
.map_or(0, |i| i + 1);
let digits: String = b[split..]
.chars()
.take_while(char::is_ascii_digit)
.collect();
(b[..split].to_owned(), digits.parse().unwrap_or(0))
}
fn sort(entries: &mut [Entry]) {
entries.sort_by(|a, b| newer(&b.version, &b.build, &a.version, &a.build));
}
#[cfg(test)]
mod tests {
use super::*;
/// A catalog shaped as Apple's: a physical Mac's entry with the IPSW's SHA-1, the virtual
/// Mac's without it, and a build for another Mac alone.
const CATALOG: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>MobileDeviceProductTypes</key><dict/>
<key>MobileDeviceSoftwareVersionsByVersion</key><dict><key>1</key><dict>
<key>MobileDeviceSoftwareVersions</key><dict>
<key>Mac99,1</key><dict>
<key>30A100</key><dict><key>Restore</key><dict>
<key>BuildVersion</key><string>30A100</string>
<key>FirmwareSHA1</key><string>ABCDEF0123456789ABCDEF0123456789ABCDEF01</string>
<key>FirmwareURL</key><string>https://updates.cdn-apple.com/x/1111/UniversalMac_31.0_30A100_Restore.ipsw</string>
<key>ProductVersion</key><string>31.0</string>
</dict></dict>
<key>30A7100</key><dict><key>Restore</key><dict>
<key>BuildVersion</key><string>30A7100</string>
<key>FirmwareURL</key><string>https://updates.cdn-apple.com/x/2222/UniversalMac_31.0_30A7100_Restore.ipsw</string>
<key>ProductVersion</key><string>31.0</string>
</dict></dict>
</dict>
<key>VirtualMac2,1</key><dict>
<key>30A100</key><dict><key>Restore</key><dict>
<key>BuildVersion</key><string>30A100</string>
<key>FirmwareURL</key><string>https://updates.cdn-apple.com/x/1111/UniversalMac_31.0_30A100_Restore.ipsw</string>
<key>ProductVersion</key><string>31.0</string>
</dict></dict>
</dict>
</dict></dict></dict></dict></plist>"#;
fn entry(v: &str, b: &str) -> Entry {
Entry {
version: v.into(),
build: b.into(),
url: format!("https://updates.cdn-apple.com/x/UniversalMac_{v}_{b}_Restore.ipsw"),
sha1: None,
}
}
fn disk(v: &str, b: &str) -> OnDisk {
OnDisk {
version: v.into(),
build: b.into(),
path: PathBuf::from(format!("/c/UniversalMac_{v}_{b}_Restore.ipsw")),
size: 1,
}
}
#[test]
fn the_virtual_macs_entry_takes_its_digest_from_the_same_url() {
let e = parse(CATALOG.as_bytes()).unwrap();
assert_eq!(
e,
[Entry {
version: "31.0".into(),
build: "30A100".into(),
url: "https://updates.cdn-apple.com/x/1111/UniversalMac_31.0_30A100_Restore.ipsw"
.into(),
sha1: Some("abcdef0123456789abcdef0123456789abcdef01".into()),
}]
);
assert_eq!(e[0].file_name(), "UniversalMac_31.0_30A100_Restore.ipsw");
}
#[test]
fn the_catalog_is_fetched_with_the_pinned_headers() {
use crate::test_server::Server;
let s = Server::start(|_, _| (200, vec![], CATALOG.as_bytes().to_vec()));
let e = fetch(&Client::local(), &s.url("/c.xml")).unwrap();
assert_eq!(e[0].build, "30A100");
let h = &s.requests()[0].headers;
crate::sent_headers::assert_pinned(h, &["connection"]);
assert_eq!(
URL,
"https://mesu.apple.com/assets/macos/com_apple_macOSIPSW/com_apple_macOSIPSW.xml"
);
crate::http::check_url(URL).unwrap();
}
#[test]
fn ipsws_on_disk_are_known_by_apples_names() {
assert_eq!(
name_parts("UniversalMac_14.6.1_23G93_Restore.ipsw"),
Some(("14.6.1".into(), "23G93".into()))
);
assert_eq!(
name_parts("UniversalMac_14.6.1_23G93_Restore.ipsw.part"),
None
);
assert_eq!(name_parts("macOS-Tahoe-online-installer.dmg"), None);
let dir = std::env::temp_dir().join(format!("reims-restore-disk-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("a")).unwrap();
std::fs::create_dir_all(dir.join("b")).unwrap();
std::fs::write(dir.join("a/UniversalMac_14.6.1_23G93_Restore.ipsw"), b"x").unwrap();
std::fs::write(dir.join("b/UniversalMac_27.2.1_26B131_Restore.ipsw"), b"yy").unwrap();
std::fs::write(dir.join("b/UniversalMac_14.6.1_23G93_Restore.ipsw"), b"x").unwrap();
std::fs::write(
dir.join("b/UniversalMac_27.2.1_26B131_Restore.ipsw.part"),
b"",
)
.unwrap();
let d = on_disk(&[dir.join("a"), dir.join("b"), dir.join("none")]);
let names: Vec<_> = d.iter().map(|o| (o.build.as_str(), o.size)).collect();
assert_eq!(names, [("26B131", 2), ("23G93", 1)]);
assert_eq!(
d[1].path,
dir.join("a/UniversalMac_14.6.1_23G93_Restore.ipsw")
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_release_is_named_by_version_build_or_latest() {
let listed = [entry("27.2.1", "26B131"), entry("27.2", "26B123")];
let have = [disk("14.6.1", "23G93"), disk("27.2", "26B123")];
let dl = |e: &Entry| Found::Download(e.clone());
assert_eq!(pick("latest", &have, &listed).unwrap(), dl(&listed[0]));
assert_eq!(pick("27.2.1", &have, &listed).unwrap(), dl(&listed[0]));
// an exact version first, then the newest it begins; one on disk over a download
assert_eq!(
pick("27.2", &have, &listed).unwrap(),
Found::OnDisk(have[1].clone())
);
assert_eq!(pick("27", &have, &listed).unwrap(), dl(&listed[0]));
assert_eq!(
pick("14", &have, &listed).unwrap(),
Found::OnDisk(have[0].clone())
);
assert_eq!(
pick("23g93", &have, &listed).unwrap(),
Found::OnDisk(have[0].clone())
);
assert_eq!(pick("26B131", &have, &listed).unwrap(), dl(&listed[0]));
let e = pick("15.6.1", &have, &listed[..1]).unwrap_err().to_string();
assert_eq!(
e,
"Apple offers only the current macOS, 27.2.1 (26B131), to download, and the IPSWs \
here are 14.6.1 (23G93), 27.2 (26B123): for macOS 15.6.1, give its IPSW's path"
);
let e = pick("15.6.1", &[], &[]).unwrap_err().to_string();
assert_eq!(
e,
"there's no macOS 15.6.1 IPSW here, and Apple's catalog couldn't be read: for \
macOS 15.6.1, give its IPSW's path"
);
assert!(pick("27.20", &have, &listed).is_err());
assert!(pick("sonoma", &have, &listed).is_err());
assert!(pick("latest", &[], &[]).is_err());
}
#[test]
fn builds_and_versions_parse() {
for b in ["26B131", "23G93", "25D771280a", "20A5303"] {
assert!(is_build(b), "{b}");
}
for b in ["26b131", "2B13", "26B", "26B131aa", "27.2"] {
assert!(!is_build(b), "{b}");
}
assert!(is_version("27") && is_version("27.2.1"));
assert!(!is_version("27.") && !is_version(".2") && !is_version("27..1"));
assert_eq!(
newer("27.2.1", "26B131", "27.2", "26B123"),
std::cmp::Ordering::Greater
);
}
}
+564
View File
@@ -0,0 +1,564 @@
//! Writing the plan's three APFS containers into the disk, each at its partition: every volume
//! formed by reims-apfs's writer, and every file's bytes streamed from where the plan says they
//! come from — bytes the restore made, an IPSW member, an image's plaintext, or a boot object
//! stitched to its ticket (docs/design.md, "Writing the containers").
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};
use std::sync::Arc;
use anyhow::{Context, Result, ensure};
use reims_apfs::write::{self as apfs_write, VolumeDef, copy, fsbuild, sealed, volume};
use uuid::Uuid;
use crate::aea::KeyService;
use crate::gpt::Partition;
use crate::image;
use crate::img4;
use crate::ipsw::Ipsw;
use crate::plan::{self, Content, Data, Node, Role};
/// Where the writer reads what it writes.
pub struct Sources<'a> {
pub ipsw: &'a Ipsw,
pub keys: &'a dyn KeyService,
/// The system volume's root hash, once it is sealed: the boot directories' root hash
/// objects are made from it.
pub root_hash: Option<img4::RootHash>,
/// When every volume records it was formatted and changed, and every entry made, in
/// nanoseconds since 1970.
pub t: u64,
}
/// One file's bytes, ready to stream into its blocks: held, or read front to back, `len` bytes.
enum Bytes {
Held(Arc<[u8]>),
Stream { len: u64, r: Box<dyn Read + Send> },
}
/// A copied stream's bytes, read run by run from the system image (a hole reads as zeros).
struct Runs {
src: image::Source,
block: u64,
runs: Vec<copy::SourceRun>,
at: usize,
within: u64,
}
impl Read for Runs {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
while let Some(r) = self.runs.get(self.at) {
if self.within == r.len {
self.at += 1;
self.within = 0;
continue;
}
let n = (buf.len() as u64).min(r.len - self.within) as usize;
match r.phys {
Some(p) => self
.src
.read_exact_at(p * self.block + self.within, &mut buf[..n])?,
None => buf[..n].fill(0),
}
self.within += n as u64;
return Ok(n);
}
Ok(0)
}
}
/// The Data volume's rule for the template's paths (docs/design.md, "The disk"): each pattern of
/// `Data.symlink-patterns` a glob from the template's root, `*` within one component and `**`
/// any depth; one ending in `/` matches directories, any other everything else, the first
/// match deciding. A match is made a symbolic link back into the template.
pub struct DataRule {
rules: Vec<(bool, Vec<Tok>)>,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Tok {
Lit(u8),
/// Any bytes within one component.
Star,
/// Any bytes at all.
Any,
}
impl DataRule {
/// The rule of the patterns, one per line.
#[must_use]
pub fn new(patterns: &str) -> Self {
let rules = patterns
.lines()
.map(str::trim)
.filter(|p| !p.is_empty())
.map(|p| {
let (dir, p) = p.strip_suffix('/').map_or((false, p), |d| (true, d));
let mut toks = Vec::new();
for (i, part) in p.split('/').enumerate() {
if i > 0 {
toks.push(Tok::Lit(b'/'));
}
if part == "**" {
toks.push(Tok::Any);
continue;
}
for b in part.bytes() {
toks.push(if b == b'*' { Tok::Star } else { Tok::Lit(b) });
}
}
(dir, toks)
})
.collect();
Self { rules }
}
/// What becomes of the template's entry at `path` (from the template's root), a directory or
/// not (a symbolic link is never asked): kept, or a link of `<../ per component of its
/// parent>System/Library/Templates/Data/<path>`, a directory's ending in `/`.
#[must_use]
pub fn decide(&self, path: &str, is_dir: bool) -> copy::Replace {
let hit = self
.rules
.iter()
.any(|(dir, toks)| *dir == is_dir && matches(toks, path.as_bytes()));
if !hit {
return copy::Replace::Keep;
}
let mut target = "../".repeat(path.matches('/').count());
target.push_str("System/Library/Templates/Data/");
target.push_str(path);
if is_dir {
target.push('/');
}
copy::Replace::Link(target.into_bytes())
}
}
/// Whether `toks` match all of `s`.
fn matches(toks: &[Tok], s: &[u8]) -> bool {
match toks.split_first() {
None => s.is_empty(),
Some((Tok::Lit(c), rest)) => s.first() == Some(c) && matches(rest, &s[1..]),
Some((Tok::Star, rest)) => {
let span = s.iter().position(|&b| b == b'/').unwrap_or(s.len());
(0..=span).any(|n| matches(rest, &s[n..]))
}
Some((Tok::Any, rest)) => (0..=s.len()).any(|n| matches(rest, &s[n..])),
}
}
/// Where the data template is in the system image.
const TEMPLATE: &str = "/System/Library/Templates/Data";
/// Its patterns of what the Data volume links to instead of copying.
const PATTERNS: &str = "/System/Library/Templates/Data.symlink-patterns";
/// Where the Data volume keeps the template's receipt, and its flags (`SF_RESTRICTED`).
const RECEIPT: &str = "Library/Apple/System/Library/Receipts/com.apple.files.data-template.plist";
const SF_RESTRICTED: u32 = 0x8_0000;
/// The Data volume: the system image's data template, as [`DataRule`] makes it, with its
/// receipt.
fn data_volume<'a>(
v: &'a plan::Volume,
image_name: &str,
receipt: &Arc<[u8]>,
src: &Sources,
) -> Result<(VolumeDef<'a>, Vec<Bytes>)> {
let (source, c) = image::open_container_source(src.ipsw, image_name, src.keys)?;
let block = u64::from(c.block_size());
let sys = c.system_volume()?;
let root = sys
.lookup(TEMPLATE)
.with_context(|| format!("find {TEMPLATE} in {image_name}"))?;
let rule = DataRule::new(&String::from_utf8_lossy(&sys.read_file(PATTERNS)?));
let records = sys
.fs_tree_records()
.context("read the system image's records")?;
let added = [fsbuild::Item {
path: RECEIPT.into(),
kind: fsbuild::Kind::File {
len: receipt.len() as u64,
},
mode: 0o666,
uid: 0,
gid: 0,
bsd_flags: SF_RESTRICTED,
xattrs: Vec::new(),
}];
let copied = copy::copy_tree(
&records,
root.id,
true,
src.t,
&mut |p, d| rule.decide(p, d),
&added,
)
.context("copy the data template")?;
drop(records);
let bytes = copied
.sources
.iter()
.zip(&copied.streams)
.map(|(s, st)| match s {
copy::StreamSource::Runs(runs) => Bytes::Stream {
len: st.len,
r: Box::new(Runs {
src: source.clone(),
block,
runs: runs.clone(),
at: 0,
within: 0,
}),
},
copy::StreamSource::Added(_) => Bytes::Held(receipt.clone()),
})
.collect();
let def = VolumeDef {
name: v.name,
uuid: *v.uuid.as_bytes(),
role: v.role.apfs(),
system: false,
group: v.group.map_or([0; 16], |g| *g.as_bytes()),
records: copied.records,
streams: copied.streams,
counts: copied.counts,
next_obj_id: copied.next_obj_id,
seal: None,
};
Ok((def, bytes))
}
/// The system volume: the OS image's volume sealed with reims-apfs's own tree at the time its
/// canonical metadata `mtree` records (docs/design.md, "The system volume's seal"). Sets
/// `src.root_hash`, whose first hash is the seal's and the other two the IPSW's `root_hash`'s.
fn system_volume<'a>(
v: &'a plan::Volume,
image_name: &str,
mtree: &str,
root_hash: &str,
src: &mut Sources,
) -> Result<(VolumeDef<'a>, Vec<Bytes>)> {
let t = crate::mtree::root_time(&src.ipsw.read(mtree)?)
.with_context(|| format!("read the seal's time from {mtree}"))?;
let apple = img4::parse_im4p(&src.ipsw.read(root_hash)?)
.and_then(|p| img4::RootHash::parse(&p.payload))
.with_context(|| format!("read {root_hash}"))?;
let (source, c) = image::open_container_source(src.ipsw, image_name, src.keys)?;
let block = u64::from(c.block_size());
ensure!(
block == apfs_write::geometry::BLOCK_SIZE,
"{image_name}'s blocks are {block} bytes"
);
let sys = c.system_volume()?;
let set = reims_apfs::canon::sealed_set(&sys, t)
.with_context(|| format!("read {image_name}'s system volume"))?;
let tree = reims_apfs::seal::build(&set.records, 0);
let reims_apfs::canon::SealedSet {
records,
streams,
counts,
next_obj_id,
next_doc_id,
..
} = set;
drop(records);
let hash = img4::RootHash {
hashes: [tree.root_hash, apple.hashes[1], apple.hashes[2]],
};
let seal = sealed::Seal {
tree,
streams: streams
.iter()
.map(|s| volume::Stream {
id: s.id,
owner: s.owner,
len: s.blocks * block,
})
.collect(),
snapshot: hash.snapshot_name(),
snapshot_uuid: *Uuid::new_v4().as_bytes(),
inum: next_obj_id,
next_doc_id,
};
src.root_hash = Some(hash);
// Each stream's bytes, and zeros to the end of its blocks: a sealed file's last segment is
// hashed zero-padded to whole blocks.
let bytes = streams
.into_iter()
.map(|s| {
let len = s.blocks * block;
ensure!(
s.size <= len,
"stream {} holds {} bytes in {len}",
s.id,
s.size
);
let mut runs = s.runs;
if len > s.size {
runs.push(copy::SourceRun {
len: len - s.size,
phys: None,
});
}
Ok(Bytes::Stream {
len,
r: Box::new(Runs {
src: source.clone(),
block,
runs,
at: 0,
within: 0,
}),
})
})
.collect::<Result<Vec<_>>>()?;
let group = v.group.map_or([0; 16], |g| *g.as_bytes());
let def = VolumeDef::sealed(v.name, *v.uuid.as_bytes(), group, counts, seal);
Ok((def, bytes))
}
/// A file's length and where its bytes come from.
fn open_data(data: &Data, src: &Sources) -> Result<(u64, Bytes)> {
Ok(match data {
Data::Bytes(b) => (b.len() as u64, Bytes::Held(b.clone())),
Data::Member(m) => {
let len = src.ipsw.member(m)?.size;
(
len,
Bytes::Stream {
len,
r: src.ipsw.reader(m)?,
},
)
}
Data::Plain(m) => {
let (len, r) = image::plain_stream(src.ipsw, m, src.keys)?;
(len, Bytes::Stream { len, r })
}
Data::Stitched {
component,
member,
manifest,
} => {
let out = img4::personalize(component, &src.ipsw.read(member)?, manifest)
.with_context(|| format!("stitch {component} from {member}"))?;
(out.len() as u64, Bytes::Held(out.into()))
}
Data::SealedRootHash { manifest } => {
let seal = src
.root_hash
.as_ref()
.context("a boot directory's root hash before the system volume is sealed")?;
let out = img4::stitch_img4(&seal.system_im4p(), manifest);
(out.len() as u64, Bytes::Held(out.into()))
}
})
}
/// A volume of the plan's entries: the writer's description of it, and the bytes of each of its
/// data streams, in the order of the streams.
fn entries_volume<'a>(
v: &'a plan::Volume,
entries: &[plan::Entry],
src: &Sources,
) -> Result<(VolumeDef<'a>, Vec<Bytes>)> {
let mut items = Vec::with_capacity(entries.len());
let mut bytes: Vec<Option<Bytes>> = Vec::with_capacity(entries.len());
for e in entries {
let (kind, b) = match &e.node {
Node::Dir => (fsbuild::Kind::Dir, None),
Node::File(d) => {
let (len, b) =
open_data(d, src).with_context(|| format!("{}/{}", v.name, e.path))?;
(fsbuild::Kind::File { len }, Some(b))
}
Node::Symlink(t) => (fsbuild::Kind::Symlink(t.as_bytes().to_vec()), None),
Node::Clone(of) => (fsbuild::Kind::Clone(of.clone()), None),
};
items.push(fsbuild::Item {
path: e.path.clone(),
kind,
mode: e.mode,
uid: e.uid,
gid: e.gid,
bsd_flags: 0,
xattrs: Vec::new(),
});
bytes.push(b);
}
let built =
fsbuild::build(&items, true, src.t).with_context(|| format!("lay out {}", v.name))?;
let streams = built
.stream_items
.iter()
.map(|&i| {
bytes[i]
.take()
.context("a stream for an entry without bytes")
})
.collect::<Result<Vec<_>>>()?;
let mut def = VolumeDef::of(v.name, *v.uuid.as_bytes(), v.role.apfs(), built);
def.system = v.role == Role::System;
def.group = v.group.map_or([0; 16], |g| *g.as_bytes());
Ok((def, streams))
}
/// Copy exactly `len` bytes from `r` to `w`.
fn copy_exact(r: &mut dyn Read, w: &mut File, len: u64) -> Result<()> {
let mut buf = vec![0u8; 1 << 20];
let mut left = len;
while left > 0 {
let n = (buf.len() as u64).min(left) as usize;
r.read_exact(&mut buf[..n])?;
w.write_all(&buf[..n])?;
left -= n as u64;
}
// Nothing past the length the stream gave.
let mut probe = [0u8; 1];
ensure!(
matches!(r.read(&mut probe), Ok(0)),
"a stream runs past the {len} bytes it gave"
);
Ok(())
}
/// Write the container of `volumes` at `part` of `disk`. Sealing a system volume sets
/// `src.root_hash`, which the volumes after it that hold boot directories need.
///
/// # Errors
///
/// An entry the writer cannot lay out, a source that cannot be read, volumes that do not fit
/// the partition, or a write that fails.
pub fn write_container(
disk: &mut File,
part: &Partition,
volumes: &[plan::Volume],
src: &mut Sources,
) -> Result<()> {
let block = apfs_write::geometry::BLOCK_SIZE;
let block_count = part.len() / block;
let mut defs = Vec::with_capacity(volumes.len());
let mut all_bytes = Vec::with_capacity(volumes.len());
for v in volumes {
match &v.content {
Content::Entries(entries) => {
let (def, bytes) = entries_volume(v, entries, src)?;
defs.push(def);
all_bytes.push(bytes);
}
Content::DataTemplate { image, receipt } => {
let (def, bytes) = data_volume(v, image, receipt, src)
.with_context(|| format!("lay out {}", v.name))?;
defs.push(def);
all_bytes.push(bytes);
}
Content::SealedSystem {
image,
mtree,
root_hash,
} => {
let (def, bytes) = system_volume(v, image, mtree, root_hash, src)
.with_context(|| format!("seal {}", v.name))?;
defs.push(def);
all_bytes.push(bytes);
}
}
}
let formed = apfs_write::container(block_count, *Uuid::new_v4().as_bytes(), src.t, defs)
.context("lay out the container")?;
let base = part.offset();
for (addr, b) in &formed.blocks {
disk.seek(SeekFrom::Start(base + addr * block))?;
disk.write_all(b)?;
}
for ((v, firsts), bytes) in volumes.iter().zip(&formed.stream_blocks).zip(all_bytes) {
for (first, b) in firsts.iter().zip(bytes) {
disk.seek(SeekFrom::Start(base + first * block))?;
match b {
Bytes::Held(h) => disk.write_all(&h)?,
// A stream that gives other than the length the writer laid out fails here.
Bytes::Stream { len, mut r } => copy_exact(&mut r, disk, len)
.with_context(|| format!("write {}'s files", v.name))?,
}
}
}
disk.flush()?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn link(r: copy::Replace) -> Option<String> {
match r {
copy::Replace::Keep => None,
copy::Replace::Link(t) => Some(String::from_utf8(t).unwrap()),
}
}
// Patterns of the forms the data templates hold, written here: a directory pattern with `*`
// in a component, a file pattern with `*` inside a component, and `**` at the end.
const PATTERNS: &str = "\
Library/Things/*.bundle/Contents/
System/Assets/*/kind_A/*.asset/Data/
System/Core.bundle/Contents/Icons*.bundle/Res/*.icns
Library/Pictures/**
";
#[test]
fn a_directory_pattern_links_directories_only() {
let r = DataRule::new(PATTERNS);
assert_eq!(
link(r.decide("Library/Things/x.bundle/Contents", true)).as_deref(),
Some("../../../System/Library/Templates/Data/Library/Things/x.bundle/Contents/")
);
assert_eq!(
link(r.decide("Library/Things/x.bundle/Contents", false)),
None
);
assert_eq!(link(r.decide("Library/Things/x.bundle/Other", true)), None);
// `*` stays within one component.
assert_eq!(
link(r.decide("Library/Things/a/b.bundle/Contents", true)),
None
);
assert_eq!(
link(r.decide("System/Assets/v1/kind_A/q.asset/Data", true)).as_deref(),
Some(
"../../../../../System/Library/Templates/Data/System/Assets/v1/kind_A/q.asset/Data/"
)
);
}
#[test]
fn a_file_pattern_links_files_and_keeps_directories() {
let r = DataRule::new(PATTERNS);
assert_eq!(
link(r.decide(
"System/Core.bundle/Contents/IconsX.bundle/Res/a.icns",
false
))
.as_deref(),
Some(
"../../../../../System/Library/Templates/Data/System/Core.bundle/Contents/IconsX.bundle/Res/a.icns"
)
);
assert!(
link(r.decide("System/Core.bundle/Contents/Icons.bundle/Res/a.icns", false)).is_some()
);
assert_eq!(
link(r.decide("System/Core.bundle/Contents/Icons.bundle/Res/a.png", false)),
None
);
// `**` links every file below, at any depth, and keeps the directories.
assert_eq!(
link(r.decide("Library/Pictures/Animals/Cat.heic", false)).as_deref(),
Some("../../../System/Library/Templates/Data/Library/Pictures/Animals/Cat.heic")
);
assert_eq!(link(r.decide("Library/Pictures/Animals", true)), None);
assert_eq!(link(r.decide("Library/Pictures", true)), None);
assert_eq!(link(r.decide("Library/Other/Cat.heic", false)), None);
}
}
+724
View File
@@ -0,0 +1,724 @@
//! Downloading the IPSW Apple's catalog lists (catalog.rs) into a cache directory: from Apple's
//! CDN through the crate's one client (http.rs), into `<name>.part`, which a later download
//! continues by a ranged request, then checked against the SHA-1 Apple's catalog gives and
//! renamed to Apple's own name for the file, so the file is never at that name before it is
//! whole and checked. An IPSW already there is taken as it is: it was checked when it was
//! renamed into place.
//!
//! A download only ever appends to its `.part`: one it can't continue (longer than the file, or
//! where the CDN answers the whole file rather than the rest) is unlinked and a new one made, so
//! no file is truncated or rewritten in place, and another name for the same file (a hard link)
//! keeps what it holds. It learns the file's length first: a `.part` as long as the file is
//! only checked, never fetched over.
//!
//! One download of a file runs at a time: each holds a lock file beside it ([`lock_path`]), and
//! looks for the finished file again once it holds the lock, which the download that finished it
//! removes after the rename.
//!
//! A download reports its step and its progress, stops when its cancel flag is set (keeping
//! what it has, which the next continues), and before it fetches checks that the file system has
//! the space the rest of the file takes: the length Apple's CDN answers, less what is there. One
//! download of a file runs at a time: each holds a lock on its `.<name>.lock` ([`lock_path`]).
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use anyhow::{Context, Result, bail, ensure};
use sha1::{Digest as _, Sha1};
use crate::catalog::{self, Entry};
use crate::http::{Client, content_range};
use crate::pipeline::Event;
/// Tries of a request that fails or a body that stops, in a row, before the download gives up.
const TRIES: u32 = 5;
/// Room left beyond the file, on top of its length.
const MARGIN: u64 = 64 << 20;
/// Downloads `e`'s IPSW into `dir`, or finds it there; its path.
pub fn download(
client: &Client,
e: &Entry,
dir: &Path,
events: &mut dyn FnMut(Event),
cancel: &AtomicBool,
) -> Result<PathBuf> {
download_with(client, e, dir, events, cancel, &free_space)
}
/// [`download`], with the space free where `dir` is from `free`.
fn download_with(
client: &Client,
e: &Entry,
dir: &Path,
events: &mut dyn FnMut(Event),
cancel: &AtomicBool,
free: &dyn Fn(&Path) -> Result<u64>,
) -> Result<PathBuf> {
let name = e.file_name();
// Apple's name, which is also a safe one: no directory in it
ensure!(
catalog::name_parts(name).is_some(),
"Apple's catalog names the IPSW {name:?}, not UniversalMac_<version>_<build>_Restore.ipsw"
);
std::fs::create_dir_all(dir).with_context(|| format!("make {}", dir.display()))?;
let done = dir.join(name);
if done.is_file() {
return Ok(done);
}
let _lock = lock(dir, name)?;
// Finished by the download that held the lock before.
if done.is_file() {
return Ok(done);
}
let part_path = dir.join(format!("{name}.part"));
let what = format!("Downloading macOS {} ({})", e.version, e.build);
events(Event::Step(what.clone()));
let total = length(client, &e.url)?;
let mut part = match std::fs::metadata(&part_path) {
Ok(m) if m.len() <= total => OpenOptions::new()
.append(true)
.open(&part_path)
.with_context(|| format!("open {}", part_path.display()))?,
Ok(_) => {
// longer than the file: start over
std::fs::remove_file(&part_path)
.with_context(|| format!("remove {}", part_path.display()))?;
new_part(&part_path)?
}
Err(_) => new_part(&part_path)?,
};
let mut have = part.metadata()?.len();
let mut hash = Sha1::new();
if have > 0 {
hash_prefix(&part_path, have, &mut hash, cancel)?;
}
let need = total - have + MARGIN;
let free = free(dir)?;
if free < need {
bail!(
"downloading {name} needs {} free in {}, and there are {}",
gib(need),
dir.display(),
gib(free)
);
}
let mut buf = vec![0u8; 1 << 20];
let mut tries = 0;
while have < total {
ensure!(!cancel.load(Ordering::SeqCst), "the download was stopped");
let answer = client.get(&e.url, Some(&format!("bytes={have}-")));
let mut r = match answer {
Ok((_, r)) if r.status().is_server_error() => {
retry(
&mut tries,
anyhow::anyhow!("Apple's CDN answered {}", r.status()),
)?;
continue;
}
Ok((_, r)) => r,
Err(err) if is_network(&err) => {
retry(&mut tries, err)?;
continue;
}
Err(err) => return Err(err),
};
match r.status().as_u16() {
206 => {
let cr = header(&r, "content-range").and_then(content_range);
if cr != Some((have, total - 1, total)) {
// another range, or the file changed: start over
part = start_over(&part_path, &mut have, &mut hash)?;
continue;
}
}
200 => {
// the whole file, not the rest: start over, from this answer
let len: Option<u64> = header(&r, "content-length").and_then(|v| v.parse().ok());
ensure!(
len == Some(total),
"Apple's CDN answered the IPSW as {len:?} bytes, then as {total}"
);
if have > 0 {
part = start_over(&part_path, &mut have, &mut hash)?;
}
}
s => bail!("Apple's CDN answered {s} for {}", e.url),
}
// ureq ends a body read at its limit with an error, not its end (ureq 3.5.1): the file
// is whole when `have` reaches `total`, whichever the read answered.
let mut body = r.body_mut().with_config().limit(total - have).reader();
let read = loop {
if cancel.load(Ordering::SeqCst) {
part.flush()?;
bail!("the download was stopped");
}
let n = match body.read(&mut buf) {
Ok(0) => break Ok(()),
Ok(n) => n,
Err(err) => break Err(err),
};
part.write_all(&buf[..n])
.with_context(|| format!("write {}", part_path.display()))?;
hash.update(&buf[..n]);
have += n as u64;
tries = 0;
events(Event::Progress {
what: what.clone(),
done: have,
total,
});
};
if have == total {
break;
}
// the body stopped short: continue from where it stopped
let err = match read {
Err(err) => anyhow::Error::from(err),
Ok(()) => anyhow::anyhow!("Apple's CDN ended the IPSW at {have} of {total} bytes"),
};
retry(&mut tries, err)?;
}
part.sync_all()?;
drop(part);
let got: String = hash.finalize().iter().map(|b| format!("{b:02x}")).collect();
match &e.sha1 {
Some(want) if *want != got => {
let _ = std::fs::remove_file(&part_path);
bail!(
"the downloaded {name} isn't the file Apple's catalog lists: its SHA-1 is {got}, \
and Apple's is {want}. It was removed: download it again"
);
}
Some(_) => {}
None => events(Event::Note(format!(
"Apple's catalog gives no SHA-1 for {name}: it is kept unchecked"
))),
}
std::fs::rename(&part_path, &done)
.with_context(|| format!("rename {} to {name}", part_path.display()))?;
// Held still, so a download that takes the lock after this finds the file.
let _ = std::fs::remove_file(lock_path(dir, name));
Ok(done)
}
/// The length of the file at `url`, from a request for its first byte.
fn length(client: &Client, url: &str) -> Result<u64> {
let mut tries = 0;
loop {
let (_, r) = match client.get(url, Some("bytes=0-0")) {
Ok(a) => a,
Err(err) if is_network(&err) => {
retry(&mut tries, err)?;
continue;
}
Err(err) => return Err(err),
};
let total = match r.status().as_u16() {
206 => header(&r, "content-range")
.and_then(content_range)
.map(|c| c.2),
200 => header(&r, "content-length").and_then(|v| v.parse().ok()),
s if s >= 500 => {
retry(&mut tries, anyhow::anyhow!("Apple's CDN answered {s}"))?;
continue;
}
s => bail!("Apple's CDN answered {s} for {url}"),
};
return total.context("Apple's CDN answered the IPSW without its length");
}
}
/// A new, empty `.part`, made where none is.
fn new_part(path: &Path) -> Result<File> {
OpenOptions::new()
.create_new(true)
.append(true)
.open(path)
.with_context(|| format!("make {}", path.display()))
}
/// Unlinks the `.part` at `path` and makes a new one in its place, to download the file from
/// its start: the old file is never truncated, so another name for it keeps what it holds.
fn start_over(path: &Path, have: &mut u64, hash: &mut Sha1) -> Result<File> {
std::fs::remove_file(path).with_context(|| format!("remove {}", path.display()))?;
*have = 0;
*hash = Sha1::new();
new_part(path)
}
/// What downloading `e`'s IPSW into `dir` still takes: the file's length on Apple's CDN, and how
/// much of it `dir` holds (all of it where the file is there).
pub fn remaining(client: &Client, e: &Entry, dir: &Path) -> Result<(u64, u64)> {
let name = e.file_name();
if let Ok(m) = std::fs::metadata(dir.join(name)) {
return Ok((m.len(), m.len()));
}
let have = std::fs::metadata(dir.join(format!("{name}.part"))).map_or(0, |m| m.len());
let total = length(client, &e.url)?;
// a part longer than the file is started over
Ok((total, if have > total { 0 } else { have }))
}
/// The lock file a download of `name` holds in its directory: hidden, so a listing of the
/// directory's files leaves it out.
pub fn lock_path(dir: &Path, name: &str) -> PathBuf {
dir.join(format!(".{name}.lock"))
}
/// Takes the lock of a download of `name` into `dir`, held until the file returned closes, or
/// says another download has it.
fn lock(dir: &Path, name: &str) -> Result<File> {
use std::os::fd::AsRawFd as _;
let path = lock_path(dir, name);
let f = OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(&path)
.with_context(|| format!("open {}", path.display()))?;
// SAFETY: flock on an open descriptor; the lock goes when the file is closed.
if unsafe { libc::flock(f.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 {
bail!("another download of {name} is running");
}
Ok(f)
}
/// Hashes the first `have` bytes of the file at `path` into `hash`, opening it to read alone.
fn hash_prefix(path: &Path, have: u64, hash: &mut Sha1, cancel: &AtomicBool) -> Result<()> {
let f = File::open(path).with_context(|| format!("open {}", path.display()))?;
let mut r = f.take(have);
let mut buf = vec![0u8; 1 << 20];
loop {
ensure!(!cancel.load(Ordering::SeqCst), "the download was stopped");
let n = r.read(&mut buf)?;
if n == 0 {
return Ok(());
}
hash.update(&buf[..n]);
}
}
/// Counts a failed try, waiting before the next, or ends the download with `err` after the last.
fn retry(tries: &mut u32, err: anyhow::Error) -> Result<()> {
*tries += 1;
if *tries >= TRIES {
return Err(err.context(format!("the download failed {TRIES} times in a row")));
}
std::thread::sleep(Duration::from_millis(250 << *tries));
Ok(())
}
/// Whether `err` is the network's, which another try may not meet, rather than a refusal.
fn is_network(err: &anyhow::Error) -> bool {
err.chain()
.any(|c| c.downcast_ref::<ureq::Error>().is_some())
}
fn header<'a>(r: &'a ureq::http::Response<ureq::Body>, name: &str) -> Option<&'a str> {
r.headers().get(name).and_then(|v| v.to_str().ok())
}
/// The space free to this user on the file system `dir` is on.
pub fn free_space(dir: &Path) -> Result<u64> {
let c = std::ffi::CString::new(dir.as_os_str().as_encoded_bytes())?;
// SAFETY: statvfs fills the struct it is given, from a NUL-terminated path.
let mut s: libc::statvfs = unsafe { std::mem::zeroed() };
if unsafe { libc::statvfs(c.as_ptr(), &mut s) } != 0 {
return Err(std::io::Error::last_os_error())
.with_context(|| format!("statvfs {}", dir.display()));
}
#[allow(clippy::useless_conversion)]
Ok(u64::from(s.f_bavail) * u64::from(s.f_frsize))
}
fn gib(bytes: u64) -> String {
format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_server::{Reply, Server};
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
const NAME: &str = "UniversalMac_31.0_30A100_Restore.ipsw";
fn data() -> Vec<u8> {
(0..3_000_000u32)
.map(|i| (i.wrapping_mul(2654435761) >> 24) as u8)
.collect()
}
fn sha1_hex(b: &[u8]) -> String {
Sha1::digest(b).iter().map(|b| format!("{b:02x}")).collect()
}
fn temp_dir(tag: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("reims-restore-dl-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
d
}
/// A CDN serving `data` at /NAME by ranges, or whole where `ignore_range`; its first answer
/// to a request for more than the first byte (the length's) is cut off after `cut` bytes.
fn cdn(data: Vec<u8>, cut: Option<usize>, ignore_range: bool) -> Server {
let answers = AtomicUsize::new(0);
Server::start(move |path, req| {
if path != format!("/x/{NAME}") {
return Reply::from((404, vec![], vec![]));
}
let len = data.len();
let range = req.header("range").and_then(|r| r.strip_prefix("bytes="));
if range == Some("0-0") && !ignore_range {
return Reply::from((
206,
vec![("Content-Range".into(), format!("bytes 0-0/{len}"))],
data[..1].to_vec(),
));
}
let a: usize = range
.and_then(|r| r.strip_suffix('-'))
.map_or(0, |a| a.parse().unwrap());
let first = range != Some("0-0") && answers.fetch_add(1, Ordering::SeqCst) == 0;
let mut r = if ignore_range || range.is_none() {
Reply::from((200, vec![], data.clone()))
} else if a >= len {
Reply::from((
416,
vec![("Content-Range".into(), format!("bytes */{len}"))],
vec![],
))
} else {
Reply::from((
206,
vec![(
"Content-Range".into(),
format!("bytes {a}-{}/{len}", len - 1),
)],
data[a..].to_vec(),
))
};
if first {
r.cut = cut;
}
r
})
}
fn entry(s: &Server, sha1: Option<String>) -> Entry {
Entry {
version: "31.0".into(),
build: "30A100".into(),
url: s.url(&format!("/x/{NAME}")),
sha1,
}
}
fn plenty(_: &Path) -> Result<u64> {
Ok(u64::MAX / 2)
}
fn run(e: &Entry, dir: &Path, cancel: &AtomicBool) -> (Result<PathBuf>, Vec<Event>) {
let mut seen = Vec::new();
let r = download_with(
&Client::local(),
e,
dir,
&mut |ev| seen.push(ev),
cancel,
&plenty,
);
(r, seen)
}
/// A body that stops part way is continued by a ranged request from where it stopped, and
/// the file, checked, takes Apple's name.
#[test]
fn a_download_continues_where_its_answer_stopped() {
let d = data();
let s = cdn(d.clone(), Some(1_000_000), false);
let dir = temp_dir("resume");
let (r, ev) = run(
&entry(&s, Some(sha1_hex(&d))),
&dir,
&AtomicBool::new(false),
);
assert_eq!(r.unwrap(), dir.join(NAME));
assert_eq!(std::fs::read(dir.join(NAME)).unwrap(), d);
assert!(!dir.join(format!("{NAME}.part")).exists());
// and its lock file is gone with it
assert!(!lock_path(&dir, NAME).exists());
let ranges: Vec<_> = s
.requests()
.iter()
.map(|q| q.header("range").unwrap().to_owned())
.collect();
assert_eq!(ranges, ["bytes=0-0", "bytes=0-", "bytes=1000000-"]);
assert_eq!(ev[0], Event::Step("Downloading macOS 31.0 (30A100)".into()));
assert!(ev.contains(&Event::Progress {
what: "Downloading macOS 31.0 (30A100)".into(),
done: 3_000_000,
total: 3_000_000
}));
// a second download finds it, and asks for nothing
let (r, _) = run(
&entry(&s, Some(sha1_hex(&d))),
&dir,
&AtomicBool::new(false),
);
assert_eq!(r.unwrap(), dir.join(NAME));
assert_eq!(s.requests().len(), 3);
let _ = std::fs::remove_dir_all(&dir);
}
/// A `.part` left by an earlier run is continued; where the CDN answers the whole file
/// instead of the range, it starts over; a `.part` as long as the file is only checked,
/// with nothing fetched past the file's length.
#[test]
fn a_partial_file_is_continued_or_started_over() {
let d = data();
for (ignore_range, have, ranges) in [
(false, 1_234_567, &["bytes=0-0", "bytes=1234567-"][..]),
(true, 1_234_567, &["bytes=0-0", "bytes=1234567-"][..]),
(false, 3_000_000, &["bytes=0-0"][..]),
] {
let s = cdn(d.clone(), None, ignore_range);
let dir = temp_dir("partial");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join(format!("{NAME}.part")), &d[..have]).unwrap();
let (r, _) = run(
&entry(&s, Some(sha1_hex(&d))),
&dir,
&AtomicBool::new(false),
);
assert_eq!(r.unwrap(), dir.join(NAME), "{ignore_range} {have}");
assert_eq!(std::fs::read(dir.join(NAME)).unwrap(), d);
let asked: Vec<_> = s
.requests()
.iter()
.map(|q| q.header("range").unwrap().to_owned())
.collect();
assert_eq!(asked, ranges);
let _ = std::fs::remove_dir_all(&dir);
}
}
/// A `.part` that is another name for a file (a hard link) keeps that file as it was when
/// the download starts over: the part is unlinked and made anew, never truncated or
/// rewritten in place. So does a `.part` longer than the file.
#[test]
fn starting_over_leaves_another_name_for_the_part_as_it_was() {
let d = data();
for (ignore_range, kept) in [(true, vec![9u8; 1000]), (false, vec![9u8; 3_000_001])] {
let s = cdn(d.clone(), None, ignore_range);
let dir = temp_dir("links");
std::fs::create_dir_all(&dir).unwrap();
let other = dir.join("other.bin");
std::fs::write(&other, &kept).unwrap();
std::fs::hard_link(&other, dir.join(format!("{NAME}.part"))).unwrap();
let (r, _) = run(
&entry(&s, Some(sha1_hex(&d))),
&dir,
&AtomicBool::new(false),
);
assert_eq!(r.unwrap(), dir.join(NAME), "{ignore_range}");
assert_eq!(std::fs::read(dir.join(NAME)).unwrap(), d);
assert_eq!(std::fs::read(&other).unwrap(), kept, "{ignore_range}");
let _ = std::fs::remove_dir_all(&dir);
}
}
/// A file whose SHA-1 isn't Apple's is removed, and the error says so.
#[test]
fn a_download_that_isnt_apples_file_is_removed() {
let d = data();
let s = cdn(d, None, false);
let dir = temp_dir("digest");
let wrong = "0".repeat(40);
let (r, _) = run(
&entry(&s, Some(wrong.clone())),
&dir,
&AtomicBool::new(false),
);
let e = r.unwrap_err().to_string();
assert!(
e.contains(&format!("and Apple's is {wrong}. It was removed")),
"{e}"
);
assert!(!dir.join(NAME).exists());
assert!(!dir.join(format!("{NAME}.part")).exists());
let _ = std::fs::remove_dir_all(&dir);
}
/// A redirect off the allowed hosts is refused before anything is fetched there.
#[test]
fn a_redirect_off_apples_hosts_is_refused() {
let s = Server::start(|_, _| {
(
302,
vec![("Location".into(), format!("https://example.com/{NAME}"))],
vec![],
)
});
let dir = temp_dir("redirect");
let (r, _) = run(&entry(&s, None), &dir, &AtomicBool::new(false));
let e = format!("{:#}", r.unwrap_err());
assert!(
e.contains(&format!("https://example.com/{NAME} is not local")),
"{e}"
);
assert_eq!(s.requests().len(), 1);
assert!(!dir.join(NAME).exists());
let _ = std::fs::remove_dir_all(&dir);
}
/// A stopped download keeps what it has, and the next continues it.
#[test]
fn a_stopped_download_keeps_its_part_for_the_next() {
let d = data();
let s = cdn(d.clone(), None, false);
let dir = temp_dir("cancel");
let cancel = Arc::new(AtomicBool::new(false));
let mut events = 0;
let stop = cancel.clone();
let r = download_with(
&Client::local(),
&entry(&s, Some(sha1_hex(&d))),
&dir,
&mut |e| {
if matches!(e, Event::Progress { .. }) {
events += 1;
stop.store(true, Ordering::SeqCst);
}
},
&cancel,
&plenty,
);
assert_eq!(r.unwrap_err().to_string(), "the download was stopped");
assert_eq!(events, 1);
let kept = std::fs::metadata(dir.join(format!("{NAME}.part")))
.unwrap()
.len();
assert!(kept > 0 && kept < d.len() as u64, "{kept}");
assert!(!dir.join(NAME).exists());
let (r, _) = run(
&entry(&s, Some(sha1_hex(&d))),
&dir,
&AtomicBool::new(false),
);
assert_eq!(r.unwrap(), dir.join(NAME));
assert_eq!(std::fs::read(dir.join(NAME)).unwrap(), d);
assert_eq!(
s.requests().last().unwrap().header("range").unwrap(),
format!("bytes={kept}-")
);
let _ = std::fs::remove_dir_all(&dir);
}
/// The space the rest of the file takes is checked against what is free, from the length
/// the CDN answers.
#[test]
fn a_download_checks_the_space_the_rest_of_the_file_takes() {
let d = data();
let s = cdn(d.clone(), None, false);
let dir = temp_dir("space");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join(format!("{NAME}.part")), &d[..1_000_000]).unwrap();
let r = download_with(
&Client::local(),
&entry(&s, None),
&dir,
&mut |_| {},
&AtomicBool::new(false),
&|_| Ok(MARGIN + 1_999_999),
);
let e = r.unwrap_err().to_string();
assert!(
e.starts_with(&format!("downloading {NAME} needs 0.1 GiB free in")),
"{e}"
);
let r = download_with(
&Client::local(),
&entry(&s, None),
&dir,
&mut |_| {},
&AtomicBool::new(false),
&|_| Ok(MARGIN + 2_000_000),
);
assert_eq!(r.unwrap(), dir.join(NAME));
let _ = std::fs::remove_dir_all(&dir);
}
/// The download's requests carry the pinned headers and the range alone.
#[test]
fn a_download_sends_only_the_pinned_headers() {
let d = data();
let s = cdn(d.clone(), None, false);
let dir = temp_dir("headers");
let (r, _) = run(
&entry(&s, Some(sha1_hex(&d))),
&dir,
&AtomicBool::new(false),
);
r.unwrap();
for q in s.requests() {
crate::sent_headers::assert_pinned(&q.headers, &["range"]);
}
let _ = std::fs::remove_dir_all(&dir);
}
/// One download of a file at a time.
#[test]
fn only_one_download_of_a_file_runs_at_a_time() {
let s = cdn(data(), None, false);
let dir = temp_dir("lock");
std::fs::create_dir_all(&dir).unwrap();
let held = lock(&dir, NAME).unwrap();
let (r, _) = run(&entry(&s, None), &dir, &AtomicBool::new(false));
assert_eq!(
r.unwrap_err().to_string(),
format!("another download of {NAME} is running")
);
assert!(s.requests().is_empty());
drop(held);
let _ = std::fs::remove_dir_all(&dir);
}
/// What a download still takes: the CDN's length, less what is here.
#[test]
fn what_a_download_still_takes() {
let d = data();
let s = cdn(d.clone(), None, false);
let dir = temp_dir("remaining");
let e = entry(&s, None);
let c = Client::local();
assert_eq!(remaining(&c, &e, &dir).unwrap(), (3_000_000, 0));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join(format!("{NAME}.part")), &d[..1000]).unwrap();
assert_eq!(remaining(&c, &e, &dir).unwrap(), (3_000_000, 1000));
assert_eq!(s.requests()[0].header("range"), Some("bytes=0-0"));
std::fs::write(dir.join(NAME), &d).unwrap();
assert_eq!(remaining(&c, &e, &dir).unwrap(), (3_000_000, 3_000_000));
assert_eq!(s.requests().len(), 2);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn only_apples_file_names_are_written() {
let s = cdn(data(), None, false);
let mut e = entry(&s, None);
e.url = s.url("/x/../../etc/passwd");
let dir = temp_dir("name");
let (r, _) = run(&e, &dir, &AtomicBool::new(false));
assert!(r.unwrap_err().to_string().contains("not UniversalMac_"));
assert!(s.requests().is_empty());
}
}
+346
View File
@@ -0,0 +1,346 @@
//! The disk's GUID partition table, laid out as Virtualization.framework's restore lays it out
//! (docs/design.md, "The disk"): three partitions, the iBoot system container, the main APFS
//! container and the recoveryOS container, in 512-byte sectors.
use std::io::{Seek, SeekFrom, Write};
use anyhow::{Result, ensure};
use uuid::Uuid;
/// The sector size of the table.
pub const SECTOR: u64 = 512;
/// The partition entries: 128 of 128 bytes, from LBA 2, and again before the backup header.
const ENTRIES: usize = 128;
const ENTRY_LEN: usize = 128;
const ENTRY_SECTORS: u64 = (ENTRIES * ENTRY_LEN) as u64 / SECTOR;
/// The first LBA a partition may use.
const FIRST_USABLE: u64 = 2 + ENTRY_SECTORS;
/// The iBoot system container's type, `Apple_APFS_ISC`.
pub const ISC_TYPE: Uuid = Uuid::from_u128(0x69646961_6700_11aa_aa11_00306543ecac);
/// The main container's type, `Apple_APFS`.
pub const APFS_TYPE: Uuid = Uuid::from_u128(0x7c3457ef_0000_11aa_aa11_00306543ecac);
/// The recoveryOS container's type, `Apple_APFS_Recovery`.
pub const RECOVERY_TYPE: Uuid = Uuid::from_u128(0x52637672_7900_11aa_aa11_00306543ecac);
/// The iBoot system container: 500 MiB from LBA 40.
const ISC_FIRST: u64 = 40;
const ISC_SECTORS: u64 = (500 << 20) / SECTOR;
/// The recoveryOS container: 5 GiB less 40 KiB, ending 7 sectors before the last usable one.
const RECOVERY_SECTORS: u64 = ((5 << 30) - (40 << 10)) / SECTOR;
const RECOVERY_GAP: u64 = 7;
/// One partition.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Partition {
/// Its type.
pub kind: Uuid,
/// Its own GUID.
pub guid: Uuid,
/// Its name.
pub name: &'static str,
/// Its first sector.
pub first: u64,
/// Its last sector, inclusive.
pub last: u64,
}
impl Partition {
/// Its first byte.
pub fn offset(&self) -> u64 {
self.first * SECTOR
}
/// Its length in bytes.
pub fn len(&self) -> u64 {
(self.last + 1 - self.first) * SECTOR
}
/// Whether it holds no sector (never, for a table [`Table::layout`] made).
pub fn is_empty(&self) -> bool {
self.last < self.first
}
}
/// The table of a disk.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Table {
/// The disk's GUID.
pub disk: Uuid,
/// The disk's size in sectors.
pub sectors: u64,
/// The iBoot system container, the main container and the recoveryOS container.
pub parts: [Partition; 3],
}
impl Table {
/// The table of a disk of `size` bytes, with random GUIDs. The layout is that of a 64 GiB
/// disk Virtualization.framework restored (14.6.1 to 27.2.1, all alike) **[vz]**; on other
/// sizes the first and last partitions keep their places from each end.
pub fn layout(size: u64) -> Result<Self> {
let g = || Uuid::new_v4();
Self::layout_with(size, g(), [g(), g(), g()])
}
/// [`Table::layout`] with the GUIDs given.
pub fn layout_with(size: u64, disk: Uuid, guids: [Uuid; 3]) -> Result<Self> {
ensure!(
size.is_multiple_of(4096),
"the disk's size, {size} bytes, is not a multiple of 4 KiB"
);
let sectors = size / SECTOR;
let last_usable = sectors - 1 - ENTRY_SECTORS - 1;
let recovery_last = last_usable - RECOVERY_GAP;
let recovery_first = recovery_last + 1 - RECOVERY_SECTORS;
let main_first = ISC_FIRST + ISC_SECTORS;
ensure!(
recovery_first > main_first + (1 << 30) / SECTOR,
"a disk of {size} bytes is too small for the three containers"
);
Ok(Self {
disk,
sectors,
parts: [
Partition {
kind: ISC_TYPE,
guid: guids[0],
name: "iBootSystemContainer",
first: ISC_FIRST,
last: main_first - 1,
},
Partition {
kind: APFS_TYPE,
guid: guids[1],
name: "Container",
first: main_first,
last: recovery_first - 1,
},
Partition {
kind: RECOVERY_TYPE,
guid: guids[2],
name: "RecoveryOSContainer",
first: recovery_first,
last: recovery_last,
},
],
})
}
/// The iBoot system container.
pub fn isc(&self) -> &Partition {
&self.parts[0]
}
/// The main container.
pub fn main(&self) -> &Partition {
&self.parts[1]
}
/// The recoveryOS container.
pub fn recovery(&self) -> &Partition {
&self.parts[2]
}
/// The partition entries, as they are written twice.
fn entries(&self) -> Vec<u8> {
let mut e = vec![0u8; ENTRIES * ENTRY_LEN];
for (i, p) in self.parts.iter().enumerate() {
let at = &mut e[i * ENTRY_LEN..(i + 1) * ENTRY_LEN];
at[..16].copy_from_slice(&guid_bytes(p.kind));
at[16..32].copy_from_slice(&guid_bytes(p.guid));
at[32..40].copy_from_slice(&p.first.to_le_bytes());
at[40..48].copy_from_slice(&p.last.to_le_bytes());
for (j, c) in p.name.encode_utf16().enumerate() {
at[56 + 2 * j..58 + 2 * j].copy_from_slice(&c.to_le_bytes());
}
}
e
}
/// A header: the primary one at LBA 1 when `primary`, else the backup at the last LBA.
fn header(&self, primary: bool, entries_crc: u32) -> [u8; SECTOR as usize] {
let last = self.sectors - 1;
let (me, other, entries_at) = if primary {
(1, last, 2)
} else {
(last, 1, last - ENTRY_SECTORS)
};
let mut h = [0u8; SECTOR as usize];
h[..8].copy_from_slice(b"EFI PART");
h[8..12].copy_from_slice(&0x0001_0000u32.to_le_bytes());
h[12..16].copy_from_slice(&92u32.to_le_bytes());
h[24..32].copy_from_slice(&me.to_le_bytes());
h[32..40].copy_from_slice(&other.to_le_bytes());
h[40..48].copy_from_slice(&FIRST_USABLE.to_le_bytes());
h[48..56].copy_from_slice(&(last - ENTRY_SECTORS - 1).to_le_bytes());
h[56..72].copy_from_slice(&guid_bytes(self.disk));
h[72..80].copy_from_slice(&entries_at.to_le_bytes());
h[80..84].copy_from_slice(&(ENTRIES as u32).to_le_bytes());
h[84..88].copy_from_slice(&(ENTRY_LEN as u32).to_le_bytes());
h[88..92].copy_from_slice(&entries_crc.to_le_bytes());
let crc = crc32fast::hash(&h[..92]);
h[16..20].copy_from_slice(&crc.to_le_bytes());
h
}
/// The protective MBR: one partition of type 0xEE over the whole disk, up to 2^32 - 1
/// sectors.
fn mbr(&self) -> [u8; SECTOR as usize] {
let mut m = [0u8; SECTOR as usize];
let e = &mut m[446..462];
e.copy_from_slice(&[
0x00, 0xfe, 0xff, 0xff, 0xee, 0xfe, 0xff, 0xff, 1, 0, 0, 0, 0, 0, 0, 0,
]);
let n = u32::try_from(self.sectors - 1).unwrap_or(u32::MAX);
e[12..].copy_from_slice(&n.to_le_bytes());
m[510] = 0x55;
m[511] = 0xaa;
m
}
/// Writes the protective MBR, both headers and both copies of the entries to `disk`, a
/// file already the table's size.
pub fn write<W: Write + Seek>(&self, disk: &mut W) -> Result<()> {
let entries = self.entries();
let crc = crc32fast::hash(&entries);
let last = self.sectors - 1;
disk.seek(SeekFrom::Start(0))?;
disk.write_all(&self.mbr())?;
disk.write_all(&self.header(true, crc))?;
disk.write_all(&entries)?;
disk.seek(SeekFrom::Start((last - ENTRY_SECTORS) * SECTOR))?;
disk.write_all(&entries)?;
disk.write_all(&self.header(false, crc))?;
Ok(())
}
}
/// A GUID as GPT stores it: the first three fields little-endian, the rest as they are.
pub fn guid_bytes(u: Uuid) -> [u8; 16] {
u.to_bytes_le()
}
#[cfg(test)]
mod tests {
use super::*;
/// The 64 GiB layout every reference guest has **[vz]**, with GUIDs of the tests' own.
#[test]
fn a_64_gib_disk_is_laid_out_as_vzs() {
let t = Table::layout(64 << 30).unwrap();
assert_eq!((t.isc().first, t.isc().last), (40, 1_024_039));
assert_eq!((t.main().first, t.main().last), (1_024_040, 123_732_007));
assert_eq!(
(t.recovery().first, t.recovery().last),
(123_732_008, 134_217_687)
);
assert_eq!(t.recovery().len(), 5_368_668_160);
assert_eq!(t.main().len(), 62_826_479_616);
assert_eq!(t.isc().len(), 500 << 20);
for p in &t.parts {
assert!(p.offset().is_multiple_of(4096) && p.len().is_multiple_of(4096));
}
}
#[test]
fn the_table_reads_back() {
let size = 40u64 << 30;
let ids = [Uuid::from_u128(1), Uuid::from_u128(2), Uuid::from_u128(3)];
let t = Table::layout_with(size, Uuid::from_u128(0xd15c), ids).unwrap();
let mut disk = Sparse {
len: size,
..Sparse::default()
};
t.write(&mut disk).unwrap();
let read = reims_apfs::gpt::read(&disk).unwrap();
assert_eq!(read.sector_size, SECTOR);
assert_eq!(read.disk_guid, "00000000-0000-0000-0000-00000000D15C");
assert_eq!(read.partitions.len(), 3);
for (r, p) in read.partitions.iter().zip(&t.parts) {
assert_eq!(r.type_guid, p.kind.to_string().to_uppercase());
assert_eq!(r.unique_guid, p.guid.to_string().to_uppercase());
assert_eq!(r.name, p.name);
assert_eq!((r.first_lba, r.last_lba), (p.first, p.last));
}
// The backup header names the primary, carries the same entries' CRC, and checks.
let last = t.sectors - 1;
let backup = disk.bytes_at(last * SECTOR, SECTOR as usize);
let primary = disk.bytes_at(SECTOR, SECTOR as usize);
assert_eq!(&backup[..8], b"EFI PART");
assert_eq!(u64::from_le_bytes(backup[32..40].try_into().unwrap()), 1);
assert_eq!(
u64::from_le_bytes(backup[72..80].try_into().unwrap()),
last - ENTRY_SECTORS
);
assert_eq!(backup[88..92], primary[88..92]);
let mut h = backup[..92].to_vec();
h[16..20].fill(0);
assert_eq!(crc32fast::hash(&h).to_le_bytes(), backup[16..20]);
let mbr = disk.bytes_at(0, 512);
assert_eq!(&mbr[510..], &[0x55, 0xaa]);
assert_eq!(
u64::from(u32::from_le_bytes(mbr[458..462].try_into().unwrap())),
t.sectors - 1
);
}
#[test]
fn a_disk_too_small_is_refused() {
assert!(Table::layout(6 << 30).is_err());
assert!(Table::layout((64 << 30) + 512).is_err());
}
/// A disk image of `len` bytes held as the writes made to it, the rest zero.
#[derive(Default)]
struct Sparse {
len: u64,
at: u64,
writes: Vec<(u64, Vec<u8>)>,
}
impl Sparse {
fn bytes_at(&self, off: u64, len: usize) -> Vec<u8> {
let mut out = vec![0u8; len];
for (o, d) in &self.writes {
for (i, b) in d.iter().enumerate() {
let p = o + i as u64;
if p >= off && p < off + len as u64 {
out[(p - off) as usize] = *b;
}
}
}
out
}
}
impl Write for Sparse {
fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
self.writes.push((self.at, b.to_vec()));
self.at += b.len() as u64;
Ok(b.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl Seek for Sparse {
fn seek(&mut self, p: SeekFrom) -> std::io::Result<u64> {
match p {
SeekFrom::Start(o) => self.at = o,
_ => unimplemented!("the table seeks from the start"),
}
Ok(self.at)
}
}
impl reims_apfs::dev::Source for Sparse {
fn read_at(&self, off: u64, buf: &mut [u8]) -> std::io::Result<()> {
buf.copy_from_slice(&self.bytes_at(off, buf.len()));
Ok(())
}
fn len(&self) -> u64 {
self.len
}
}
}
+382
View File
@@ -0,0 +1,382 @@
//! HTTPS to Apple's hosts for files: the client every such request goes through ([`Client`]),
//! and a file on Apple's CDN read at offsets by ranged requests ([`HttpRange`]): the parts of an
//! IPSW the tool needs without downloading it, such as AVPBooter from 14.6.1's system image
//! (avpbooter.rs). Apple's catalog of IPSWs (catalog.rs) and whole IPSWs (download.rs) come
//! through the same client.
//!
//! A request goes only to one of Apple's hosts ([`check_url`]), over HTTPS, with the fixed
//! User-Agent and no header naming the host, its user or this project. The client follows no
//! redirect by itself: [`Client::get`] follows each only to a URL [`check_url`] allows, so a
//! redirect can't take a request off Apple's hosts.
use std::collections::HashMap;
use std::io;
use std::sync::Mutex;
use std::time::Duration;
use anyhow::{Context, Result, bail, ensure};
use crate::source::ReadAt;
/// The hosts files are read from: Apple's CDN for IPSWs, and mesu for Apple's catalog of them.
const HOSTS: &[&str] = &["updates.cdn-apple.com", "mesu.apple.com"];
/// The most redirects a request follows.
const REDIRECTS: usize = 5;
/// Reads go in aligned blocks of this size, and this many are kept.
const BLOCK: u64 = 1 << 20;
const CACHED: usize = 64;
/// A file on Apple's CDN, read by ranged GETs and kept in a cache of blocks.
pub struct HttpRange {
client: Client,
url: String,
len: u64,
cache: Mutex<Cache>,
}
#[derive(Default)]
struct Cache {
blocks: HashMap<u64, (u64, Vec<u8>)>,
tick: u64,
}
/// Checks that `url` is HTTPS on one of Apple's hosts for IPSWs and their catalog.
pub fn check_url(url: &str) -> Result<()> {
let rest = url
.strip_prefix("https://")
.with_context(|| format!("{url} is not HTTPS"))?;
let host = rest.split(['/', ':', '?', '#']).next().unwrap_or_default();
ensure!(
HOSTS.contains(&host),
"{url} is not on Apple's hosts for IPSWs ({})",
HOSTS.join(", ")
);
Ok(())
}
/// The client requests for files go through: on Apple's hosts, or in tests a local server.
pub struct Client {
agent: ureq::Agent,
allow: fn(&str) -> Result<()>,
}
impl Client {
/// For Apple's hosts over HTTPS ([`check_url`]). A request ends when its connection, its
/// answer's head or any read of its body stalls for a minute, however long the body is.
pub fn apple() -> Client {
Client::with(check_url, true)
}
/// For a server on this host, over HTTP: the tests'.
#[cfg(test)]
pub fn local() -> Client {
fn allow(url: &str) -> Result<()> {
ensure!(url.starts_with("http://127.0.0.1:"), "{url} is not local");
Ok(())
}
Client::with(allow, false)
}
fn with(allow: fn(&str) -> Result<()>, https_only: bool) -> Client {
let minute = Some(Duration::from_secs(60));
let agent = ureq::Agent::config_builder()
.user_agent(crate::USER_AGENT)
.https_only(https_only)
.max_redirects(0)
.http_status_as_error(false)
.timeout_connect(minute)
.timeout_recv_response(minute)
.timeout_per_read(minute)
.build()
.into();
Client { agent, allow }
}
/// GETs `url`, with a `Range` header where `range` is given (`bytes=0-99`), following up to
/// [`REDIRECTS`] redirects, each only to a URL this client allows. Answers with any status
/// but a redirect; the URL that answered, and the answer.
pub fn get(
&self,
url: &str,
range: Option<&str>,
) -> Result<(String, ureq::http::Response<ureq::Body>)> {
let mut url = url.to_owned();
for _ in 0..=REDIRECTS {
(self.allow)(&url)?;
let mut req = self.agent.get(&url);
if let Some(r) = range {
req = req.header("Range", r);
}
let resp = req.call().with_context(|| format!("GET {url}"))?;
if !resp.status().is_redirection() {
return Ok((url, resp));
}
let to = resp
.headers()
.get("location")
.and_then(|v| v.to_str().ok())
.with_context(|| format!("{url} redirected with no Location"))?;
url = redirect_target(&url, to).with_context(|| format!("{url} redirected to {to}"))?;
}
bail!("{url}: more than {REDIRECTS} redirects")
}
}
/// Where a redirect from `from` to `location` goes: `location` if it is a URL, else its path on
/// `from`'s scheme and host.
fn redirect_target(from: &str, location: &str) -> Result<String> {
if location.contains("://") {
return Ok(location.to_owned());
}
ensure!(
location.starts_with('/') && !location.starts_with("//"),
"a Location that is neither a URL nor a path"
);
let (scheme, rest) = from.split_once("://").context("a URL with no scheme")?;
let host = rest.split(['/', '?', '#']).next().unwrap_or_default();
Ok(format!("{scheme}://{host}{location}"))
}
/// Parses a `Content-Range: bytes a-b/total` header into (a, b, total).
pub(crate) fn content_range(v: &str) -> Option<(u64, u64, u64)> {
let v = v.trim().strip_prefix("bytes ")?;
let (range, total) = v.split_once('/')?;
let (a, b) = range.split_once('-')?;
Some((a.parse().ok()?, b.parse().ok()?, total.parse().ok()?))
}
impl HttpRange {
/// Opens `url`, learning its length from a one-byte ranged request.
pub fn open(url: &str) -> Result<Self> {
Self::open_with(url, Client::apple())
}
fn open_with(url: &str, client: Client) -> Result<Self> {
(client.allow)(url)?;
let mut s = Self {
client,
url: url.to_owned(),
len: 0,
cache: Mutex::default(),
};
let (_, total) = s.get(0, 0).with_context(|| format!("reach {url}"))?;
s.len = total;
Ok(s)
}
/// Bytes `a..=b` of the file, and the file's length.
fn get(&self, a: u64, b: u64) -> Result<(Vec<u8>, u64)> {
let mut last = None;
for attempt in 0..4 {
if attempt > 0 {
std::thread::sleep(Duration::from_secs(1 << attempt));
}
let mut r = match self.client.get(&self.url, Some(&format!("bytes={a}-{b}"))) {
Ok((_, r)) if (400..500).contains(&r.status().as_u16()) => {
bail!("Apple's CDN refused {} ({})", self.url, r.status())
}
Ok((_, r)) if r.status().is_server_error() => {
last = Some(anyhow::anyhow!("Apple's CDN answered {}", r.status()));
continue;
}
Ok((_, r)) => r,
Err(e) => {
last = Some(e);
continue;
}
};
ensure!(
r.status().as_u16() == 206,
"Apple's CDN answered {} to a ranged request",
r.status()
);
let cr = r
.headers()
.get("content-range")
.and_then(|v| v.to_str().ok())
.and_then(content_range)
.context("Apple's CDN answered a ranged request without its range")?;
// b is within the file (block() clamps it), so the answer holds the whole range: a
// shorter one would leave a block short of what its readers slice from it.
ensure!(
cr.0 == a && cr.1 == b,
"Apple's CDN answered bytes {}-{} for {a}-{b}",
cr.0,
cr.1
);
// ureq's limit refuses a read once it is reached, so a body of exactly the limit
// fails (measured, ureq 3.5.1): one byte more, and the length is checked below.
match r.body_mut().with_config().limit(b - a + 2).read_to_vec() {
Ok(body) if body.len() as u64 == cr.1 - cr.0 + 1 => return Ok((body, cr.2)),
Ok(body) => {
last = Some(anyhow::anyhow!(
"a ranged answer of {} bytes for {}",
body.len(),
cr.1 - cr.0 + 1
))
}
Err(e) => last = Some(e.into()),
}
}
Err(last.unwrap()).with_context(|| format!("read bytes {a}-{b} of {}", self.url))
}
fn block(&self, index: u64) -> io::Result<Vec<u8>> {
{
let mut c = self.cache.lock().unwrap();
c.tick += 1;
let tick = c.tick;
if let Some(e) = c.blocks.get_mut(&index) {
e.0 = tick;
return Ok(e.1.clone());
}
}
let a = index * BLOCK;
let b = (a + BLOCK).min(self.len) - 1;
let (data, _) = self
.get(a, b)
.map_err(|e| io::Error::other(format!("{e:#}")))?;
let mut c = self.cache.lock().unwrap();
if c.blocks.len() >= CACHED
&& let Some(old) = c
.blocks
.iter()
.min_by_key(|(_, (t, _))| *t)
.map(|(k, _)| *k)
{
c.blocks.remove(&old);
}
let tick = c.tick;
c.blocks.insert(index, (tick, data.clone()));
Ok(data)
}
}
impl ReadAt for HttpRange {
fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize> {
if offset >= self.len {
return Ok(0);
}
let n = (buf.len() as u64).min(self.len - offset) as usize;
let mut done = 0;
while done < n {
let at = offset + done as u64;
let block = self.block(at / BLOCK)?;
let from = (at % BLOCK) as usize;
let take = (n - done).min(block.len() - from);
buf[done..done + take].copy_from_slice(&block[from..from + take]);
done += take;
}
Ok(n)
}
fn len(&self) -> u64 {
self.len
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_apples_hosts_over_https() {
assert!(check_url("https://updates.cdn-apple.com/a/b.ipsw").is_ok());
assert!(check_url("https://mesu.apple.com/assets/macos/c.xml").is_ok());
assert!(check_url("http://updates.cdn-apple.com/a/b.ipsw").is_err());
assert!(check_url("https://updates.cdn-apple.com.example.net/b.ipsw").is_err());
assert!(check_url("https://example.com/updates.cdn-apple.com/b.ipsw").is_err());
assert!(check_url("https://example.com#updates.cdn-apple.com").is_err());
}
#[test]
fn a_ranged_request_sends_only_the_pinned_headers() {
let h = crate::sent_headers::of(|url| {
Client::local().get(url, Some("bytes=0-0")).unwrap();
});
crate::sent_headers::assert_pinned(&h, &["range"]);
}
#[test]
fn redirects_are_followed_only_where_allowed() {
use crate::test_server::Server;
let s = Server::start(|path, _| match path {
"/a" => (302, vec![("Location".into(), "/b".into())], vec![]),
"/b" => (200, vec![], b"here".to_vec()),
"/away" => (
301,
vec![("Location".into(), "https://example.com/x.ipsw".into())],
vec![],
),
"/loop" => (302, vec![("Location".into(), "/loop".into())], vec![]),
_ => (404, vec![], vec![]),
});
let c = Client::local();
let (url, mut r) = c.get(&s.url("/a"), None).unwrap();
assert_eq!(url, s.url("/b"));
assert_eq!(r.body_mut().read_to_vec().unwrap(), b"here");
let e = format!("{:#}", c.get(&s.url("/away"), None).unwrap_err());
assert!(e.contains("https://example.com/x.ipsw is not local"), "{e}");
let e = format!("{:#}", c.get(&s.url("/loop"), None).unwrap_err());
assert!(e.contains("more than 5 redirects"), "{e}");
// the redirect to example.com was refused before any request went there
assert_eq!(
s.paths(),
[
"/a", "/b", "/away", "/loop", "/loop", "/loop", "/loop", "/loop", "/loop"
]
);
}
/// A ranged answer must hold the range asked for: a shorter one, or another range, is an
/// error, not a short block.
#[test]
fn a_short_ranged_answer_is_refused() {
use crate::test_server::Server;
let s = Server::start(|path, req| {
let total = 4u64 << 20;
let (a, b) = req
.header("range")
.and_then(|r| r.strip_prefix("bytes="))
.and_then(|r| r.split_once('-'))
.map(|(a, b)| (a.parse::<u64>().unwrap(), b.parse::<u64>().unwrap()))
.unwrap();
// "/short" answers one byte short of what was asked past the first byte
let b2 = if path == "/short" && b > 0 { b - 1 } else { b };
(
206,
vec![("Content-Range".into(), format!("bytes {a}-{b2}/{total}"))],
vec![7u8; (b2 - a + 1) as usize],
)
});
let mut buf = [0u8; 16];
let ok = HttpRange::open_with(&s.url("/whole"), Client::local()).unwrap();
assert_eq!(ok.read_at(5, &mut buf).unwrap(), 16);
let short = HttpRange::open_with(&s.url("/short"), Client::local()).unwrap();
let e = short.read_at(5, &mut buf).unwrap_err().to_string();
assert!(e.contains("answered bytes 0-1048574 for 0-1048575"), "{e}");
}
#[test]
fn a_redirect_keeps_the_scheme_and_host() {
assert_eq!(
redirect_target("https://mesu.apple.com/a/b.xml", "/c.xml").unwrap(),
"https://mesu.apple.com/c.xml"
);
assert_eq!(
redirect_target("https://a.example/x", "https://b.example/y").unwrap(),
"https://b.example/y"
);
assert!(redirect_target("https://a.example/x", "//b.example/y").is_err());
assert!(redirect_target("https://a.example/x", "y").is_err());
}
#[test]
fn content_ranges_parse() {
assert_eq!(content_range("bytes 0-0/1234"), Some((0, 0, 1234)));
assert_eq!(content_range("bytes 5-9/10"), Some((5, 9, 10)));
assert_eq!(content_range("bytes */10"), None);
}
}
+209
View File
@@ -0,0 +1,209 @@
//! An IPSW's disk images, opened where they lie: a stored member read in place, decrypted if it
//! is an Apple Encrypted Archive, then unpacked if it is a UDIF image.
use std::io::{self, Read};
use std::sync::Arc;
use anyhow::{Context, Result, bail};
use crate::aea::{self, Aea, KeyService};
use crate::ipsw::Ipsw;
use crate::source::{Cursor, ReadAt, SubRange};
use crate::udif::Udif;
/// What an image member is, layer by layer.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Layers {
/// An Apple Encrypted Archive around the rest.
pub encrypted: bool,
/// A UDIF image (inside the archive, if any).
pub udif: bool,
}
/// A source of an image's bytes, any of the layers.
pub type Source = Arc<dyn ReadAt>;
/// Opens member `name` of `ipsw`, a stored image: returns its plaintext (the archive decrypted,
/// with its key from `keys`) and what it was.
pub fn open_plain(ipsw: &Ipsw, name: &str, keys: &dyn KeyService) -> Result<(Source, Layers)> {
let range = ipsw
.range(name)?
.with_context(|| format!("{name} is deflated in the IPSW, so it can't be read in place"))?;
let mut head = [0u8; 4];
range
.read_exact_at(0, &mut head)
.with_context(|| format!("read {name}"))?;
if aea::is_aea(&head) {
let key = aea::archive_key(&range, keys).with_context(|| format!("get {name}'s key"))?;
let plain = Aea::open(range, &key).with_context(|| format!("decrypt {name}"))?;
Ok((
Arc::new(plain),
Layers {
encrypted: true,
udif: false,
},
))
} else {
Ok((Arc::new(range), Layers::default()))
}
}
/// Member `name`'s plaintext as a stream, front to back, and its length: an Apple Encrypted
/// Archive decrypted (stored, as every IPSW keeps its archives), a deflated member inflated (as
/// 14's IPSWs keep their BaseSystem and Cryptex1 images, and every IPSW its Cryptex1 AppOS and
/// 27's its RosettaOS), any other member as stored. A member read from the zip has its CRC-32
/// checked at its end; an archive's segments are checked as they are decrypted.
pub fn plain_stream(
ipsw: &Ipsw,
name: &str,
keys: &dyn KeyService,
) -> Result<(u64, Box<dyn Read + Send>)> {
let size = ipsw.member(name)?.size;
let mut r = ipsw.reader(name)?;
let mut head = Vec::new();
(&mut r)
.take(4)
.read_to_end(&mut head)
.with_context(|| format!("read {name}"))?;
if !aea::is_aea(&head) {
return Ok((size, Box::new(io::Cursor::new(head).chain(r))));
}
drop(r);
if ipsw.range(name)?.is_none() {
bail!("{name} is an encrypted archive deflated in the IPSW, which no IPSW has been");
}
let (plain, _) = open_plain(ipsw, name, keys)?;
Ok((plain.len(), Box::new(Cursor::new(plain))))
}
/// Opens member `name` as a disk: its plaintext, unpacked if it is a UDIF image.
pub fn open_disk(ipsw: &Ipsw, name: &str, keys: &dyn KeyService) -> Result<(Source, Layers)> {
let (plain, mut layers) = open_plain(ipsw, name, keys)?;
if is_udif(&*plain)? {
let img = Udif::open(plain).with_context(|| format!("open {name} as a UDIF image"))?;
layers.udif = true;
Ok((Arc::new(img), layers))
} else {
Ok((plain, layers))
}
}
/// Opens member `name`'s APFS container: the `Apple_APFS` partition of its disk, or the whole
/// disk where it is the container itself.
pub fn open_apfs(ipsw: &Ipsw, name: &str, keys: &dyn KeyService) -> Result<(Source, Layers)> {
let (plain, mut layers) = open_plain(ipsw, name, keys)?;
if is_udif(&*plain)? {
let img = Udif::open(plain).with_context(|| format!("open {name} as a UDIF image"))?;
layers.udif = true;
let p = img
.partition("Apple_APFS")
.with_context(|| format!("find {name}'s APFS container"))?
.clone();
let img: Source = Arc::new(img);
let part = SubRange::new(img, p.offset, p.len)?;
check_nxsb(&part, name)?;
Ok((Arc::new(part), layers))
} else {
check_nxsb(&*plain, name)?;
Ok((plain, layers))
}
}
/// An APFS reader's view of one of our sources.
struct Adapt(Source);
impl reims_apfs::dev::Source for Adapt {
fn read_at(&self, off: u64, buf: &mut [u8]) -> std::io::Result<()> {
self.0.read_exact_at(off, buf)
}
fn len(&self) -> u64 {
self.0.len()
}
}
/// Opens member `name`'s APFS container for reading files out of it.
pub fn open_container(
ipsw: &Ipsw,
name: &str,
keys: &dyn KeyService,
) -> Result<reims_apfs::Container> {
let (src, _) = open_apfs(ipsw, name, keys)?;
reims_apfs::open(Arc::new(Adapt(src))).with_context(|| format!("open {name}'s APFS container"))
}
/// Opens member `name`'s APFS container for reading files and records out of it, with the
/// source it reads: a block `b` of the container is at `b * block_size` of the source, so a
/// copy can read a stream's extents straight from it.
pub fn open_container_source(
ipsw: &Ipsw,
name: &str,
keys: &dyn KeyService,
) -> Result<(Source, reims_apfs::Container)> {
let (src, _) = open_apfs(ipsw, name, keys)?;
let c = reims_apfs::open(Arc::new(Adapt(src.clone())))
.with_context(|| format!("open {name}'s APFS container"))?;
Ok((src, c))
}
/// Whether `src` ends in a UDIF trailer.
pub fn is_udif(src: &dyn ReadAt) -> Result<bool> {
let len = src.len();
if len < 512 {
return Ok(false);
}
let mut koly = [0u8; 4];
src.read_exact_at(len - 512, &mut koly)
.context("read an image's last sector")?;
Ok(&koly == b"koly")
}
/// Fails unless `src` starts with an APFS container superblock.
fn check_nxsb(src: &dyn ReadAt, name: &str) -> Result<()> {
let mut b = [0u8; 36];
src.read_exact_at(0, &mut b)
.with_context(|| format!("read {name}'s container"))?;
if &b[32..36] != b"NXSB" {
bail!("{name} holds no APFS container");
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::aea::AppleKeyService;
use crate::ipsw::tests::zip_with;
fn read_all(ipsw: &Ipsw, name: &str) -> Result<(u64, Vec<u8>)> {
let (len, mut r) = plain_stream(ipsw, name, &AppleKeyService::default())?;
let mut out = Vec::new();
r.read_to_end(&mut out)?;
Ok((len, out))
}
#[test]
fn a_stored_or_deflated_image_streams_as_it_is() {
let big: Vec<u8> = (0..300_000u32).flat_map(|i| i.to_le_bytes()).collect();
let p = zip_with(&[
("stored.dmg", &big, false),
("deflated.dmg", &big, true),
("tiny", b"ab", true),
]);
let ipsw = Ipsw::open(&p.0).unwrap();
for name in ["stored.dmg", "deflated.dmg"] {
let (len, got) = read_all(&ipsw, name).unwrap();
assert_eq!(len, big.len() as u64);
assert!(got == big, "{name}");
}
assert_eq!(read_all(&ipsw, "tiny").unwrap(), (2, b"ab".to_vec()));
}
#[test]
fn a_deflated_encrypted_archive_is_refused() {
let p = zip_with(&[("x.dmg.aea", b"AEA1 and the rest", true)]);
let ipsw = Ipsw::open(&p.0).unwrap();
let e = read_all(&ipsw, "x.dmg.aea").unwrap_err();
assert!(format!("{e:#}").contains("deflated"), "{e:#}");
}
}
File diff suppressed because it is too large. Load diff
+601
View File
@@ -0,0 +1,601 @@
//! An IPSW, read where it lies: its zip directory, its small members whole, its large ones as
//! streams, and stored ones at random offsets, with no extraction to disk.
use std::collections::HashMap;
use std::fs::File;
use std::io::{self, BufReader, Read};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use anyhow::{Context, Result, bail};
use crate::source::{Cursor, ReadAt, SubRange};
/// How a member is stored in the zip.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Method {
/// Stored as it is: its bytes can be read at any offset.
Stored,
/// Deflated: its bytes can only be streamed.
Deflated,
}
/// One member of the IPSW's zip.
#[derive(Clone, Debug)]
pub struct Member {
/// Its name in the zip.
pub name: String,
/// Where its data starts in the file.
pub data_start: u64,
/// Its size in the zip.
pub compressed_size: u64,
/// Its size once read.
pub size: u64,
/// How it is stored.
pub method: Method,
/// The CRC-32 of its contents.
pub crc32: u32,
/// Its Unix mode (type and permission bits), where the zip records one.
pub mode: Option<u32>,
/// Its modification time, Unix seconds: the zip's extended timestamp where it has one, else
/// its DOS time read as UTC.
pub mtime: u32,
/// Whether it is a directory.
pub dir: bool,
}
/// A stored member's bytes, read at offsets.
pub type Range = SubRange<Arc<dyn ReadAt>>;
/// An open IPSW.
pub struct Ipsw {
path: PathBuf,
src: Arc<dyn ReadAt>,
members: HashMap<String, Member>,
/// Its directories' entries, by name (ending with `/`).
dirs: HashMap<String, Member>,
}
impl Ipsw {
/// Opens `path` and reads its zip directory.
pub fn open(path: &Path) -> Result<Self> {
let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
Self::from_source(Arc::new(crate::source::FileRange::whole(file)?), path)
}
/// Reads the zip directory of an IPSW whose bytes `src` gives, such as a ranged download.
/// `path` names it in messages.
pub fn from_source(src: Arc<dyn ReadAt>, path: &Path) -> Result<Self> {
let mut zip =
zip::ZipArchive::new(BufReader::new(Cursor::new(src.clone()))).with_context(|| {
format!(
"{} is not a zip archive: is it a whole IPSW?",
path.display()
)
})?;
let mut members = HashMap::new();
let mut dirs = HashMap::new();
for i in 0..zip.len() {
let f = zip
.by_index_raw(i)
.with_context(|| format!("read member {i} of {}", path.display()))?;
let name = f.name().context("a member's name")?.into_owned();
let mtime = mtime(&f);
if f.is_dir() {
dirs.insert(
name.clone(),
Member {
name,
data_start: 0,
compressed_size: 0,
size: 0,
method: Method::Stored,
crc32: 0,
mode: f.unix_mode(),
mtime,
dir: true,
},
);
continue;
}
let method = match f.compression() {
zip::CompressionMethod::Stored => Method::Stored,
zip::CompressionMethod::Deflated => Method::Deflated,
other => bail!("{name} is compressed with {other:?}, which an IPSW doesn't use"),
};
if f.encrypted() {
bail!("{name} is encrypted in the zip, which an IPSW never is");
}
let data_start = f
.data_start()
.with_context(|| format!("{name}: no data offset"))?;
members.insert(
name.clone(),
Member {
name,
data_start,
compressed_size: f.compressed_size(),
size: f.size(),
method,
crc32: f.crc32(),
mode: f.unix_mode(),
mtime,
dir: false,
},
);
}
let len = src.len();
for m in members.values() {
if m.data_start
.checked_add(m.compressed_size)
.is_none_or(|end| end > len)
{
bail!(
"{} ends past the end of {} ({len} bytes): the IPSW is truncated",
m.name,
path.display()
);
}
}
Ok(Self {
path: path.to_owned(),
src,
members,
dirs,
})
}
/// The IPSW's path.
pub fn path(&self) -> &Path {
&self.path
}
/// The member called `name`.
pub fn member(&self, name: &str) -> Result<&Member> {
self.members
.get(name)
.with_context(|| format!("the IPSW has no {name}"))
}
/// Whether the IPSW has a member called `name`.
pub fn has(&self, name: &str) -> bool {
self.members.contains_key(name)
}
/// The members whose names start with `prefix`, directories too, by name.
pub fn entries(&self, prefix: &str) -> Vec<&Member> {
let mut v: Vec<&Member> = self
.members
.values()
.chain(self.dirs.values())
.filter(|m| m.name.starts_with(prefix))
.collect();
v.sort_by(|a, b| a.name.cmp(&b.name));
v
}
/// Every member's name.
pub fn names(&self) -> impl Iterator<Item = &str> {
self.members.keys().map(String::as_str)
}
/// Reads a member whole into memory, checking its CRC-32: for manifests, property lists and
/// the components iBoot takes whole (the restore ramdisk is 373 MB on 27.2.1). Images are
/// read with [`Ipsw::reader`] or [`Ipsw::range`] instead.
pub fn read(&self, name: &str) -> Result<Vec<u8>> {
let m = self.member(name)?;
let size = usize::try_from(m.size)
.with_context(|| format!("{name} is {} bytes, too large for memory", m.size))?;
let mut out = Vec::new();
out.try_reserve_exact(size)
.with_context(|| format!("no memory for {name}'s {size} bytes"))?;
self.reader(name)?
.read_to_end(&mut out)
.with_context(|| format!("read {name} from the IPSW"))?;
Ok(out)
}
/// A stream of a member's contents, which fails at its end, and on every read after, if its
/// CRC-32 or size is wrong.
pub fn reader(&self, name: &str) -> Result<Box<dyn Read + Send>> {
let m = self.member(name)?.clone();
let raw = Cursor::new(SubRange::new(
self.src.clone(),
m.data_start,
m.compressed_size,
)?);
let inner: Box<dyn Read + Send> = match m.method {
Method::Stored => Box::new(raw),
Method::Deflated => Box::new(flate2::read::DeflateDecoder::new(
BufReader::with_capacity(1 << 20, raw),
)),
};
Ok(Box::new(Checked {
inner,
name: m.name,
want_size: m.size,
want_crc: m.crc32,
size: 0,
crc: crc32fast::Hasher::new(),
end: None,
}))
}
/// A stored member's bytes at random offsets, or `None` if it is deflated.
pub fn range(&self, name: &str) -> Result<Option<Range>> {
let m = self.member(name)?;
if m.method != Method::Stored {
return Ok(None);
}
Ok(Some(SubRange::new(self.src.clone(), m.data_start, m.size)?))
}
/// A stored member read in place, as [`Ipsw::range`], whose CRC-32 is checked as it is read
/// front to back: see [`CheckedRange`]. `None` if the member is compressed.
pub fn checked_range(&self, name: &str) -> Result<Option<CheckedRange>> {
let m = self.member(name)?;
Ok(self.range(name)?.map(|range| CheckedRange {
range,
name: m.name.clone(),
want_crc: m.crc32,
front: Mutex::new(Front {
next: 0,
crc: crc32fast::Hasher::new(),
damaged: None,
}),
}))
}
}
/// A stored member read in place whose CRC-32 is checked as it is read front to back, as ASR
/// streams the system image: the read that carries the front to the member's end fails if the
/// member's CRC-32 is wrong, and so does every read after it. A read behind the front, or past a
/// gap ahead of it, is served unchecked and leaves the front where it is.
pub struct CheckedRange {
range: Range,
name: String,
want_crc: u32,
front: Mutex<Front>,
}
/// How far a [`CheckedRange`] has been read front to back, and the CRC-32 of that much.
struct Front {
next: u64,
crc: crc32fast::Hasher,
damaged: Option<String>,
}
impl ReadAt for CheckedRange {
fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize> {
let n = self.range.read_at(offset, buf)?;
let mut f = self.front.lock().unwrap_or_else(|e| e.into_inner());
if let Some(msg) = &f.damaged {
return Err(io::Error::new(io::ErrorKind::InvalidData, msg.clone()));
}
let end = offset + n as u64;
if offset <= f.next && end > f.next {
let from = (f.next - offset) as usize;
f.crc.update(&buf[from..n]);
f.next = end;
if f.next == self.range.len() {
let crc = std::mem::take(&mut f.crc).finalize();
if crc != self.want_crc {
let msg = format!(
"{}'s CRC-32 is {crc:08x}, not {:08x}: the IPSW is damaged",
self.name, self.want_crc
);
f.damaged = Some(msg.clone());
return Err(io::Error::new(io::ErrorKind::InvalidData, msg));
}
}
}
Ok(n)
}
fn len(&self) -> u64 {
self.range.len()
}
}
/// A zip entry's modification time, Unix seconds.
fn mtime<R: std::io::Read>(f: &zip::read::ZipFile<'_, R>) -> u32 {
for e in f.extra_data_fields() {
if let zip::ExtraField::ExtendedTimestamp(t) = e
&& let Some(t) = t.mod_time()
{
return t;
}
}
f.last_modified().map_or(0, |d| {
unix_seconds(
d.year().into(),
d.month().into(),
d.day().into(),
d.hour().into(),
d.minute().into(),
d.second().into(),
)
})
}
/// A UTC civil time as Unix seconds (0 before 1970, clamped to u32).
fn unix_seconds(y: i64, mo: i64, d: i64, h: i64, mi: i64, s: i64) -> u32 {
// days from 1970-01-01, by the proleptic Gregorian calendar
let y = if mo <= 2 { y - 1 } else { y };
let era = y.div_euclid(400);
let yoe = y - era * 400;
let mp = (mo + 9) % 12;
let doy = (153 * mp + 2) / 5 + d - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
let days = era * 146097 + doe - 719468;
(days * 86400 + h * 3600 + mi * 60 + s).clamp(0, u32::MAX.into()) as u32
}
/// A member's stream that checks its size and CRC-32 at its end.
struct Checked {
inner: Box<dyn Read + Send>,
name: String,
want_size: u64,
want_crc: u32,
size: u64,
crc: crc32fast::Hasher,
/// The end's verdict once a read has reached it, which every later read returns:
/// `Read` lets a caller read again past the end.
end: Option<Result<(), (io::ErrorKind, String)>>,
}
impl Checked {
/// The verdict on a stream that has ended at `self.size` bytes.
fn verdict(&mut self) -> Result<(), (io::ErrorKind, String)> {
if self.size != self.want_size {
return Err((
io::ErrorKind::UnexpectedEof,
format!(
"{} ends after {} of its {} bytes: the IPSW is damaged",
self.name, self.size, self.want_size
),
));
}
let crc = std::mem::take(&mut self.crc).finalize();
if crc != self.want_crc {
return Err((
io::ErrorKind::InvalidData,
format!(
"{}'s CRC-32 is {crc:08x}, not {:08x}: the IPSW is damaged",
self.name, self.want_crc
),
));
}
Ok(())
}
}
impl Read for Checked {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if let Some(end) = &self.end {
return match end {
Ok(()) => Ok(0),
Err((kind, msg)) => Err(io::Error::new(*kind, msg.clone())),
};
}
let n = self.inner.read(buf)?;
self.size += n as u64;
if self.size > self.want_size {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"{} holds more than its {} bytes: the IPSW is damaged",
self.name, self.want_size
),
));
}
self.crc.update(&buf[..n]);
if n == 0 && !buf.is_empty() {
let end = self.verdict();
self.end = Some(end);
return self.read(buf);
}
Ok(n)
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use std::io::Write;
/// A zip of `members`: name, contents, and whether deflated.
pub(crate) fn zip_with(members: &[(&str, &[u8], bool)]) -> tempfile_path::TempPath {
let p = tempfile_path::TempPath::new("zip");
let f = File::create(&p.0).unwrap();
let mut w = zip::ZipWriter::new(f);
for (name, data, deflate) in members {
let opts = zip::write::SimpleFileOptions::default().compression_method(if *deflate {
zip::CompressionMethod::Deflated
} else {
zip::CompressionMethod::Stored
});
w.start_file(*name, opts).unwrap();
w.write_all(data).unwrap();
}
w.finish().unwrap();
p
}
pub(crate) mod tempfile_path {
use std::path::PathBuf;
/// A path in the system's temporary directory, removed when dropped.
pub struct TempPath(pub PathBuf);
impl TempPath {
pub fn new(ext: &str) -> Self {
let mut b = [0u8; 8];
getrandom::fill(&mut b).unwrap();
Self(std::env::temp_dir().join(format!(
"reims-restore-test-{}.{ext}",
u64::from_le_bytes(b)
)))
}
}
impl Drop for TempPath {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
}
#[test]
fn stored_and_deflated_members_read_back() {
let big: Vec<u8> = (0..100_000u32).flat_map(|i| i.to_le_bytes()).collect();
let p = zip_with(&[("a.txt", b"hello", false), ("dir/b.bin", &big, true)]);
let ipsw = Ipsw::open(&p.0).unwrap();
assert_eq!(ipsw.read("a.txt").unwrap(), b"hello");
assert_eq!(ipsw.read("dir/b.bin").unwrap(), big);
assert!(ipsw.range("dir/b.bin").unwrap().is_none());
let r = ipsw.range("a.txt").unwrap().unwrap();
let mut buf = [0u8; 3];
crate::source::ReadAt::read_exact_at(&r, 2, &mut buf).unwrap();
assert_eq!(&buf, b"llo");
assert!(ipsw.read("missing").is_err());
}
#[test]
fn a_members_unix_mode_is_kept() {
let p = tempfile_path::TempPath::new("zip");
let mut w = zip::ZipWriter::new(File::create(&p.0).unwrap());
let opts = zip::write::SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Stored)
.unix_permissions(0o755);
w.start_file("tool", opts).unwrap();
w.write_all(b"#!").unwrap();
w.finish().unwrap();
let ipsw = Ipsw::open(&p.0).unwrap();
assert_eq!(
ipsw.member("tool").unwrap().mode.map(|m| m & 0o777),
Some(0o755)
);
}
#[test]
fn entries_list_directories_and_times() {
let p = tempfile_path::TempPath::new("zip");
let mut w = zip::ZipWriter::new(File::create(&p.0).unwrap());
let t = zip::DateTime::from_date_and_time(2024, 7, 29, 12, 30, 10).unwrap();
let opts = zip::write::SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Stored)
.last_modified_time(t);
w.add_directory("Firmware/", opts.unix_permissions(0o755))
.unwrap();
w.start_file("Firmware/a.im4p", opts).unwrap();
w.write_all(b"abc").unwrap();
w.start_file("other", opts).unwrap();
w.finish().unwrap();
let ipsw = Ipsw::open(&p.0).unwrap();
let e = ipsw.entries("Firmware/");
let names: Vec<_> = e.iter().map(|m| (m.name.as_str(), m.dir, m.size)).collect();
assert_eq!(
names,
[("Firmware/", true, 0), ("Firmware/a.im4p", false, 3)]
);
// 2024-07-29 12:30:10 UTC
assert_eq!(e[1].mtime, 1_722_256_210);
assert!(!ipsw.has("Firmware/"));
}
#[test]
fn civil_times_become_unix_seconds() {
assert_eq!(unix_seconds(1970, 1, 1, 0, 0, 0), 0);
assert_eq!(unix_seconds(2000, 3, 1, 0, 0, 0), 951_868_800);
assert_eq!(unix_seconds(1960, 1, 1, 0, 0, 0), 0);
}
#[test]
fn a_damaged_member_fails_its_crc() {
let p = zip_with(&[("a.txt", b"hello world", false)]);
let ipsw = Ipsw::open(&p.0).unwrap();
let start = ipsw.member("a.txt").unwrap().data_start;
drop(ipsw);
let mut bytes = std::fs::read(&p.0).unwrap();
bytes[start as usize] ^= 1;
std::fs::write(&p.0, &bytes).unwrap();
let ipsw = Ipsw::open(&p.0).unwrap();
let err = ipsw.read("a.txt").unwrap_err();
assert!(format!("{err:#}").contains("CRC-32"), "{err:#}");
}
#[test]
fn reads_past_the_end_repeat_its_verdict() {
let p = zip_with(&[("a.txt", b"hello", false), ("b.txt", b"world", true)]);
let ipsw = Ipsw::open(&p.0).unwrap();
for name in ["a.txt", "b.txt"] {
let mut s = ipsw.reader(name).unwrap();
let mut all = Vec::new();
s.read_to_end(&mut all).unwrap();
assert_eq!(all.len(), 5);
let mut buf = [0u8; 16];
assert_eq!(s.read(&mut buf).unwrap(), 0);
assert_eq!(s.read(&mut buf).unwrap(), 0);
}
let start = ipsw.member("a.txt").unwrap().data_start;
drop(ipsw);
let mut bytes = std::fs::read(&p.0).unwrap();
bytes[start as usize] ^= 1;
std::fs::write(&p.0, &bytes).unwrap();
let ipsw = Ipsw::open(&p.0).unwrap();
let mut s = ipsw.reader("a.txt").unwrap();
let mut all = Vec::new();
let first = s.read_to_end(&mut all).unwrap_err().to_string();
let mut buf = [0u8; 16];
let again = s.read(&mut buf).unwrap_err().to_string();
assert_eq!(first, again);
assert!(!first.contains("00000000"), "{first}");
}
#[test]
fn a_checked_range_fails_where_its_front_reaches_a_damaged_end() {
let data: Vec<u8> = (0..70_000u32).map(|i| (i * 13 % 251) as u8).collect();
let p = zip_with(&[("img", &data, false)]);
let ipsw = Ipsw::open(&p.0).unwrap();
// Sound: read front to back in uneven pieces, with a look behind and one far ahead.
let r = ipsw.checked_range("img").unwrap().unwrap();
let mut buf = vec![0u8; 9_000];
r.read_exact_at(60_000, &mut buf[..100]).unwrap();
let mut off = 0u64;
while off < r.len() {
let n = (r.len() - off).min(9_000) as usize;
r.read_exact_at(off, &mut buf[..n]).unwrap();
r.read_exact_at(off / 2, &mut buf[..10]).unwrap();
off += n as u64;
}
r.read_exact_at(0, &mut buf[..10]).unwrap();
// Damaged: one bit flipped in the middle.
let start = ipsw.member("img").unwrap().data_start;
drop((r, ipsw));
let mut bytes = std::fs::read(&p.0).unwrap();
bytes[start as usize + 35_000] ^= 2;
std::fs::write(&p.0, &bytes).unwrap();
let ipsw = Ipsw::open(&p.0).unwrap();
let r = ipsw.checked_range("img").unwrap().unwrap();
let mut off = 0u64;
let err = loop {
let n = (r.len() - off).min(9_000) as usize;
if let Err(e) = r.read_exact_at(off, &mut buf[..n]) {
break e;
}
off += n as u64;
};
assert!(off + 9_000 >= r.len(), "failed before the end, at {off}");
assert!(err.to_string().contains("CRC-32"), "{err}");
assert!(r.read_exact_at(0, &mut buf[..10]).is_err());
}
#[test]
fn a_truncated_ipsw_is_refused() {
let p = zip_with(&[("a.txt", &[7u8; 5000], false)]);
let bytes = std::fs::read(&p.0).unwrap();
// Keep the directory but drop the member's data: the directory then points past the
// end once the tail is moved up.
let q = tempfile_path::TempPath::new("zip");
std::fs::write(&q.0, &bytes[..bytes.len() / 2]).unwrap();
assert!(Ipsw::open(&q.0).is_err());
}
}
+426
View File
@@ -0,0 +1,426 @@
//! The boot kernel collection an IPSW carries (its install identity's `KernelCache`, IM4P
//! `krnl`): the payload decompressed — LZFSE (`bvx2`) or LZSS (`complzss`) — and read as a
//! Mach-O file set (`MH_FILESET`), each kext found by its `LC_FILESET_ENTRY` and its segments by
//! its own load commands. Ambrosia loads this same kernel collection from the guest's Preboot and
//! patches kexts' segments in place; the LocalPolicy's trust anchors are read from it
//! ([`crate::anchors`]).
//!
//! A file set's offsets are from the start of the whole collection: an entry's Mach-O header
//! is at its `fileoff`, and its segments' and sections' file offsets are the collection's.
use anyhow::{Context, Result, bail, ensure};
use crate::img4;
const MH_MAGIC_64: u32 = 0xfeed_facf;
const MH_FILESET: u32 = 0xc;
const LC_SEGMENT_64: u32 = 0x19;
const LC_FILESET_ENTRY: u32 = 0x8000_0035;
const MACH_HEADER_64: usize = 32;
const SEGMENT_COMMAND_64: usize = 72;
const SECTION_64: usize = 80;
/// The LZSS payload's header: `complzss`, an Adler-32 of the decompressed bytes, their size
/// and the compressed size (each 32-bit big-endian), then padding; the stream starts at 0x180.
const LZSS_MAGIC: &[u8; 8] = b"complzss";
const LZSS_DATA: usize = 0x180;
/// The kernel collection IM4P `im4p` holds, decompressed.
///
/// # Errors
///
/// The IM4P is not `krnl`, its payload is neither compressed form nor a Mach-O, or it does not
/// decompress to the size it records.
pub fn decompress(im4p: &[u8]) -> Result<Vec<u8>> {
let p = img4::parse_im4p(im4p).context("read the kernel cache's IM4P")?;
ensure!(
&p.tag == b"krnl",
"the kernel cache is IM4P {}, not krnl",
String::from_utf8_lossy(&p.tag)
);
let b = &p.payload;
let out = if b.starts_with(b"bvx2") || b.starts_with(b"bvx1") || b.starts_with(b"bvxn") {
let mut out = Vec::new();
lzfse_rust::decode_bytes(b, &mut out)
.map_err(|e| anyhow::anyhow!("the kernel cache's LZFSE: {e}"))?;
if let Some(c) = p.compression {
ensure!(
out.len() as u64 == c.size,
"the kernel cache decompresses to {} bytes, not the {} its IM4P records",
out.len(),
c.size
);
}
out
} else if b.starts_with(LZSS_MAGIC) {
lzss_payload(b)?
} else if b.get(..4) == Some(&MH_MAGIC_64.to_le_bytes()) {
b.clone()
} else {
bail!("the kernel cache's payload is neither LZFSE, LZSS nor a Mach-O")
};
Ok(out)
}
/// A `complzss` payload, decompressed and checked against its header.
fn lzss_payload(b: &[u8]) -> Result<Vec<u8>> {
ensure!(
b.len() >= LZSS_DATA,
"an LZSS payload shorter than its header"
);
let be = |at: usize| u32::from_be_bytes(b[at..at + 4].try_into().unwrap());
let (sum, size, stored) = (be(8), be(12) as usize, be(16) as usize);
let data = b
.get(LZSS_DATA..LZSS_DATA + stored)
.context("an LZSS payload shorter than its compressed size")?;
let out = lzss(data, size);
ensure!(
out.len() == size,
"an LZSS payload decompresses to {} of {size} bytes",
out.len()
);
ensure!(adler32(&out) == sum, "an LZSS payload fails its checksum");
Ok(out)
}
/// LZSS as Apple's kernel caches use it: a 4 KiB ring first filled with spaces, a flag byte
/// before each eight items, a set bit a literal byte and a clear one a 12-bit ring position and
/// a 4-bit length of three to eighteen bytes. Stops at `size` bytes or the input's end.
fn lzss(src: &[u8], size: usize) -> Vec<u8> {
const N: usize = 4096;
const F: usize = 18;
const THRESHOLD: usize = 2;
let mut ring = [b' '; N];
let mut r = N - F;
let mut out = Vec::with_capacity(size);
let mut flags = 0u32;
let mut i = 0;
while out.len() < size {
flags >>= 1;
if flags & 0x100 == 0 {
let Some(&f) = src.get(i) else { break };
i += 1;
flags = u32::from(f) | 0xff00;
}
if flags & 1 != 0 {
let Some(&c) = src.get(i) else { break };
i += 1;
out.push(c);
ring[r] = c;
r = (r + 1) % N;
} else {
let (Some(&a), Some(&b)) = (src.get(i), src.get(i + 1)) else {
break;
};
i += 2;
let pos = usize::from(a) | (usize::from(b & 0xf0) << 4);
let len = usize::from(b & 0x0f) + THRESHOLD + 1;
for k in 0..len {
let c = ring[(pos + k) % N];
out.push(c);
ring[r] = c;
r = (r + 1) % N;
}
}
}
out.truncate(size);
out
}
fn adler32(d: &[u8]) -> u32 {
let (mut a, mut b) = (1u32, 0u32);
for chunk in d.chunks(5552) {
for &x in chunk {
a += u32::from(x);
b += a;
}
a %= 65521;
b %= 65521;
}
b << 16 | a
}
/// A kernel collection read as a Mach-O file set: each entry's identifier and where its Mach-O
/// header is.
pub struct FileSet<'a> {
b: &'a [u8],
entries: Vec<(String, usize)>,
}
fn u32_at(b: &[u8], at: usize) -> Result<u32> {
let x = b
.get(at..at + 4)
.context("a Mach-O field past the file's end")?;
Ok(u32::from_le_bytes(x.try_into().unwrap()))
}
fn u64_at(b: &[u8], at: usize) -> Result<u64> {
let x = b
.get(at..at + 8)
.context("a Mach-O field past the file's end")?;
Ok(u64::from_le_bytes(x.try_into().unwrap()))
}
/// A fixed-width, NUL-padded name.
fn name16(b: &[u8], at: usize) -> Result<&[u8]> {
let n = b
.get(at..at + 16)
.context("a Mach-O name past the file's end")?;
Ok(&n[..n.iter().position(|&c| c == 0).unwrap_or(16)])
}
/// The load commands of the Mach-O header at `at`: each command's type and where it starts.
fn load_commands(b: &[u8], at: usize) -> Result<Vec<(u32, usize)>> {
ensure!(
u32_at(b, at)? == MH_MAGIC_64,
"no 64-bit Mach-O header at {at:#x}"
);
let n = u32_at(b, at + 16)? as usize;
let size = u32_at(b, at + 20)? as usize;
let end = at + MACH_HEADER_64 + size;
ensure!(end <= b.len(), "Mach-O load commands past the file's end");
let mut out = Vec::with_capacity(n);
let mut c = at + MACH_HEADER_64;
for _ in 0..n {
let cmd = u32_at(b, c)?;
let len = u32_at(b, c + 4)? as usize;
ensure!(
len >= 8 && c + len <= end,
"a Mach-O load command runs past the commands"
);
out.push((cmd, c));
c += len;
}
Ok(out)
}
impl<'a> FileSet<'a> {
/// Read `b` as a file set.
///
/// # Errors
///
/// `b` is not a 64-bit Mach-O file set, or its commands run past it.
pub fn parse(b: &'a [u8]) -> Result<Self> {
ensure!(
u32_at(b, 0)? == MH_MAGIC_64 && u32_at(b, 12)? == MH_FILESET,
"the kernel cache is not a Mach-O file set"
);
let mut entries = Vec::new();
for (cmd, c) in load_commands(b, 0)? {
if cmd != LC_FILESET_ENTRY {
continue;
}
let fileoff = usize::try_from(u64_at(b, c + 16)?)?;
let id_at = c + u32_at(b, c + 24)? as usize;
let len = u32_at(b, c + 4)? as usize;
let id = b
.get(id_at..c + len)
.context("a file set entry's name past its command")?;
let id = &id[..id.iter().position(|&x| x == 0).unwrap_or(id.len())];
entries.push((String::from_utf8_lossy(id).into_owned(), fileoff));
}
Ok(Self { b, entries })
}
/// The entries' identifiers, in the order the file set lists them.
pub fn ids(&self) -> impl Iterator<Item = &str> {
self.entries.iter().map(|(id, _)| id.as_str())
}
fn header(&self, id: &str) -> Result<usize> {
self.entries
.iter()
.find(|(e, _)| e == id)
.map(|&(_, at)| at)
.with_context(|| format!("the kernel cache holds no {id}"))
}
/// The bytes of each of entry `id`'s segments that the file holds, in its commands' order.
///
/// # Errors
///
/// No entry is `id`, or its header or segments run past the file.
pub fn segments(&self, id: &str) -> Result<Vec<(String, &'a [u8])>> {
let mut out = Vec::new();
for (cmd, c) in load_commands(self.b, self.header(id)?)? {
if cmd != LC_SEGMENT_64 {
continue;
}
let name = String::from_utf8_lossy(name16(self.b, c + 8)?).into_owned();
let off = usize::try_from(u64_at(self.b, c + 40)?)?;
let size = usize::try_from(u64_at(self.b, c + 48)?)?;
let bytes = self
.b
.get(off..off + size)
.with_context(|| format!("{id}'s segment {name} past the file's end"))?;
out.push((name, bytes));
}
Ok(out)
}
/// Section `sect` of segment `seg` of entry `id`.
///
/// # Errors
///
/// No entry is `id`, it has no such section, or the section runs past the file.
pub fn section(&self, id: &str, seg: &str, sect: &str) -> Result<&'a [u8]> {
for (cmd, c) in load_commands(self.b, self.header(id)?)? {
if cmd != LC_SEGMENT_64 || name16(self.b, c + 8)? != seg.as_bytes() {
continue;
}
let n = u32_at(self.b, c + 64)? as usize;
for i in 0..n {
let s = c + SEGMENT_COMMAND_64 + i * SECTION_64;
if name16(self.b, s)? != sect.as_bytes() {
continue;
}
let size = usize::try_from(u64_at(self.b, s + 40)?)?;
let off = u32_at(self.b, s + 48)? as usize;
return self
.b
.get(off..off + size)
.with_context(|| format!("{id}'s {seg},{sect} past the file's end"));
}
}
bail!("{id} has no {seg},{sect}")
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
// An LZSS stream written by hand: three literals, then six bytes from the ring where the
// first literal went (N - F = 4078 = 0xfee).
#[test]
fn lzss_reads_literals_and_ring_references() {
let src = [0x07, b'a', b'b', b'c', 0xee, 0xf3];
assert_eq!(lzss(&src, 9), b"abcabcabc");
// Before anything is written the ring reads as spaces.
assert_eq!(lzss(&[0x00, 0x00, 0x00], 3), b" ");
}
#[test]
fn an_lzss_payload_is_checked_by_its_header() {
let mut p = LZSS_MAGIC.to_vec();
p.extend_from_slice(&adler32(b"abcabcabc").to_be_bytes());
p.extend_from_slice(&9u32.to_be_bytes());
p.extend_from_slice(&6u32.to_be_bytes());
p.resize(LZSS_DATA, 0);
p.extend_from_slice(&[0x07, b'a', b'b', b'c', 0xee, 0xf3]);
assert_eq!(lzss_payload(&p).unwrap(), b"abcabcabc");
p[8] ^= 1;
assert!(lzss_payload(&p).is_err());
}
/// A Mach-O header of `filetype` with `cmds`.
fn macho(filetype: u32, cmds: &[Vec<u8>]) -> Vec<u8> {
let mut b = Vec::new();
b.extend_from_slice(&MH_MAGIC_64.to_le_bytes());
b.extend_from_slice(&0x0100_000cu32.to_le_bytes());
b.extend_from_slice(&0u32.to_le_bytes());
b.extend_from_slice(&filetype.to_le_bytes());
b.extend_from_slice(&(cmds.len() as u32).to_le_bytes());
b.extend_from_slice(&(cmds.iter().map(Vec::len).sum::<usize>() as u32).to_le_bytes());
b.extend_from_slice(&[0; 8]);
for c in cmds {
b.extend_from_slice(c);
}
b
}
fn name(s: &str) -> [u8; 16] {
let mut n = [0u8; 16];
n[..s.len()].copy_from_slice(s.as_bytes());
n
}
/// A segment command of one section, both at file offset `off` for `len` bytes.
fn segment(seg: &str, sect: &str, off: u64, len: u64) -> Vec<u8> {
let mut c = Vec::new();
c.extend_from_slice(&LC_SEGMENT_64.to_le_bytes());
c.extend_from_slice(&((SEGMENT_COMMAND_64 + SECTION_64) as u32).to_le_bytes());
c.extend_from_slice(&name(seg));
c.extend_from_slice(&[0; 16]); // vmaddr, vmsize
c.extend_from_slice(&off.to_le_bytes());
c.extend_from_slice(&len.to_le_bytes());
c.extend_from_slice(&[0; 8]); // maxprot, initprot
c.extend_from_slice(&1u32.to_le_bytes());
c.extend_from_slice(&0u32.to_le_bytes());
c.extend_from_slice(&name(sect));
c.extend_from_slice(&name(seg));
c.extend_from_slice(&[0; 8]); // addr
c.extend_from_slice(&len.to_le_bytes());
c.extend_from_slice(&(off as u32).to_le_bytes());
c.extend_from_slice(&[0; 28]);
c
}
fn entry(id: &str, fileoff: u64) -> Vec<u8> {
let mut c = Vec::new();
let len = (32 + id.len() + 1).div_ceil(8) * 8;
c.extend_from_slice(&LC_FILESET_ENTRY.to_le_bytes());
c.extend_from_slice(&(len as u32).to_le_bytes());
c.extend_from_slice(&0u64.to_le_bytes());
c.extend_from_slice(&fileoff.to_le_bytes());
c.extend_from_slice(&32u32.to_le_bytes());
c.extend_from_slice(&0u32.to_le_bytes());
c.extend_from_slice(id.as_bytes());
c.resize(len, 0);
c
}
/// A file set of `kexts` (identifier, its `__TEXT,__const` bytes), written here: the set's
/// header and entries, then each kext's header and its constants.
pub(crate) fn fileset(kexts: &[(&str, &[u8])]) -> Vec<u8> {
let head_len = macho(
MH_FILESET,
&kexts.iter().map(|(id, _)| entry(id, 0)).collect::<Vec<_>>(),
)
.len();
let kext_head = macho(0xb, &[segment("__TEXT", "__const", 0, 0)]).len();
let mut at = head_len as u64;
let mut entries = Vec::new();
let mut bodies = Vec::new();
for (id, consts) in kexts {
entries.push(entry(id, at));
let data_at = at + kext_head as u64;
let mut k = macho(
0xb,
&[segment("__TEXT", "__const", data_at, consts.len() as u64)],
);
k.extend_from_slice(consts);
at += k.len() as u64;
bodies.push(k);
}
let mut b = macho(MH_FILESET, &entries);
for k in bodies {
b.extend(k);
}
b
}
#[test]
fn a_file_sets_kexts_and_sections_are_found() {
let b = fileset(&[
("com.example.a", b"first kext's constants"),
("com.example.b", b"second"),
]);
let fs = FileSet::parse(&b).unwrap();
assert_eq!(
fs.ids().collect::<Vec<_>>(),
["com.example.a", "com.example.b"]
);
assert_eq!(
fs.section("com.example.b", "__TEXT", "__const").unwrap(),
b"second"
);
assert_eq!(
fs.segments("com.example.a").unwrap(),
[("__TEXT".to_owned(), &b"first kext's constants"[..])]
);
assert!(fs.section("com.example.c", "__TEXT", "__const").is_err());
assert!(fs.section("com.example.a", "__TEXT", "__cstring").is_err());
assert!(FileSet::parse(&b[..40]).is_err());
}
}
+112
View File
@@ -0,0 +1,112 @@
//! reims-restore: restores macOS from an IPSW onto an arm64 VM's disk, as Apple's restore would,
//! without Apple's tools or code (docs/design.md). It reads the IPSW where it lies, decrypts and
//! decompresses its images as it copies them, asks Apple's TSS for the VM's tickets, and writes
//! the disk, its auxiliary storage and the VM's ECID itself, on any host.
pub mod aea;
pub mod anchors;
pub mod aux;
pub mod catalog;
pub mod containers;
pub mod download;
pub mod gpt;
pub mod http;
pub mod image;
pub mod img4;
pub mod ipsw;
pub mod kernelcache;
pub mod manifest;
pub mod mtree;
pub mod pipeline;
pub mod plan;
pub mod policy;
pub mod source;
pub mod tss;
pub mod udif;
pub mod xml_plist;
/// The User-Agent of every request the tool makes (Apple's TSS, key service and CDN): the one
/// community restore tools send to these endpoints, fixed, naming nothing of the host, its user
/// or this project.
pub const USER_AGENT: &str = "InetURL/1.0";
/// The headers each of the tool's HTTP clients sends, read off a local listener.
#[cfg(test)]
mod test_server;
#[cfg(test)]
pub(crate) mod sent_headers {
use std::io::{Read as _, Write as _};
use std::net::TcpListener;
/// The header lines of the one request `send` makes to the URL it is given: lowercased
/// names, in the order sent.
pub fn of(send: impl FnOnce(&str)) -> Vec<(String, String)> {
let l = TcpListener::bind("127.0.0.1:0").unwrap();
let url = format!("http://{}/k", l.local_addr().unwrap());
let t = std::thread::spawn(move || {
let (mut s, _) = l.accept().unwrap();
let mut req = Vec::new();
let mut b = [0u8; 4096];
let end = loop {
if let Some(i) = req.windows(4).position(|w| w == b"\r\n\r\n") {
break i + 4;
}
let n = s.read(&mut b).unwrap();
assert!(n > 0, "the request ended before its headers did");
req.extend_from_slice(&b[..n]);
};
let head = String::from_utf8(req[..end].to_vec()).unwrap();
let body = head
.lines()
.filter_map(|l| l.split_once(':'))
.find(|(k, _)| k.eq_ignore_ascii_case("content-length"))
.map_or(0, |(_, v)| v.trim().parse::<usize>().unwrap());
// read the body before answering, so closing resets nothing the client still sends
let mut have = req.len() - end;
while have < body {
let n = s.read(&mut b).unwrap();
assert!(n > 0, "the request ended before its body did");
have += n;
}
s.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
.unwrap();
head
});
send(&url);
let head = t.join().unwrap();
head.split("\r\n")
.skip(1)
.take_while(|l| !l.is_empty())
.map(|l| {
let (k, v) = l.split_once(':').unwrap();
(k.trim().to_ascii_lowercase(), v.trim().to_owned())
})
.collect()
}
/// Checks that `h` holds the fixed User-Agent and no header beyond the host, the User-Agent,
/// ureq's accept headers and `extra`.
pub fn assert_pinned(h: &[(String, String)], extra: &[&str]) {
let ua = h
.iter()
.find(|(k, _)| k == "user-agent")
.map(|(_, v)| v.as_str());
assert_eq!(ua, Some(crate::USER_AGENT));
for (k, v) in h {
assert!(
["host", "user-agent", "accept", "accept-encoding"].contains(&k.as_str())
|| extra.contains(&k.as_str()),
"unexpected header {k}: {v}"
);
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn the_user_agent_is_the_fixed_one() {
assert_eq!(crate::USER_AGENT, "InetURL/1.0");
}
}
+364
View File
@@ -0,0 +1,364 @@
//! reims-restore: restores macOS from an IPSW onto an arm64 VM's disk (docs/design.md).
use std::fs::File;
use std::io::Write as _;
use std::path::PathBuf;
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use reims_restore::aea::AppleKeyService;
use reims_restore::http::Client;
use reims_restore::image;
use reims_restore::ipsw::Ipsw;
use reims_restore::manifest::{self, BuildManifest};
use reims_restore::source::ReadAt;
use reims_restore::{catalog, download};
#[derive(Parser)]
#[command(
version,
about = "Restore macOS from an IPSW onto an arm64 VM's disk, without Apple's tools"
)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
/// Show an IPSW's build, its virtual Mac identities and how its images are stored.
Inspect {
/// The IPSW.
ipsw: PathBuf,
},
/// Write one of an IPSW's images out as a raw, sparse file: decrypted, unpacked, and with
/// `--apfs` only its APFS container.
Extract {
/// The IPSW.
ipsw: PathBuf,
/// The build identity's component, such as `OS` or `Cryptex1,SystemOS`.
component: String,
/// Where to write it; must not exist.
out: PathBuf,
/// Write only the image's APFS container.
#[arg(long)]
apfs: bool,
},
/// Restore an IPSW into a new VM directory: disk.img, aux.img, aux.img.trimmed and
/// machine-identifier.bin, for QEMU's vmapple machine on Ambrosia.
Restore {
/// The IPSW: a UniversalMac IPSW of macOS 14 or later.
ipsw: PathBuf,
/// The VM's directory, made if missing; it must not hold a restore's files.
dir: PathBuf,
/// The disk's size in GiB.
#[arg(long, default_value_t = 64)]
disk_gib: u64,
/// The VM's ECID, in hex; random by default.
#[arg(long, value_parser = parse_hex)]
ecid: Option<u64>,
/// The directory of the project's LocalPolicy keys (root.key, int.key, leaf.key): swap
/// the guest's trust anchors for the project's chain and write config.cpio, Ambrosia's
/// bundle of the patches.
#[arg(long)]
lp_keys: Option<PathBuf>,
},
/// After a macOS 14 VM's first boot: macOS 14 makes its Data volume at that boot and resets
/// the VM, which then doesn't start; this makes it bootable again, for Setup Assistant.
FinishEacs {
/// The VM's directory.
dir: PathBuf,
},
/// Download the IPSW of the current macOS from Apple, or find it downloaded, and print its
/// path. Apple offers only the current release: another is restored from an IPSW you have.
/// A download that stops is continued by the next.
Download {
/// latest, or the current release's version (27.2.1) or build (26B131); also any
/// release of an IPSW already in the directory.
version: String,
/// The directory IPSWs are kept in (default: ipsw in the cache).
#[arg(long)]
cache: Option<PathBuf>,
},
/// List the IPSW Apple offers to download, and the IPSWs downloaded.
List {
/// The directory IPSWs are kept in (default: ipsw in the cache).
#[arg(long)]
cache: Option<PathBuf>,
},
}
fn main() -> Result<()> {
match Cli::parse().command {
Command::Inspect { ipsw } => inspect(&ipsw),
Command::Extract {
ipsw,
component,
out,
apfs,
} => extract(&ipsw, &component, &out, apfs),
Command::Restore {
ipsw,
dir,
disk_gib,
ecid,
lp_keys,
} => restore(ipsw, dir, disk_gib, ecid, lp_keys),
Command::FinishEacs { dir } => {
reims_restore::pipeline::finish_eacs(&dir)?;
println!(
"{} is ready for its next boot, to Setup Assistant",
dir.display()
);
Ok(())
}
Command::Download { version, cache } => download(&version, cache),
Command::List { cache } => list(cache),
}
}
fn parse_hex(s: &str) -> Result<u64, String> {
u64::from_str_radix(s.trim_start_matches("0x"), 16).map_err(|e| e.to_string())
}
fn restore(
ipsw: PathBuf,
dir: PathBuf,
disk_gib: u64,
ecid: Option<u64>,
lp_keys: Option<PathBuf>,
) -> Result<()> {
use reims_restore::pipeline::{self, Event};
let disk_size = disk_gib
.checked_mul(1 << 30)
.with_context(|| format!("a disk of {disk_gib} GiB is too large"))?;
std::fs::create_dir_all(&dir).with_context(|| format!("make {}", dir.display()))?;
let job = pipeline::Restore {
ipsw,
dir,
disk_size,
ecid,
lp_keys,
};
on_interrupt_cancel();
let mut last = (String::new(), u64::MAX);
let done = pipeline::run(
&job,
&mut |e| match e {
Event::Step(s) => eprintln!("{s}"),
Event::Note(s) => eprintln!(" {s}"),
Event::Progress { what, done, total } => {
let pct = (done * 100).checked_div(total).unwrap_or(0);
if last.0 != what || last.1 / 10 != pct / 10 {
eprintln!(" {what}: {pct}%");
last = (what, pct);
}
}
},
&CANCEL,
)?;
println!(
"Restored macOS {} ({}) into {}, ECID {:#x}",
done.version,
done.build,
job.dir.display(),
done.ecid
);
if done.first_boot == pipeline::FirstBoot::Eacs {
println!(
"macOS {} makes its Data volume at the VM's first boot, then resets the VM, which \
then doesn't start. Once it has, run `reims-restore finish-eacs {}`; the next boot \
goes to Setup Assistant.",
done.version,
job.dir.display()
);
}
Ok(())
}
/// The cache's default: `$XDG_CACHE_HOME/reims-restore`, else `~/.cache/reims-restore`.
fn default_cache() -> Result<PathBuf> {
if let Some(x) = std::env::var_os("XDG_CACHE_HOME").filter(|x| !x.is_empty()) {
return Ok(PathBuf::from(x).join("reims-restore"));
}
let home = std::env::var_os("HOME").context("HOME is not set: pass --cache")?;
Ok(PathBuf::from(home).join(".cache/reims-restore"))
}
/// The directory IPSWs are kept in: `cache`, else the cache's `ipsw`.
fn ipsw_dir(cache: Option<PathBuf>) -> Result<PathBuf> {
match cache {
Some(c) => Ok(c),
None => Ok(default_cache()?.join("ipsw")),
}
}
/// Apple's catalog's entries for the virtual Mac, or why it couldn't be read.
fn catalog() -> (Vec<catalog::Entry>, Option<anyhow::Error>) {
match catalog::fetch(&Client::apple(), catalog::URL) {
Ok(e) => (e, None),
Err(e) => (Vec::new(), Some(e)),
}
}
fn download(version: &str, cache: Option<PathBuf>) -> Result<()> {
use reims_restore::pipeline::Event;
let dir = ipsw_dir(cache)?;
let (listed, unread) = catalog();
let found = catalog::pick(
version,
&catalog::on_disk(std::slice::from_ref(&dir)),
&listed,
);
let found = match (found, unread) {
(Ok(f), _) => f,
(Err(e), Some(why)) => return Err(e.context(format!("{why:#}"))),
(Err(e), None) => return Err(e),
};
let path = match found {
catalog::Found::OnDisk(o) => o.path,
catalog::Found::Download(e) => {
on_interrupt_cancel();
let mut last = u64::MAX;
download::download(
&Client::apple(),
&e,
&dir,
&mut |ev| match ev {
Event::Step(s) => eprintln!("{s}"),
Event::Note(s) => eprintln!(" {s}"),
Event::Progress { done, total, .. } => {
let pct = (done * 100).checked_div(total).unwrap_or(0);
if pct != last {
eprint!("\r {pct}% of {:.1} GB", total as f64 / 1e9);
last = pct;
}
if done == total {
eprintln!();
}
}
},
&CANCEL,
)?
}
};
println!("{}", path.display());
Ok(())
}
fn list(cache: Option<PathBuf>) -> Result<()> {
let dir = ipsw_dir(cache)?;
let (listed, unread) = catalog();
match unread {
Some(why) => println!("Apple's catalog couldn't be read: {why:#}"),
None => {
for e in &listed {
println!("Apple offers macOS {} ({}): {}", e.version, e.build, e.url);
}
}
}
let have = catalog::on_disk(std::slice::from_ref(&dir));
if have.is_empty() {
println!("No IPSW downloaded in {}", dir.display());
} else {
println!("Downloaded, in {}:", dir.display());
for o in have {
println!(
" macOS {} ({}) {:.1} GB {}",
o.version,
o.build,
o.size as f64 / 1e9,
o.path.file_name().unwrap_or_default().to_string_lossy()
);
}
}
Ok(())
}
/// Set by SIGINT or SIGTERM: a restore stops and its files are removed; a download stops and
/// keeps its part for the next to continue.
static CANCEL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// The first SIGINT or SIGTERM cancels the restore; a second ends the process at once.
fn on_interrupt_cancel() {
extern "C" fn handle(_: libc::c_int) {
if CANCEL.swap(true, std::sync::atomic::Ordering::SeqCst) {
// SAFETY: _exit is async-signal-safe.
unsafe { libc::_exit(130) };
}
}
for sig in [libc::SIGINT, libc::SIGTERM] {
// SAFETY: the handler only touches an atomic and calls _exit, both async-signal-safe.
unsafe { libc::signal(sig, handle as *const () as libc::sighandler_t) };
}
}
fn inspect(path: &std::path::Path) -> Result<()> {
let ipsw = Ipsw::open(path)?;
let bm = BuildManifest::parse(&ipsw.read("BuildManifest.plist")?)?;
println!("macOS {} ({})", bm.product_version()?, bm.build_version()?);
for variant in [manifest::VARIANT_INSTALL, manifest::VARIANT_ERASE] {
let id = bm.vma2_identity(variant)?;
println!("{variant}:");
let mut comps: Vec<_> = id.components().collect();
comps.sort_by_key(|(n, _)| *n);
for (name, c) in comps {
let Some(p) = c.path() else { continue };
let how = match ipsw.member(p) {
Ok(m) => format!("{} bytes, {:?}", m.size, m.method),
Err(_) => "missing".into(),
};
println!(" {name:40} {p} ({how})");
}
}
Ok(())
}
fn extract(
path: &std::path::Path,
component: &str,
out: &std::path::Path,
apfs: bool,
) -> Result<()> {
let ipsw = Ipsw::open(path)?;
let bm = BuildManifest::parse(&ipsw.read("BuildManifest.plist")?)?;
let id = bm.vma2_identity(manifest::VARIANT_INSTALL)?;
let member = id
.component(component)?
.path()
.context("the component has no path")?
.to_owned();
let keys = AppleKeyService::default();
let (src, layers) = if apfs {
image::open_apfs(&ipsw, &member, &keys)?
} else {
image::open_disk(&ipsw, &member, &keys)?
};
eprintln!("{member}: {layers:?}, {} bytes", src.len());
let mut f = File::options()
.write(true)
.create_new(true)
.open(out)
.with_context(|| format!("create {}", out.display()))?;
f.set_len(src.len())?;
let mut buf = vec![0u8; 8 << 20];
let mut off = 0u64;
let mut next = 0u64;
while off < src.len() {
let n = buf.len().min((src.len() - off) as usize);
src.read_exact_at(off, &mut buf[..n])?;
if buf[..n].iter().any(|&b| b != 0) {
use std::os::unix::fs::FileExt as _;
f.write_all_at(&buf[..n], off)?;
}
off += n as u64;
if off >= next {
eprintln!("{} MiB", off >> 20);
next += 1 << 30;
}
}
f.flush()?;
f.sync_all()?;
Ok(())
}
+279
View File
@@ -0,0 +1,279 @@
//! BuildManifest.plist: the IPSW's build identities, and the one for Apple's virtual Mac.
use anyhow::{Context, Result, bail};
use plist::{Dictionary, Value};
/// The `DeviceClass` of the virtual Mac's identities (`VirtualMac2,1`, board 0x20, chip 0xFE00).
pub const DEVICE_CLASS: &str = "vma2macosap";
/// The variant macOS's own restore installs from: its components are what the boot manifest
/// covers.
pub const VARIANT_INSTALL: &str = "macOS Customer";
/// The erase install's variant, whose components the SFR manifest covers: the installed ones and
/// those of the restore OS and firmware stages.
pub const VARIANT_ERASE: &str = "Customer Erase Install (IPSW)";
/// A parsed BuildManifest.plist.
pub struct BuildManifest {
dict: Dictionary,
}
impl BuildManifest {
/// Parses a BuildManifest.plist.
pub fn parse(bytes: &[u8]) -> Result<Self> {
let v =
Value::from_reader(std::io::Cursor::new(bytes)).context("parse BuildManifest.plist")?;
let dict = v
.into_dictionary()
.context("BuildManifest.plist is not a dictionary")?;
if !matches!(dict.get("BuildIdentities"), Some(Value::Array(_))) {
bail!("BuildManifest.plist has no BuildIdentities");
}
Ok(Self { dict })
}
/// `ProductVersion`, such as `27.2.1`.
pub fn product_version(&self) -> Result<&str> {
self.dict
.get("ProductVersion")
.and_then(Value::as_string)
.context("BuildManifest.plist has no ProductVersion")
}
/// A top-level value, such as `ManifestVersion`.
pub fn get(&self, key: &str) -> Option<&Value> {
self.dict.get(key)
}
/// `ProductBuildVersion`, such as `26B131`.
pub fn build_version(&self) -> Result<&str> {
self.dict
.get("ProductBuildVersion")
.and_then(Value::as_string)
.context("BuildManifest.plist has no ProductBuildVersion")
}
/// Every build identity.
pub fn identities(&self) -> impl Iterator<Item = Identity<'_>> {
self.dict
.get("BuildIdentities")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_dictionary)
.map(|dict| Identity { dict })
}
/// The virtual Mac's identity of `variant`; fails if there is none, or more than one.
pub fn vma2_identity(&self, variant: &str) -> Result<Identity<'_>> {
let mut found = self.identities().filter(|i| {
i.info_str("DeviceClass") == Some(DEVICE_CLASS)
&& i.info_str("Variant") == Some(variant)
});
let first = found.next().with_context(|| {
format!(
"this IPSW has no {DEVICE_CLASS} identity of variant {variant:?}: it is not a restore image for \
Apple's virtual Mac (VirtualMac2,1)"
)
})?;
if found.next().is_some() {
bail!("this IPSW has more than one {DEVICE_CLASS} identity of variant {variant:?}");
}
Ok(first)
}
}
/// One build identity.
#[derive(Clone, Copy)]
pub struct Identity<'a> {
dict: &'a Dictionary,
}
impl<'a> Identity<'a> {
/// The identity's dictionary.
pub fn dict(&self) -> &'a Dictionary {
self.dict
}
/// A string of its `Info`.
pub fn info_str(&self, key: &str) -> Option<&'a str> {
self.dict
.get("Info")?
.as_dictionary()?
.get(key)?
.as_string()
}
/// A value of its `Info`.
pub fn info(&self, key: &str) -> Option<&'a Value> {
self.dict.get("Info")?.as_dictionary()?.get(key)
}
/// A top-level integer given as a hex string or an integer, such as `ApChipID` (`0xFE00`).
pub fn int(&self, key: &str) -> Result<u64> {
parse_int(
self.dict
.get(key)
.with_context(|| format!("the identity has no {key}"))?,
)
.with_context(|| format!("the identity's {key} is not a number"))
}
/// Its components: `Manifest`'s entries.
pub fn components(&self) -> impl Iterator<Item = (&'a str, Component<'a>)> {
self.dict
.get("Manifest")
.and_then(Value::as_dictionary)
.into_iter()
.flat_map(|m| m.iter())
.filter_map(|(k, v)| {
Some((
k.as_str(),
Component {
dict: v.as_dictionary()?,
},
))
})
}
/// The component called `name`.
pub fn component(&self, name: &str) -> Result<Component<'a>> {
self.dict
.get("Manifest")
.and_then(Value::as_dictionary)
.and_then(|m| m.get(name))
.and_then(Value::as_dictionary)
.map(|dict| Component { dict })
.with_context(|| format!("the build identity has no {name}"))
}
}
/// One component of a build identity.
#[derive(Clone, Copy)]
pub struct Component<'a> {
dict: &'a Dictionary,
}
impl<'a> Component<'a> {
/// The component's dictionary.
pub fn dict(&self) -> &'a Dictionary {
self.dict
}
/// Its path in the IPSW.
pub fn path(&self) -> Option<&'a str> {
self.info()?.get("Path")?.as_string()
}
/// Its `Info`.
pub fn info(&self) -> Option<&'a Dictionary> {
self.dict.get("Info")?.as_dictionary()
}
/// A boolean of its `Info`, false where absent.
pub fn info_bool(&self, key: &str) -> bool {
self.info()
.and_then(|i| i.get(key))
.and_then(Value::as_boolean)
.unwrap_or(false)
}
/// Its digest.
pub fn digest(&self) -> Option<&'a [u8]> {
self.dict.get("Digest")?.as_data()
}
/// Whether it is `Trusted`.
pub fn trusted(&self) -> bool {
self.dict
.get("Trusted")
.and_then(Value::as_boolean)
.unwrap_or(false)
}
}
/// An integer as a manifest gives one: an integer, or a string in hex (`0x…`) or decimal.
pub fn parse_int(v: &Value) -> Option<u64> {
match v {
Value::Integer(i) => i.as_unsigned(),
Value::String(s) => {
let s = s.trim();
match s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
Some(h) => u64::from_str_radix(h, 16).ok(),
None => s.parse().ok(),
}
}
_ => None,
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
/// A BuildManifest with the three identities of a virtual Mac, written from scratch.
pub fn synthetic() -> Vec<u8> {
let comp = |path: &str, digest: u8| {
let mut info = Dictionary::new();
info.insert("Path".into(), Value::String(path.into()));
info.insert("Personalize".into(), Value::Boolean(true));
let mut d = Dictionary::new();
d.insert("Digest".into(), Value::Data(vec![digest; 48]));
d.insert("Trusted".into(), Value::Boolean(true));
d.insert("Info".into(), Value::Dictionary(info));
Value::Dictionary(d)
};
let ident = |variant: &str, behavior: &str| {
let mut info = Dictionary::new();
info.insert("DeviceClass".into(), Value::String(DEVICE_CLASS.into()));
info.insert("Variant".into(), Value::String(variant.into()));
info.insert("RestoreBehavior".into(), Value::String(behavior.into()));
let mut m = Dictionary::new();
m.insert("KernelCache".into(), comp("kernelcache.test", 1));
m.insert("DeviceTree".into(), comp("Firmware/dt.im4p", 2));
let mut d = Dictionary::new();
d.insert("ApChipID".into(), Value::String("0xFE00".into()));
d.insert("ApBoardID".into(), Value::String("0x20".into()));
d.insert("ApSecurityDomain".into(), Value::String("0x01".into()));
d.insert("Info".into(), Value::Dictionary(info));
d.insert("Manifest".into(), Value::Dictionary(m));
Value::Dictionary(d)
};
let mut root = Dictionary::new();
root.insert("ProductVersion".into(), Value::String("99.1".into()));
root.insert("ProductBuildVersion".into(), Value::String("99A1".into()));
root.insert(
"BuildIdentities".into(),
Value::Array(vec![
ident(VARIANT_ERASE, "Erase"),
ident("Customer Upgrade Install (IPSW)", "Update"),
ident(VARIANT_INSTALL, "Erase"),
]),
);
let mut out = Vec::new();
Value::Dictionary(root).to_writer_xml(&mut out).unwrap();
out
}
#[test]
fn picks_the_virtual_macs_identities() {
let bm = BuildManifest::parse(&synthetic()).unwrap();
assert_eq!(bm.product_version().unwrap(), "99.1");
let id = bm.vma2_identity(VARIANT_INSTALL).unwrap();
assert_eq!(id.int("ApChipID").unwrap(), 0xfe00);
assert_eq!(id.int("ApBoardID").unwrap(), 0x20);
assert_eq!(
id.component("KernelCache").unwrap().path(),
Some("kernelcache.test")
);
assert!(bm.vma2_identity(VARIANT_ERASE).is_ok());
assert!(bm.vma2_identity("Nope").is_err());
}
#[test]
fn integers_parse_as_manifests_give_them() {
assert_eq!(parse_int(&Value::String("0x01".into())), Some(1));
assert_eq!(parse_int(&Value::String("32".into())), Some(32));
assert_eq!(parse_int(&Value::Integer(7.into())), Some(7));
assert_eq!(parse_int(&Value::Boolean(true)), None);
}
}
+389
View File
@@ -0,0 +1,389 @@
//! The system volume's canonical metadata (`Ap,SystemVolumeCanonicalMetadata`, IM4P `msys`): an
//! mtree of the sealed volume. A seal sets every inode's four times and every directory entry's
//! date added to one instant, its root directory's `time=` (docs/design.md, "The system volume's
//! seal"); this reads that instant.
//!
//! The payload is `pbze`: a big-endian block size, then blocks, each its decoded and stored sizes
//! (big-endian) and its bytes, an LZFSE stream where it is stored smaller than it decodes and the
//! bytes themselves where not **[measured]**. Decoded, it is an Apple Archive (`AA01`) of three
//! entries on 27.2.1, a directory, `digest.db` (135 MB) and `mtree.txt` (90 MB) **[ipsw]**; the
//! mtree's text has its root directory's entry first: `. type=dir time=<seconds>.<nanoseconds>`.
//! An archive entry is `AA01`, its header's size (16-bit little-endian, the magic included), and
//! fields each a three-letter key, a type letter and a value, its blobs following the header in
//! the order their fields name them.
use anyhow::{Context, Result, bail, ensure};
use crate::img4;
/// The archive entry holding the mtree's text.
const MTREE: &str = "mtree.txt";
/// The most of the mtree's text read looking for the root's entry: it comes first.
const SEARCHED: usize = 1 << 20;
/// The root directory's `time=` of the mtree IM4P `im4p`, in nanoseconds since 1970.
///
/// # Errors
///
/// The IM4P is not `msys`, its payload is not `pbze` or fails to decode, its archive holds no
/// `mtree.txt`, or no root entry with a time is found in that text's first MiB.
pub fn root_time(im4p: &[u8]) -> Result<u64> {
let p = img4::parse_im4p(im4p).context("read the canonical metadata's IM4P")?;
ensure!(
&p.tag == b"msys",
"the canonical metadata is IM4P {}, not msys",
String::from_utf8_lossy(&p.tag)
);
let mut z = Pbze::new(&p.payload)?;
let text = archive_member(&mut z, MTREE, SEARCHED)?;
find_root_time(&text).context("find the mtree root's time")
}
/// A `pbze` payload read front to back, skipping whole blocks without decoding them.
struct Pbze<'a> {
b: &'a [u8],
/// The next block's header.
at: usize,
block: Vec<u8>,
pos: usize,
}
impl<'a> Pbze<'a> {
fn new(b: &'a [u8]) -> Result<Self> {
ensure!(b.len() >= 12 && &b[..4] == b"pbze", "not a pbze payload");
Ok(Self {
b,
at: 12,
block: Vec::new(),
pos: 0,
})
}
/// The next block's decoded and stored sizes, or `None` at the end.
fn next_sizes(&self) -> Result<Option<(usize, usize)>> {
if self.at >= self.b.len() {
return Ok(None);
}
let h = self
.b
.get(self.at..self.at + 16)
.context("a pbze block header runs past the payload")?;
let size = u64::from_be_bytes(h[..8].try_into().unwrap()) as usize;
let stored = u64::from_be_bytes(h[8..].try_into().unwrap()) as usize;
ensure!(
self.at + 16 + stored <= self.b.len(),
"a pbze block runs past the payload"
);
Ok(Some((size, stored)))
}
/// Decode the next block into `block`.
fn decode_next(&mut self) -> Result<()> {
let (size, stored) = self.next_sizes()?.context("the pbze payload ends early")?;
let data = &self.b[self.at + 16..self.at + 16 + stored];
self.at += 16 + stored;
self.block.clear();
self.pos = 0;
if stored < size {
lzfse_rust::decode_bytes(data, &mut self.block)
.map_err(|e| anyhow::anyhow!("a pbze block's LZFSE: {e}"))?;
ensure!(
self.block.len() == size,
"a pbze block decodes to {} of {size} bytes",
self.block.len()
);
} else {
self.block.extend_from_slice(data);
}
Ok(())
}
/// Pass over `n` bytes, decoding only the block they end in.
fn skip(&mut self, mut n: u64) -> Result<()> {
let here = (self.block.len() - self.pos) as u64;
if n <= here {
self.pos += n as usize;
return Ok(());
}
n -= here;
self.pos = self.block.len();
while let Some((size, stored)) = self.next_sizes()? {
if n < size as u64 {
self.decode_next()?;
self.pos = n as usize;
return Ok(());
}
n -= size as u64;
self.at += 16 + stored;
}
ensure!(n == 0, "the pbze payload ends early");
Ok(())
}
fn read_exact(&mut self, out: &mut [u8]) -> Result<()> {
let mut done = 0;
while done < out.len() {
if self.pos == self.block.len() {
self.decode_next()?;
}
let n = (out.len() - done).min(self.block.len() - self.pos);
out[done..done + n].copy_from_slice(&self.block[self.pos..self.pos + n]);
self.pos += n;
done += n;
}
Ok(())
}
}
/// The first `limit` bytes (or all) of the data of archive member `name`.
fn archive_member(z: &mut Pbze, name: &str, limit: usize) -> Result<Vec<u8>> {
loop {
let mut head = [0u8; 6];
z.read_exact(&mut head)
.with_context(|| format!("the archive holds no {name}"))?;
ensure!(
&head[..4] == b"AA01",
"not an Apple Archive entry: {:02x?}",
&head[..4]
);
let size = usize::from(u16::from_le_bytes([head[4], head[5]]));
ensure!(size >= 6, "an archive header of {size} bytes");
let mut h = vec![0u8; size - 6];
z.read_exact(&mut h)?;
let (path, blobs) = parse_header(&h)?;
for (key, len) in blobs {
if path == name && key == *b"DAT" {
let n = usize::try_from(len).unwrap_or(usize::MAX).min(limit);
let mut out = vec![0u8; n];
z.read_exact(&mut out)?;
return Ok(out);
}
z.skip(len)?;
}
}
}
/// An archive entry's blobs: each one's key and size, in order.
type Blobs = Vec<([u8; 3], u64)>;
/// An archive header's path and its blobs' keys and sizes, in order.
fn parse_header(h: &[u8]) -> Result<(String, Blobs)> {
let mut path = String::new();
let mut blobs = Vec::new();
let mut i = 0;
while i < h.len() {
let f = h
.get(i..i + 4)
.context("an archive field runs past its header")?;
let key = [f[0], f[1], f[2]];
let ty = f[3];
i += 4;
let width = match ty {
b'*' => 0,
b'1' | b'2' | b'4' | b'8' => usize::from(ty - b'0'),
b'A' => 2,
b'B' => 4,
b'C' => 8,
b'P' => {
let l = h
.get(i..i + 2)
.context("an archive path runs past its header")?;
2 + usize::from(u16::from_le_bytes([l[0], l[1]]))
}
b'S' => 8,
b'T' => 12,
b'F' => 4,
b'G' => 20,
b'H' => 32,
b'I' => 48,
b'J' => 64,
_ => bail!(
"an archive field {}{} of a type this reader doesn't know",
String::from_utf8_lossy(&key),
ty as char
),
};
let v = h
.get(i..i + width)
.context("an archive field runs past its header")?;
match ty {
b'P' if key == *b"PAT" => path = String::from_utf8_lossy(&v[2..]).into_owned(),
b'A'..=b'C' => {
let mut n = [0u8; 8];
n[..width].copy_from_slice(v);
blobs.push((key, u64::from_le_bytes(n)));
}
_ => {}
}
i += width;
}
Ok((path, blobs))
}
/// The `time=` of the first entry naming `.` as a directory, the mtree's root.
fn find_root_time(text: &[u8]) -> Result<u64> {
// An entry runs over lines joined by a trailing backslash; the root's starts with `.` and
// white space at the start of a line.
let mut entry = String::new();
for line in text.split(|&c| c == b'\n') {
let line = String::from_utf8_lossy(line);
let starts = entry.is_empty();
if starts && !(line.starts_with(". ") || line.starts_with(".\t")) {
continue;
}
entry.push_str(line.trim_end_matches('\\'));
entry.push(' ');
if line.ends_with('\\') {
continue;
}
let words: Vec<&str> = entry.split_whitespace().collect();
if words.contains(&"type=dir")
&& let Some(t) = words.iter().find_map(|w| w.strip_prefix("time="))
{
return parse_time(t);
}
entry.clear();
}
bail!("no root directory entry with a time")
}
/// `<seconds>.<nanoseconds>` in nanoseconds.
fn parse_time(t: &str) -> Result<u64> {
let (s, ns) = t.split_once('.').unwrap_or((t, "0"));
ensure!(ns.len() <= 9, "time {t} has more than nanoseconds");
let s: u64 = s.parse().with_context(|| format!("time {t}"))?;
let ns: u64 = format!("{ns:0<9}")
.parse()
.with_context(|| format!("time {t}"))?;
s.checked_mul(1_000_000_000)
.and_then(|x| x.checked_add(ns))
.with_context(|| format!("time {t} out of range"))
}
#[cfg(test)]
mod tests {
use super::*;
/// A pbze payload of `text`, cut in `block`-byte blocks, each LZFSE where that is smaller.
fn pbze(text: &[u8], block: usize) -> Vec<u8> {
let mut out = b"pbze".to_vec();
out.extend_from_slice(&(block as u64).to_be_bytes());
for chunk in text.chunks(block) {
let mut z = Vec::new();
lzfse_rust::encode_bytes(chunk, &mut z).unwrap();
let stored: &[u8] = if z.len() < chunk.len() { &z } else { chunk };
out.extend_from_slice(&(chunk.len() as u64).to_be_bytes());
out.extend_from_slice(&(stored.len() as u64).to_be_bytes());
out.extend_from_slice(stored);
}
out
}
/// An archive entry: a header of `fields` (key and type letter, value), then `blobs`.
fn entry(fields: &[(&str, Vec<u8>)], blobs: &[&[u8]]) -> Vec<u8> {
let mut h = Vec::new();
for (k, v) in fields {
h.extend_from_slice(k.as_bytes());
h.extend_from_slice(v);
}
let mut out = b"AA01".to_vec();
out.extend_from_slice(&((6 + h.len()) as u16).to_le_bytes());
out.extend_from_slice(&h);
for b in blobs {
out.extend_from_slice(b);
}
out
}
fn path(p: &str) -> Vec<u8> {
let mut v = (p.len() as u16).to_le_bytes().to_vec();
v.extend_from_slice(p.as_bytes());
v
}
// An mtree of the form the canonical metadata holds, written here: a header, a `/set`, then
// the root's entry over continued lines, then others with times of their own.
fn mtree() -> Vec<u8> {
let mut t = b"#\t user: root\n\n# .\n/set type=file\n".to_vec();
t.extend_from_slice(
b". type=dir time=1700000123.450000000 \\\n btime=1 ctime=1 inode=2 nxattr=0\n",
);
t.extend_from_slice(b" a type=dir time=99.000000000 inode=16\n");
for i in 0..5000 {
t.extend_from_slice(format!(" f{i} time=5.0 inode={}\n", 17 + i).as_bytes());
}
t
}
// An archive as the canonical metadata's: a directory, a large database the reader passes
// over, then the mtree, with fields of several types around the path and the blob.
fn archive() -> Vec<u8> {
let ts = vec![0u8; 12];
let db: Vec<u8> = (0..300_000u32).map(|i| (i * 7 + i / 251) as u8).collect();
let text = mtree();
let mut a = entry(
&[
("TYP1", b"D".to_vec()),
("PATP", path("")),
("MOD2", vec![0xed, 1]),
("CTMT", ts.clone()),
],
&[],
);
a.extend(entry(
&[
("TYP1", b"F".to_vec()),
("PATP", path("digest.db")),
("UID1", vec![0]),
("MTMT", ts.clone()),
("XATA", (5u16).to_le_bytes().to_vec()),
("DATB", (db.len() as u32).to_le_bytes().to_vec()),
],
&[b"xattr", &db],
));
a.extend(entry(
&[
("TYP1", b"F".to_vec()),
("PATP", path("mtree.txt")),
("SH2H", vec![0xab; 32]),
("DATB", (text.len() as u32).to_le_bytes().to_vec()),
],
&[&text],
));
a
}
#[test]
fn the_root_time_is_read_through_every_block_form() {
for block in [64usize, 4096, 1 << 20] {
let b = pbze(&archive(), block);
let mut z = Pbze::new(&b).unwrap();
let text = archive_member(&mut z, MTREE, SEARCHED).unwrap();
assert_eq!(
find_root_time(&text).unwrap(),
1_700_000_123_450_000_000,
"{block}"
);
}
}
#[test]
fn times_parse_to_nanoseconds() {
assert_eq!(
parse_time("1793942531.000000000").unwrap(),
1_793_942_531_000_000_000
);
assert_eq!(parse_time("1.5").unwrap(), 1_500_000_000);
assert_eq!(parse_time("7").unwrap(), 7_000_000_000);
assert!(parse_time("1.0000000001").is_err());
}
#[test]
fn an_mtree_without_a_root_time_is_refused() {
assert!(find_root_time(b". type=dir inode=2\n a time=3.0\n").is_err());
assert!(Pbze::new(b"pbzx\0\0\0\0\0\0\0\0").is_err());
// An archive without the mtree.
let b = pbze(&archive()[..300_100], 4096);
assert!(archive_member(&mut Pbze::new(&b).unwrap(), MTREE, SEARCHED).is_err());
}
}
+981
View File
@@ -0,0 +1,981 @@
//! A whole restore, as reims-ctl and the CLI run it: from an IPSW to a VM's directory holding
//! `disk.img`, `aux.img`, `aux.img.trimmed` and `machine-identifier.bin` (docs/design.md). The
//! restore writes the disk itself, on any host: it reads the IPSW where it lies, has Apple's TSS
//! sign the VM's tickets, and lays out the GPT, the three APFS containers and NVRAM as a fresh
//! restore by Virtualization.framework leaves them. No VM runs, and none of Apple's code.
use std::fs::{File, OpenOptions};
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::SystemTime;
use anyhow::{Context, Result, bail, ensure};
use plist::{Dictionary, Value};
use uuid::Uuid;
use crate::aea::AppleKeyService;
use crate::aux::{self, Nvram};
use crate::gpt::Table;
use crate::ipsw::Ipsw;
use crate::manifest::{BuildManifest, VARIANT_ERASE, VARIANT_INSTALL};
use crate::tss::{self, ApNonces, ApTicket, TssClient};
use crate::{anchors, containers, image, img4, kernelcache, plan, policy};
/// A restore to run.
#[derive(Debug, Clone)]
pub struct Restore {
/// The IPSW, a local file.
pub ipsw: PathBuf,
/// The VM's directory: it exists and holds none of the files a restore writes.
pub dir: PathBuf,
/// The disk's size in bytes.
pub disk_size: u64,
/// The VM's ECID; random when `None`.
pub ecid: Option<u64>,
/// The directory of the project's LocalPolicy keys (`root.key`, `int.key`, `leaf.key`):
/// with them the restore swaps the guest's trust anchors for the project's chain and writes
/// Ambrosia's bundle of the patches, [`CONFIG`] ([`crate::anchors`]); without them it signs
/// with the built-in chain and writes no bundle.
pub lp_keys: Option<PathBuf>,
}
/// What a restore reports as it goes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Event {
/// A step began: a short sentence.
Step(String),
/// Progress through a long step.
Progress {
/// What is progressing.
what: String,
/// How far it is.
done: u64,
/// Where it ends.
total: u64,
},
/// A line for the log.
Note(String),
}
/// A finished restore.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Restored {
/// The VM's ECID.
pub ecid: u64,
/// The macOS version restored, such as `15.6.1`.
pub version: String,
/// Its build, such as `24G90`.
pub build: String,
/// What the VM's first boot does.
pub first_boot: FirstBoot,
}
/// What a restored VM's first boot does.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FirstBoot {
/// It goes to Setup Assistant.
SetupAssistant,
/// macOS 14 ([`data_by_eacs`]): it makes the Data volume by EACS and resets the VM, and then
/// Ambrosia finds no LocalPolicy and stops. [`finish_eacs`] on the VM's directory then makes
/// it bootable, and the next boot goes to Setup Assistant.
Eacs,
}
/// Whether macOS `version`'s first boot makes its Data volume itself, by EACS, with the restore
/// leaving it out: macOS 14. Its kernel refuses an unencrypted Data volume ("unencrypted data
/// volume is not allowed") **[measured]**, and Virtualization.framework's 14.6.1 restore leaves
/// Data encrypted where those of 15.6.1 and later leave it unencrypted **[vz]**; only the guest's
/// keystore can make an encrypted one (docs/design.md, "macOS 14's Data volume").
pub fn data_by_eacs(version: &str) -> bool {
version.split('.').next() == Some("14")
}
/// The files a restore leaves in the VM's directory.
pub const DISK: &str = "disk.img";
/// The auxiliary storage in Virtualization.framework's form, with its 16 KiB header.
pub const AUX: &str = "aux.img";
/// The auxiliary storage as QEMU attaches it.
pub const AUX_TRIMMED: &str = "aux.img.trimmed";
/// The ECID in Virtualization.framework's form, a binary plist `{ECID: n}`.
pub const MACHINE_IDENTIFIER: &str = "machine-identifier.bin";
/// Ambrosia's configuration bundle of the patches that swap the guest's LocalPolicy anchors for
/// the project's, where the restore was given the project's keys.
pub const CONFIG: &str = "config.cpio";
/// For [`FirstBoot::Eacs`], until [`finish_eacs`]: the iBoot system container's partition as the
/// restore wrote it, sparse.
pub const EACS_ISC: &str = "isc.pre-eacs";
/// For [`FirstBoot::Eacs`], until [`finish_eacs`]: the auxiliary storage as the restore wrote it.
pub const EACS_AUX: &str = "aux.pre-eacs";
/// The auxiliary storage's size as QEMU attaches it.
const AUX_SIZE: u64 = aux::SIZE as u64;
/// The smallest disk a restore makes. A restored system takes 25.1 GiB of 27.2.1's 64 GiB disk
/// (Virtualization.framework) **[measured]**; below 32 GiB the system has little room to run in.
pub const MIN_DISK: u64 = 32 << 30;
/// The values a restore draws at random, which bind the VM's tickets and policies to it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Secrets {
/// The VM's ECID.
pub ecid: u64,
/// The AP nonce the boot manifest and the Cryptex1 ticket carry (`BNCH`, `cnch`).
pub nonces: ApNonces,
/// NVRAM's policy nonces and the disk's GUIDs.
pub nvram: Nvram,
}
/// Runs a restore. `events` hears its steps; setting `cancel` stops it between steps. On
/// success the VM's files are in `r.dir`; otherwise none of them is.
pub fn run(r: &Restore, events: &mut dyn FnMut(Event), cancel: &AtomicBool) -> Result<Restored> {
let step = |events: &mut dyn FnMut(Event), s: &str| events(Event::Step(s.to_owned()));
step(events, "Reading the IPSW");
let ipsw = Ipsw::open(&r.ipsw)?;
let bm = BuildManifest::parse(&ipsw.read("BuildManifest.plist")?)
.with_context(|| format!("read {}'s BuildManifest.plist", r.ipsw.display()))?;
let version = bm.product_version()?.to_owned();
let build = bm.build_version()?.to_owned();
let (install, erase) = match (
bm.vma2_identity(VARIANT_INSTALL),
bm.vma2_identity(VARIANT_ERASE),
) {
(Ok(i), Ok(e)) => (i, e),
_ => bail!(
"{} (macOS {version}, {build}) has no virtual Mac build identity: a restore needs a \
UniversalMac IPSW of macOS 14 or later",
r.ipsw.display()
),
};
events(Event::Note(format!("macOS {version} ({build})")));
let eacs = data_by_eacs(&version);
if eacs {
events(Event::Note(
"macOS 14 makes its Data volume at its first boot: the restore leaves it out".into(),
));
}
check_dir(&r.dir)?;
ensure!(
r.disk_size >= MIN_DISK,
"a {} disk is too small for macOS: give it at least {}",
gib(r.disk_size),
gib(MIN_DISK)
);
let table = Table::layout(r.disk_size)?;
let secrets = Secrets::generate(r.ecid, &table)?;
cancelled(cancel)?;
step(events, "Reading the system image's data template");
let keys = AppleKeyService::default();
let os = install
.component("OS")?
.path()
.context("the manifest's OS has no path")?
.to_owned();
let container = image::open_container(&ipsw, &os, &keys)?;
let system = container.system_volume()?;
let mut images = 0;
for m in plan::copied_images(&install)? {
images += ipsw.member(&m)?.size;
}
let need = space_needed(
system.sb.alloc_count * u64::from(container.block_size()),
images,
);
check_space(&r.dir, free_space(&r.dir)?, need)?;
let patterns = system
.read_file(DATA_PATTERNS)
.with_context(|| format!("read {DATA_PATTERNS} from {os}"))?;
let receipt = plan::receipt(
&version,
&build,
&String::from_utf8_lossy(&patterns),
SystemTime::now(),
);
cancelled(cancel)?;
step(events, "Asking Apple to sign the VM's tickets");
let tss = TssClient::new();
let boot_manifest: Arc<[u8]> = tss
.ap_ticket(&install, ApTicket::Boot, secrets.ecid, &secrets.nonces)?
.into();
let sfr_manifest: Arc<[u8]> = tss
.ap_ticket(&erase, ApTicket::Sfr, secrets.ecid, &secrets.nonces)?
.into();
let cryptex1: Arc<[u8]> = tss
.cryptex1_ticket(&install, secrets.ecid, &secrets.nonces.ap_nonce)?
.into();
let ronh = img4::sha384(secrets.nvram.recovery_policy_nonce());
let mut args = Dictionary::new();
args.insert(
"Ap,NextStageIM4MHash".into(),
Value::Data(img4::sha384(&sfr_manifest).to_vec()),
);
args.insert(
"Ap,RecoveryOSPolicyNonceHash".into(),
Value::Data(ronh.to_vec()),
);
args.insert(
"Ap,VolumeUUID".into(),
Value::String(plan::RECOVERY_GROUP.to_string().to_uppercase()),
);
let recovery_os_policy = img4::stitch_img4(
&img4::LPOL_IM4P,
&tss.local_policy_ticket(&erase, &args, secrets.ecid)?,
);
cancelled(cancel)?;
step(events, "Signing the VM's LocalPolicies");
let (signer, bundle) = match &r.lp_keys {
Some(dir) => {
let kernel = install
.component("KernelCache")?
.path()
.context("the manifest's KernelCache has no path")?;
let kc = kernelcache::decompress(&ipsw.read(kernel)?)
.with_context(|| format!("read {kernel}"))?;
let guest = anchors::guest(&kernelcache::FileSet::parse(&kc)?)
.with_context(|| format!("find the LocalPolicy anchors in {kernel}"))?;
drop(kc);
let keys = anchors::Keys::load(dir)?;
let chain = anchors::chain(&guest, &keys)?;
let signer = policy::Signer::with_key(keys.leaf, &[&chain.intermediate, &chain.leaf])?;
let bundle = anchors::config_bundle(&anchors::config(&guest, &chain))?;
(signer, Some(bundle))
}
None => {
events(Event::Note(
"no LocalPolicy keys given: the policies carry the built-in chain, and no \
anchor bundle is written"
.into(),
));
(policy::Signer::project(), None)
}
};
let boot = img4::parse_im4m(&boot_manifest).context("read the boot manifest")?;
let prop = |k: &str| {
boot.props
.get(k)
.with_context(|| format!("the boot manifest has no {k}"))
};
let binding = policy::Binding {
ecid: secrets.ecid,
chip: prop("CHIP")?.as_int().context("CHIP")?,
board: prop("BORD")?.as_int().context("BORD")?,
security_domain: prop("SDOM")?.as_int().context("SDOM")?,
love: prop("love")?.as_data().context("love")?.to_vec(),
boot_manifest_hash: img4::sha384(&boot_manifest),
cryptex1_ticket_hash: img4::sha384(&cryptex1),
local_nonce: *secrets.nvram.local_policy_nonce(),
remote_nonce: *secrets.nvram.remote_policy_nonce(),
group: secrets.nvram.group,
};
let names: Vec<String> = ipsw.names().map(str::to_owned).collect();
let has = |n: &str| ipsw.has(n);
let the_plan = plan::plan(&plan::Inputs {
manifest: &bm,
has: &has,
names: &names,
install,
erase,
ecid: secrets.ecid,
group: secrets.nvram.group,
boot_manifest,
sfr_manifest: sfr_manifest.clone(),
cryptex1_ticket: cryptex1,
policy: (
binding.file_name(policy::Kind::MacOs),
binding.sign(policy::Kind::MacOs, &signer).into(),
),
policy_recovery: (
binding.file_name(policy::Kind::Recovery),
binding.sign(policy::Kind::Recovery, &signer).into(),
),
recovery_os_policy: recovery_os_policy.into(),
ronh: ronh.iter().map(|b| format!("{b:02X}")).collect(),
receipt,
eacs_store: eacs.then_some(table.main().guid),
})?;
cancelled(cancel)?;
let aux = aux::trimmed(&secrets.nvram, &sfr_manifest)?;
step(events, "Making the VM's disks");
let files = Files::new(&r.dir);
if let Err(e) = files.make(r.disk_size) {
files.discard();
return Err(e);
}
let src = containers::Sources {
ipsw: &ipsw,
keys: &keys,
root_hash: None,
t: nanos(SystemTime::now()),
};
let written = write(&files, &table, &aux, &the_plan, src, events, cancel).and_then(|()| {
if eacs {
files.keep_for_eacs(&table)
} else {
Ok(())
}
});
match written.and_then(|()| files.finish(secrets.ecid, bundle.as_deref(), eacs)) {
Ok(()) => Ok(Restored {
ecid: secrets.ecid,
version,
build,
first_boot: if eacs {
FirstBoot::Eacs
} else {
FirstBoot::SetupAssistant
},
}),
Err(e) => {
files.discard();
Err(e)
}
}
}
/// Where the system image keeps the patterns of its data template's paths that the Data volume
/// links to instead of copying.
const DATA_PATTERNS: &str = "/System/Library/Templates/Data.symlink-patterns";
impl Secrets {
/// Draws them, with `ecid` when given, for a disk of `table`.
pub fn generate(ecid: Option<u64>, table: &Table) -> Result<Self> {
let ecid = match ecid {
Some(e) => e,
None => tss::random_ecid()?,
};
let mut policy_nonces = [[0u8; 16]; 7];
for n in &mut policy_nonces {
getrandom::fill(n).map_err(|e| anyhow::anyhow!("no random bytes for a nonce: {e}"))?;
}
Ok(Self {
ecid,
nonces: ApNonces::generate()?,
nvram: Nvram {
policy_nonces,
container: table.main().guid,
group: Uuid::new_v4(),
},
})
}
}
/// Writes the disk's table, its containers as `plan` lays them out (the main container's system
/// volume sealed first, so its boot directories carry the seal's root hash), and the auxiliary
/// storage `aux` into the restore's files.
fn write(
files: &Files,
table: &Table,
aux: &[u8],
plan: &plan::Plan,
mut src: containers::Sources,
events: &mut dyn FnMut(Event),
cancel: &AtomicBool,
) -> Result<()> {
let mut disk = OpenOptions::new()
.write(true)
.open(files.part(DISK))
.context("open the disk")?;
table
.write(&mut disk)
.context("write the disk's partition table")?;
for (what, part, volumes) in [
(
"Sealing the system volume and writing the main container",
table.main(),
&plan.main,
),
("Writing the iBoot system container", table.isc(), &plan.isc),
(
"Writing the recoveryOS container",
table.recovery(),
&plan.recovery,
),
] {
cancelled(cancel)?;
events(Event::Step(what.to_owned()));
containers::write_container(&mut disk, part, volumes, &mut src)?;
}
disk.sync_all().context("flush the disk")?;
let mut trimmed = OpenOptions::new()
.write(true)
.open(files.part(AUX_TRIMMED))
.context("open the auxiliary storage")?;
trimmed
.write_all(aux)
.context("write the auxiliary storage")?;
Ok(())
}
/// `t` in nanoseconds since 1970.
fn nanos(t: SystemTime) -> u64 {
t.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| u64::try_from(d.as_nanos()).unwrap_or(u64::MAX))
}
/// Fails once `cancel` is set, between the steps that don't watch it themselves.
fn cancelled(cancel: &AtomicBool) -> Result<()> {
ensure!(!cancel.load(Ordering::SeqCst), "the restore was cancelled");
Ok(())
}
/// What a restore writes beyond the system volume and the images it copies: the plan's own files
/// (86 MB on 14.6.1), the Data volume's copy of the data template (the Data volume a restore of
/// 14.6.1 by Apple's restore OS made took 207 MB) and APFS's metadata, with room to spare.
const SLACK: u64 = 2 << 30;
/// The space a restore writes: the system volume as the OS image allocates it (`system` bytes),
/// the images it copies whole (`images` bytes, as the IPSW stores them, which an encrypted
/// archive's plaintext is within), the rest within [`SLACK`], and the auxiliary storage twice
/// over (`aux.img.trimmed` and `aux.img`). Every file is written uncompressed.
pub fn space_needed(system: u64, images: u64) -> u64 {
system + images + SLACK + 2 * AUX_SIZE
}
/// The space free to this user on the file system `path` is on, or would be made on: that of
/// the nearest directory above it that exists.
pub fn free_space(path: &Path) -> Result<u64> {
let mut p = path;
while !p.exists() {
p = p.parent().context("no directory above it exists")?;
}
let c = std::ffi::CString::new(p.as_os_str().as_encoded_bytes())?;
// SAFETY: statvfs fills the struct it is given, from a NUL-terminated path.
let mut s: libc::statvfs = unsafe { std::mem::zeroed() };
if unsafe { libc::statvfs(c.as_ptr(), &mut s) } != 0 {
return Err(std::io::Error::last_os_error())
.with_context(|| format!("statvfs {}", p.display()));
}
#[allow(clippy::useless_conversion)]
Ok(u64::from(s.f_bavail) * u64::from(s.f_frsize))
}
/// Refuses a restore into `dir` where `free` (the space free there) is short of `need`, saying
/// how much it needs.
pub fn check_space(dir: &Path, free: u64, need: u64) -> Result<()> {
ensure!(
free >= need,
"the restore needs about {} free in {}, and there are {}: free some space, or restore \
onto another disk",
gib(need),
dir.display(),
gib(free)
);
Ok(())
}
fn gib(bytes: u64) -> String {
format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64)
}
/// Refuses a directory that doesn't exist or already holds a restore's files.
fn check_dir(dir: &Path) -> Result<()> {
ensure!(
dir.is_dir(),
"{} is not a directory: make the VM's directory first",
dir.display()
);
for f in [
DISK,
AUX,
AUX_TRIMMED,
CONFIG,
MACHINE_IDENTIFIER,
EACS_ISC,
EACS_AUX,
] {
ensure!(
!dir.join(f).exists(),
"{} already holds {f}: restore into an empty VM directory",
dir.display()
);
}
Ok(())
}
/// The restore's files in the VM's directory, under temporary names until it succeeds.
struct Files {
dir: PathBuf,
}
impl Files {
fn new(dir: &Path) -> Self {
Self {
dir: dir.to_owned(),
}
}
fn part(&self, name: &str) -> PathBuf {
self.dir.join(format!("{name}.part"))
}
fn make(&self, disk_size: u64) -> Result<()> {
for (name, size) in [(DISK, disk_size), (AUX_TRIMMED, AUX_SIZE)] {
let p = self.part(name);
let f = File::create(&p).with_context(|| format!("make {}", p.display()))?;
f.set_len(size)
.with_context(|| format!("size {} to {size} bytes", p.display()))?;
}
Ok(())
}
/// For [`FirstBoot::Eacs`]: keeps the iBoot system container's partition of the disk and the
/// auxiliary storage as written, for [`finish_eacs`].
fn keep_for_eacs(&self, table: &Table) -> Result<()> {
let disk = File::open(self.part(DISK)).context("open the disk")?;
let isc = table.isc();
copy_sparse(&disk, isc.offset(), isc.len(), &self.part(EACS_ISC), 0)?;
let aux = File::open(self.part(AUX_TRIMMED)).context("open the auxiliary storage")?;
copy_sparse(&aux, 0, AUX_SIZE, &self.part(EACS_AUX), 0)
}
/// Writes `aux.img`, the machine identifier and the anchor bundle (if any), and moves the
/// disks into place, and, for `eacs`, the copies [`finish_eacs`] puts back.
fn finish(&self, ecid: u64, bundle: Option<&[u8]>, eacs: bool) -> Result<()> {
if let Some(b) = bundle {
let p = self.part(CONFIG);
std::fs::write(&p, b).with_context(|| format!("write {}", p.display()))?;
}
let aux = self.part(AUX);
{
let mut out = File::create(&aux).with_context(|| format!("make {}", aux.display()))?;
out.write_all(&aux::vz_header())?;
let mut trimmed = File::open(self.part(AUX_TRIMMED))?;
std::io::copy(&mut trimmed, &mut out)
.with_context(|| format!("write {}", aux.display()))?;
out.sync_all()?;
}
let id = self.part(MACHINE_IDENTIFIER);
machine_identifier(ecid)
.to_file_binary(&id)
.with_context(|| format!("write {}", id.display()))?;
for name in [DISK, AUX_TRIMMED] {
let p = self.part(name);
File::open(&p)
.and_then(|f| f.sync_all())
.with_context(|| format!("flush {}", p.display()))?;
}
// The machine identifier goes last; a failed move takes back those made before it.
let mut moved = Vec::new();
let mut names = vec![DISK, AUX_TRIMMED, AUX];
if bundle.is_some() {
names.push(CONFIG);
}
if eacs {
names.extend([EACS_ISC, EACS_AUX]);
}
names.push(MACHINE_IDENTIFIER);
for name in names {
let to = self.dir.join(name);
if let Err(e) = std::fs::rename(self.part(name), &to) {
for m in moved {
let _ = std::fs::remove_file(m);
}
return Err(e).with_context(|| format!("move {} into place", to.display()));
}
moved.push(to);
}
if let Ok(d) = File::open(&self.dir) {
let _ = d.sync_all();
}
Ok(())
}
fn discard(&self) {
for name in [
DISK,
AUX_TRIMMED,
AUX,
CONFIG,
MACHINE_IDENTIFIER,
EACS_ISC,
EACS_AUX,
] {
let _ = std::fs::remove_file(self.part(name));
}
}
}
/// Copies `len` bytes of `from` at `at` into a new file `to` at `to_at`, writing only the 4 KiB
/// blocks that aren't all zeroes, so the copy stays sparse.
fn copy_sparse(from: &File, at: u64, len: u64, to: &Path, to_at: u64) -> Result<()> {
use std::os::unix::fs::FileExt as _;
let out = File::create(to).with_context(|| format!("make {}", to.display()))?;
out.set_len(to_at + len)?;
let mut buf = vec![0u8; 1 << 20];
let mut done = 0;
while done < len {
let n = buf
.len()
.min(usize::try_from(len - done).unwrap_or(usize::MAX));
from.read_exact_at(&mut buf[..n], at + done)
.with_context(|| format!("read {n} bytes at {}", at + done))?;
for (i, b) in buf[..n].chunks(4096).enumerate() {
if b.iter().any(|x| *x != 0) {
out.write_all_at(b, to_at + done + (i * 4096) as u64)
.with_context(|| format!("write {}", to.display()))?;
}
}
done += n as u64;
}
out.sync_all()?;
Ok(())
}
/// Makes a VM whose restore left its Data volume to EACS ([`FirstBoot::Eacs`]) bootable, after
/// its first boot made the Data volume and reset: puts the iBoot system container back as the
/// restore wrote it (EACS deleted the macOS LocalPolicy, which only the restore can sign) and the
/// policy nonces back into NVRAM ([`aux::put_back_policy_entries`]), keeping what the guest
/// wrote in the auxiliary storage, its keys in the ean storage among it; then removes the copies.
/// Refuses before the guest's keystore has made its keys. A run cut short can run again.
pub fn finish_eacs(dir: &Path) -> Result<()> {
use std::os::unix::fs::FileExt as _;
let (isc, pre_aux) = (dir.join(EACS_ISC), dir.join(EACS_AUX));
ensure!(
isc.is_file() && pre_aux.is_file(),
"{} holds no restore waiting for its first boot's EACS",
dir.display()
);
let mut a = std::fs::read(dir.join(AUX_TRIMMED))
.with_context(|| format!("read {}", dir.join(AUX_TRIMMED).display()))?;
ensure!(
a.len() == aux::SIZE,
"{AUX_TRIMMED} is not {} bytes",
aux::SIZE
);
ensure!(
aux::ean_entries(&a[aux::EAN_AT..]).is_some_and(|n| n > 1),
"the VM's first boot hasn't made its keys yet: boot it once, until macOS has made its \
Data volume and reset, then finish"
);
let restored =
std::fs::read(&pre_aux).with_context(|| format!("read {}", pre_aux.display()))?;
aux::put_back_policy_entries(&mut a, &restored)?;
let disk = OpenOptions::new()
.read(true)
.write(true)
.open(dir.join(DISK))
.context("open the disk")?;
let t = reims_apfs::gpt::read(&disk).context("read the disk's partition table")?;
let p = t
.partitions
.iter()
.find(|p| p.index == 1)
.context("the disk has no first partition")?;
let (at, len) = (
p.first_lba * t.sector_size,
(p.last_lba + 1 - p.first_lba) * t.sector_size,
);
let from = File::open(&isc).with_context(|| format!("open {}", isc.display()))?;
ensure!(
from.metadata()?.len() == len,
"{EACS_ISC} is not the size of the disk's first partition"
);
let (mut was, mut now) = (vec![0u8; 1 << 20], vec![0u8; 1 << 20]);
let mut done = 0;
while done < len {
let n = was
.len()
.min(usize::try_from(len - done).unwrap_or(usize::MAX));
from.read_exact_at(&mut was[..n], done)?;
disk.read_exact_at(&mut now[..n], at + done)?;
if was[..n] != now[..n] {
disk.write_all_at(&was[..n], at + done)
.context("write the iBoot system container back")?;
}
done += n as u64;
}
disk.sync_all().context("flush the disk")?;
let mut h = aux::vz_header();
h.extend_from_slice(&a);
for (name, bytes) in [(AUX_TRIMMED, &a), (AUX, &h)] {
let p = dir.join(name);
let tmp = dir.join(format!("{name}.part"));
std::fs::write(&tmp, bytes).with_context(|| format!("write {}", tmp.display()))?;
File::open(&tmp)?.sync_all()?;
std::fs::rename(&tmp, &p).with_context(|| format!("move {} into place", p.display()))?;
}
for f in [&isc, &pre_aux] {
std::fs::remove_file(f).with_context(|| format!("remove {}", f.display()))?;
}
Ok(())
}
/// Virtualization.framework's machine identifier: `{ECID: n}`.
fn machine_identifier(ecid: u64) -> Value {
let mut d = Dictionary::new();
d.insert("ECID".into(), Value::Integer(ecid.into()));
Value::Dictionary(d)
}
#[cfg(test)]
mod tests {
use super::*;
fn temp_dir() -> PathBuf {
let mut b = [0u8; 6];
getrandom::fill(&mut b).unwrap();
let hex: String = b.iter().map(|x| format!("{x:02x}")).collect();
let p = std::env::temp_dir().join(format!("reims-restore-test-{hex}"));
std::fs::create_dir(&p).unwrap();
p
}
#[test]
fn a_finished_restore_leaves_vzs_files() {
let d = temp_dir();
let f = Files::new(&d);
f.make(1 << 20).unwrap();
std::fs::write(f.part(AUX_TRIMMED), b"nvram").unwrap();
f.finish(0x1234_5678_9abc_def0, None, false).unwrap();
assert!(!d.join(CONFIG).exists(), "no bundle without the keys");
for n in [DISK, AUX, AUX_TRIMMED, MACHINE_IDENTIFIER] {
assert!(d.join(n).is_file(), "{n}");
assert!(!f.part(n).exists(), "{n}.part");
}
assert_eq!(std::fs::metadata(d.join(DISK)).unwrap().len(), 1 << 20);
let aux = std::fs::read(d.join(AUX)).unwrap();
assert_eq!(&aux[..aux::HEADER_LEN], &aux::vz_header()[..]);
assert_eq!(&aux[aux::HEADER_LEN..], b"nvram");
let id = Value::from_file(d.join(MACHINE_IDENTIFIER)).unwrap();
let ecid = id
.as_dictionary()
.and_then(|d| d.get("ECID"))
.and_then(Value::as_unsigned_integer);
assert_eq!(ecid, Some(0x1234_5678_9abc_def0));
assert!(check_dir(&d).is_err());
std::fs::remove_dir_all(&d).unwrap();
}
#[test]
fn only_macos_14_makes_its_data_volume_by_eacs() {
for v in ["14.0", "14.6.1", "14"] {
assert!(data_by_eacs(v), "{v}");
}
for v in [
"15.0", "15.6.1", "26.6.2", "27.0.1", "27.2.1", "140.1", "4.1",
] {
assert!(!data_by_eacs(v), "{v}");
}
}
fn write_at(p: &Path, at: u64, b: &[u8]) {
use std::os::unix::fs::FileExt as _;
OpenOptions::new()
.write(true)
.open(p)
.unwrap()
.write_all_at(b, at)
.unwrap();
}
fn read_at(p: &Path, at: u64, n: usize) -> Vec<u8> {
use std::os::unix::fs::FileExt as _;
let mut b = vec![0u8; n];
File::open(p).unwrap().read_exact_at(&mut b, at).unwrap();
b
}
/// A finished restore for EACS, of the tests' own bytes: the disk's table, two marks in the
/// iBoot system container and one in the main container, and the auxiliary storage.
fn restored_for_eacs() -> (PathBuf, Table, Nvram, Vec<u8>) {
let d = temp_dir();
let table = Table::layout(MIN_DISK).unwrap();
let f = Files::new(&d);
f.make(MIN_DISK).unwrap();
table
.write(&mut OpenOptions::new().write(true).open(f.part(DISK)).unwrap())
.unwrap();
let isc = table.isc();
write_at(&f.part(DISK), isc.offset() + 0x1000, b"the restore's iSC");
write_at(&f.part(DISK), isc.offset() + isc.len() - 0x1000, b"its end");
write_at(&f.part(DISK), table.main().offset(), b"the main container");
let n = Nvram {
policy_nonces: [
[0x11; 16], [0x22; 16], [3; 16], [4; 16], [5; 16], [6; 16], [7; 16],
],
container: table.main().guid,
group: Uuid::from_u128(0xbf30_4653),
};
let a = aux::trimmed(&n, b"a ticket of the tests' own").unwrap();
std::fs::write(f.part(AUX_TRIMMED), &a).unwrap();
f.keep_for_eacs(&table).unwrap();
f.finish(7, None, true).unwrap();
(d, table, n, a)
}
/// What a guest's EACS boot leaves, as far as finishing reads it: other bytes in the iBoot
/// system container and the main container, the keystore's entries counted in the ean
/// storage, and NVRAM's policy nonces not the restore's.
fn boot_by_eacs(d: &Path, t: &Table, n: &Nvram) {
let isc = t.isc();
let disk = d.join(DISK);
write_at(&disk, isc.offset() + 0x1000, &[0; 17]);
write_at(&disk, isc.offset() + 0x20_0000, b"the guest's iSC");
write_at(&disk, t.main().offset(), b"the guest's Data");
let mut other = n.clone();
other.policy_nonces[1] = [0x99; 16];
let mut a = aux::trimmed(&other, b"a ticket of the tests' own").unwrap();
let e = &mut a[aux::EAN_AT..aux::EAN_AT + 0x1000];
e[8..12].copy_from_slice(&3u32.to_le_bytes());
let crc = crc32fast::hash(&e[..0xffc]);
e[0xffc..].copy_from_slice(&crc.to_le_bytes());
std::fs::write(d.join(AUX_TRIMMED), &a).unwrap();
}
#[test]
fn a_restore_for_eacs_keeps_what_finishing_puts_back() {
let (d, t, _, a) = restored_for_eacs();
for n in [
DISK,
AUX,
AUX_TRIMMED,
MACHINE_IDENTIFIER,
EACS_ISC,
EACS_AUX,
] {
assert!(d.join(n).is_file(), "{n}");
}
let isc = std::fs::metadata(d.join(EACS_ISC)).unwrap();
assert_eq!(isc.len(), t.isc().len());
assert_eq!(read_at(&d.join(EACS_ISC), 0x1000, 17), b"the restore's iSC");
assert_eq!(std::fs::read(d.join(EACS_AUX)).unwrap(), a);
assert!(check_dir(&d).is_err());
std::fs::remove_dir_all(&d).unwrap();
}
#[test]
fn finishing_eacs_puts_the_restores_isc_and_nonces_back() {
let (d, t, n, _) = restored_for_eacs();
boot_by_eacs(&d, &t, &n);
finish_eacs(&d).unwrap();
let disk = d.join(DISK);
let isc = t.isc();
assert_eq!(
read_at(&disk, isc.offset() + 0x1000, 17),
b"the restore's iSC"
);
assert_eq!(read_at(&disk, isc.offset() + 0x20_0000, 15), [0; 15]);
assert_eq!(
read_at(&disk, isc.offset() + isc.len() - 0x1000, 7),
b"its end"
);
assert_eq!(read_at(&disk, t.main().offset(), 16), b"the guest's Data");
let a = std::fs::read(d.join(AUX_TRIMMED)).unwrap();
assert_eq!(
aux::ean_entries(&a[aux::EAN_AT..]),
Some(3),
"the guest's keys stay"
);
for i in 0..2 {
let at = aux::NVRAM_AT + i * 0x8_0000;
let parts = aux::read_bank(&a[at..at + 0x8_0000]).unwrap();
let system = &parts.iter().find(|(p, _)| p == "system").unwrap().1;
let nonces = &system
.iter()
.find(|(k, _)| k == "boop-storage-nonces")
.unwrap()
.1;
assert_eq!(nonces, &n.policy_nonces.concat());
}
let vz = std::fs::read(d.join(AUX)).unwrap();
assert_eq!(&vz[..aux::HEADER_LEN], &aux::vz_header()[..]);
assert_eq!(&vz[aux::HEADER_LEN..], &a[..]);
assert!(!d.join(EACS_ISC).exists() && !d.join(EACS_AUX).exists());
assert!(finish_eacs(&d).is_err(), "nothing left to finish");
std::fs::remove_dir_all(&d).unwrap();
}
#[test]
fn finishing_eacs_waits_for_the_guests_keys() {
let (d, t, _, a) = restored_for_eacs();
let e = finish_eacs(&d).unwrap_err().to_string();
assert!(e.contains("hasn't made its keys"), "{e}");
assert_eq!(std::fs::read(d.join(AUX_TRIMMED)).unwrap(), a);
assert_eq!(
read_at(&d.join(DISK), t.isc().offset() + 0x1000, 17),
b"the restore's iSC"
);
assert!(d.join(EACS_ISC).exists() && d.join(EACS_AUX).exists());
std::fs::remove_dir_all(&d).unwrap();
}
#[test]
fn a_restore_with_the_keys_leaves_the_bundle() {
let d = temp_dir();
let f = Files::new(&d);
f.make(4096).unwrap();
f.finish(1, Some(b"070701 a bundle"), false).unwrap();
assert_eq!(std::fs::read(d.join(CONFIG)).unwrap(), b"070701 a bundle");
assert!(!f.part(CONFIG).exists());
std::fs::remove_dir_all(&d).unwrap();
}
#[test]
fn a_failed_restore_leaves_nothing() {
let d = temp_dir();
let f = Files::new(&d);
f.make(4096).unwrap();
f.discard();
assert_eq!(std::fs::read_dir(&d).unwrap().count(), 0);
check_dir(&d).unwrap();
std::fs::remove_dir(&d).unwrap();
}
#[test]
fn a_failed_move_leaves_nothing_that_looks_finished() {
let d = temp_dir();
let f = Files::new(&d);
f.make(4096).unwrap();
// The machine identifier's place is taken by a directory with a file in it.
std::fs::create_dir(d.join(MACHINE_IDENTIFIER)).unwrap();
std::fs::write(d.join(MACHINE_IDENTIFIER).join("x"), b"x").unwrap();
assert!(f.finish(1, Some(b"a bundle"), false).is_err());
for n in [DISK, AUX, AUX_TRIMMED, CONFIG] {
assert!(!d.join(n).exists(), "{n} was left in place");
}
std::fs::remove_dir_all(d.join(MACHINE_IDENTIFIER)).unwrap();
f.discard();
assert_eq!(std::fs::read_dir(&d).unwrap().count(), 0);
std::fs::remove_dir(&d).unwrap();
}
#[test]
fn a_restore_needs_the_space_it_writes() {
let d = temp_dir();
let need = space_needed(10 << 30, 8 << 30);
assert_eq!(need, (20 << 30) + (64 << 20));
assert!(check_space(&d, need, need).is_ok());
let e = check_space(&d, need - 1, need).unwrap_err().to_string();
assert!(e.contains("20.1 GiB"), "{e}");
assert!(free_space(&d.join("not/made/yet")).unwrap() > 0);
std::fs::remove_dir_all(&d).unwrap();
}
#[test]
fn secrets_bind_nvram_to_the_disk() {
let t = Table::layout(64 << 30).unwrap();
let s = Secrets::generate(Some(0xabc), &t).unwrap();
assert_eq!(s.ecid, 0xabc);
assert_eq!(s.nvram.container, t.main().guid);
assert_eq!(s.nonces.sep_nonce, tss::VZ_SEP_NONCE);
let other = Secrets::generate(None, &t).unwrap();
assert_ne!(other.nvram.policy_nonces, s.nvram.policy_nonces);
assert_ne!(other.nonces.ap_nonce, s.nonces.ap_nonce);
}
#[test]
fn a_cancelled_restore_stops_between_steps() {
let c = AtomicBool::new(false);
assert!(cancelled(&c).is_ok());
c.store(true, Ordering::SeqCst);
assert!(cancelled(&c).is_err());
}
}
File diff suppressed because it is too large. Load diff
+322
View File
@@ -0,0 +1,322 @@
//! The macOS volume group's LocalPolicies, which the restore writes and signs itself
//! (docs/design.md, "The LocalPolicy"): iSCPreboot's `/<G>/LocalPolicy/<LPNH>.img4`, which the
//! installed macOS boots with, and `<LPNH>.recovery.img4` beside it, its recoveryOS's. Each is
//! the LocalPolicy IM4P ([`img4::LPOL_IM4P`]) stitched to a manifest whose properties bind it to
//! the VM, its boot manifest, its Cryptex1 ticket and the policy nonces in NVRAM.
//!
//! The properties are those of a fresh restore by Virtualization.framework of the same build,
//! whose policies the restore OS signs with Apple's built-in "Hacktivation" key **[vz]**. Ours
//! are signed by the project's own chain, which Ambrosia swaps in for the kernel's anchors at
//! boot ([`crate::anchors`]), so the kernel checks the signature and every binding as it would
//! Apple's.
use std::collections::BTreeMap;
use anyhow::{Context, Result, ensure};
use p384::ecdsa::signature::Signer as _;
use uuid::Uuid;
use crate::img4::{self, Prop};
/// What binds a LocalPolicy to one VM and one install.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Binding {
/// The VM's ECID.
pub ecid: u64,
/// The chip, board and security domain, as the boot manifest carries them.
pub chip: u64,
pub board: u64,
pub security_domain: u64,
/// The OS's version as the boot manifest's `love` carries it, such as `26.2.131.0.0,0`.
pub love: Vec<u8>,
/// The boot manifest (Preboot's `/<G>/boot/<H>/System/Library/Caches/apticket.der`): its
/// SHA-384 is `nsih`.
pub boot_manifest_hash: [u8; 48],
/// The Cryptex1 ticket: its SHA-384 is `spih`.
pub cryptex1_ticket_hash: [u8; 48],
/// The policy nonces whose SHA-384 are `lpnh` and `rpnh` (NVRAM's `boop-storage-nonces`).
pub local_nonce: [u8; 16],
pub remote_nonce: [u8; 16],
/// The volume group: `vuid`.
pub group: Uuid,
}
/// Which of the two policies.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
/// `<LPNH>.img4`, the installed macOS's.
MacOs,
/// `<LPNH>.recovery.img4`, its recoveryOS's.
Recovery,
}
impl Binding {
/// `lpnh`: the policy's name, in upper-case hex.
pub fn lpnh(&self) -> [u8; 48] {
img4::sha384(&self.local_nonce)
}
/// The policy's file name in `/<G>/LocalPolicy/`.
pub fn file_name(&self, kind: Kind) -> String {
let hex: String = self.lpnh().iter().map(|b| format!("{b:02X}")).collect();
match kind {
Kind::MacOs => format!("{hex}.img4"),
Kind::Recovery => format!("{hex}.recovery.img4"),
}
}
/// The manifest's own properties (MANP) **[vz]**.
pub fn props(&self, kind: Kind) -> BTreeMap<String, Prop> {
let mut p = BTreeMap::new();
let mut put = |k: &str, v: Prop| {
p.insert(k.to_owned(), v);
};
put("BORD", Prop::Int(self.board));
put("CEPO", Prop::Int(1));
put("CHIP", Prop::Int(self.chip));
put("CPRO", Prop::Bool(true));
put("CSEC", Prop::Bool(true));
put("ECID", Prop::Int(self.ecid));
put("SDOM", Prop::Int(self.security_domain));
put("lobo", Prop::Bool(true));
put("love", Prop::Data(self.love.clone()));
put("lpnh", Prop::Data(self.lpnh().to_vec()));
put("nsih", Prop::Data(self.boot_manifest_hash.to_vec()));
put(
"rpnh",
Prop::Data(img4::sha384(&self.remote_nonce).to_vec()),
);
put("vuid", Prop::Data(self.group.as_bytes().to_vec()));
match kind {
Kind::MacOs => {
put("hrlp", Prop::Bool(true));
put("spih", Prop::Data(self.cryptex1_ticket_hash.to_vec()));
put("stng", Prop::Int(1));
}
Kind::Recovery => put("rolp", Prop::Bool(true)),
}
p
}
/// The signed MANB `SET`: the properties and the `lpol` object, the LocalPolicy IM4P's
/// digest with `EKEY`.
pub fn manb(&self, kind: Kind) -> Vec<u8> {
let mut lpol = BTreeMap::new();
lpol.insert(
"DGST".to_owned(),
Prop::Data(img4::sha384(&img4::LPOL_IM4P).to_vec()),
);
lpol.insert("EKEY".to_owned(), Prop::Bool(true));
let mut objects = BTreeMap::new();
objects.insert("lpol".to_owned(), lpol);
img4::encode_manb(&self.props(kind), &objects)
}
/// The LocalPolicy, an IMG4, signed by `signer`.
pub fn sign(&self, kind: Kind, signer: &Signer) -> Vec<u8> {
let manb = self.manb(kind);
let im4m = img4::encode_im4m(&manb, &signer.sign(&manb), &signer.chain);
img4::stitch_img4(&img4::LPOL_IM4P, &im4m)
}
}
/// The key LocalPolicies are signed with, and the certificate chain the manifest carries.
pub struct Signer {
key: p384::ecdsa::SigningKey,
/// `SEQUENCE { intermediate, leaf }`, as encoded.
chain: Vec<u8>,
}
impl Signer {
/// A signer of the leaf's key (PKCS#8 or SEC1 PEM) and the chain's certificates (DER), the
/// intermediate first, as a manifest stores them.
pub fn new(key_pem: &str, certs: &[&[u8]]) -> Result<Self> {
use p384::pkcs8::DecodePrivateKey as _;
let key = p384::SecretKey::from_pkcs8_pem(key_pem)
.or_else(|_| p384::SecretKey::from_sec1_pem(key_pem))
.context("the LocalPolicy key is not a P-384 private key in PEM")?;
Self::with_key(p384::ecdsa::SigningKey::from(key), certs)
}
/// A signer of the leaf's `key` and the chain's certificates (DER), the intermediate first.
pub fn with_key(key: p384::ecdsa::SigningKey, certs: &[&[u8]]) -> Result<Self> {
ensure!(
!certs.is_empty(),
"the LocalPolicy signer has no certificates"
);
let body: Vec<u8> = certs.concat();
let mut chain = vec![0x30];
chain.extend(der_len(body.len()));
chain.extend(body);
Ok(Self { key, chain })
}
/// The project's signer, built in: one key for every VM, since whoever can write a VM's disk
/// can write its NVRAM too, so a key per VM would protect nothing (docs/design.md, "The
/// LocalPolicy"). `keys/make.sh` made it.
pub fn project() -> Self {
Self::new(
include_str!("../keys/policy-leaf.key"),
&[
include_bytes!("../keys/policy-intermediate.der"),
include_bytes!("../keys/policy-leaf.der"),
],
)
.expect("the built-in LocalPolicy signer is a P-384 key and its chain")
}
/// ECDSA P-384 with SHA-384 over `msg`, DER-encoded, as a manifest's signature is.
fn sign(&self, msg: &[u8]) -> Vec<u8> {
let s: p384::ecdsa::Signature = self.key.sign(msg);
s.to_der().as_bytes().to_vec()
}
}
fn der_len(n: usize) -> Vec<u8> {
if n < 0x80 {
return vec![n as u8];
}
let b = n.to_be_bytes();
let skip = b.iter().take_while(|x| **x == 0).count();
let mut out = vec![0x80 | (b.len() - skip) as u8];
out.extend(&b[skip..]);
out
}
#[cfg(test)]
mod tests {
use super::*;
use p384::ecdsa::signature::Verifier as _;
fn binding() -> Binding {
Binding {
ecid: 0x0123_4567_89ab_cdef,
chip: 0xfe00,
board: 0x20,
security_domain: 1,
love: b"26.2.131.0.0,0".to_vec(),
boot_manifest_hash: [1; 48],
cryptex1_ticket_hash: [2; 48],
local_nonce: [3; 16],
remote_nonce: [4; 16],
group: Uuid::from_u128(0xbf30_4653),
}
}
fn signer() -> (Signer, p384::ecdsa::VerifyingKey) {
let key = p384::SecretKey::from_slice(&[7u8; 48]).unwrap();
let pem = {
use p384::pkcs8::EncodePrivateKey as _;
key.to_pkcs8_pem(Default::default()).unwrap().to_string()
};
let s = Signer::new(&pem, &[b"\x30\x03\x02\x01\x01", b"\x30\x03\x02\x01\x02"]).unwrap();
let v = p384::ecdsa::VerifyingKey::from(&p384::ecdsa::SigningKey::from(key));
(s, v)
}
#[test]
fn the_macos_policy_carries_vzs_properties() {
let b = binding();
let names: Vec<String> = b.props(Kind::MacOs).into_keys().collect();
assert_eq!(
names,
[
"BORD", "CEPO", "CHIP", "CPRO", "CSEC", "ECID", "SDOM", "hrlp", "lobo", "love",
"lpnh", "nsih", "rpnh", "spih", "stng", "vuid"
]
);
let names: Vec<String> = b.props(Kind::Recovery).into_keys().collect();
assert_eq!(
names,
[
"BORD", "CEPO", "CHIP", "CPRO", "CSEC", "ECID", "SDOM", "lobo", "love", "lpnh",
"nsih", "rolp", "rpnh", "vuid"
]
);
assert_eq!(
b.props(Kind::MacOs)["vuid"],
Prop::Data(b.group.as_bytes().to_vec())
);
}
#[test]
fn a_signed_policy_parses_and_verifies() {
let b = binding();
let (s, v) = signer();
let lp = b.sign(Kind::MacOs, &s);
let (im4p, im4m) = img4::split_img4(&lp).unwrap();
assert_eq!(im4p, img4::LPOL_IM4P);
let m = img4::parse_im4m(im4m.expect("the policy carries its manifest")).unwrap();
assert_eq!(m.props, b.props(Kind::MacOs));
assert_eq!(m.signed, b.manb(Kind::MacOs));
assert_eq!(
m.objects["lpol"]["DGST"],
Prop::Data(img4::sha384(&img4::LPOL_IM4P).to_vec())
);
assert_eq!(
m.certs,
[
b"\x30\x03\x02\x01\x01".to_vec(),
b"\x30\x03\x02\x01\x02".to_vec()
]
);
let sig = p384::ecdsa::Signature::from_der(&m.signature).unwrap();
v.verify(&m.signed, &sig).unwrap();
}
#[test]
fn the_policy_is_named_for_its_nonces_hash() {
let b = binding();
let n = b.file_name(Kind::MacOs);
assert_eq!(n.len(), 96 + 5);
assert!(n.starts_with(&format!("{:02X}", img4::sha384(&[3; 16])[0])));
assert_eq!(
b.file_name(Kind::Recovery),
n.replace(".img4", ".recovery.img4")
);
}
#[test]
fn the_project_signer_signs_with_its_leaf() {
let s = Signer::project();
let b = binding();
let m = img4::parse_im4m(
img4::split_img4(&b.sign(Kind::MacOs, &s))
.unwrap()
.1
.unwrap(),
)
.unwrap();
assert_eq!(
m.certs,
[
include_bytes!("../keys/policy-intermediate.der").to_vec(),
include_bytes!("../keys/policy-leaf.der").to_vec()
]
);
let v = p384::ecdsa::VerifyingKey::from(&s.key);
let sig = p384::ecdsa::Signature::from_der(&m.signature).unwrap();
v.verify(&m.signed, &sig).unwrap();
// The leaf certificate is the key's.
let point = v.to_sec1_point(false);
assert!(
include_bytes!("../keys/policy-leaf.der")
.windows(97)
.any(|w| w == point.as_bytes())
);
}
#[test]
fn a_key_that_is_not_p384_is_refused() {
let p256 = {
use p256::pkcs8::EncodePrivateKey as _;
p256::SecretKey::from_slice(&[7u8; 32])
.unwrap()
.to_pkcs8_pem(Default::default())
.unwrap()
.to_string()
};
assert!(Signer::new(&p256, &[b"\x30\x00"]).is_err());
assert!(Signer::new("not a key", &[b"\x30\x00"]).is_err());
}
}
+214
View File
@@ -0,0 +1,214 @@
//! Random access to bytes: a file, a range of one, or an image inside another, read at offsets
//! from several places at once.
use std::fs::File;
use std::io;
use std::os::unix::fs::FileExt;
use std::sync::Arc;
/// Bytes read at offsets, from any thread.
pub trait ReadAt: Send + Sync {
/// Reads up to `buf.len()` bytes at `offset`; returns how many, 0 only at or past the end.
fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize>;
/// The number of bytes.
fn len(&self) -> u64;
/// Whether there are no bytes.
fn is_empty(&self) -> bool {
self.len() == 0
}
/// Fills `buf` from `offset`, or fails with `UnexpectedEof`.
fn read_exact_at(&self, mut offset: u64, mut buf: &mut [u8]) -> io::Result<()> {
while !buf.is_empty() {
let n = self.read_at(offset, buf)?;
if n == 0 {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
format!("short read at {offset} of {} bytes", self.len()),
));
}
offset += n as u64;
buf = &mut buf[n..];
}
Ok(())
}
}
impl<T: ReadAt + ?Sized> ReadAt for Arc<T> {
fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize> {
(**self).read_at(offset, buf)
}
fn len(&self) -> u64 {
(**self).len()
}
}
impl<T: ReadAt + ?Sized> ReadAt for Box<T> {
fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize> {
(**self).read_at(offset, buf)
}
fn len(&self) -> u64 {
(**self).len()
}
}
impl ReadAt for [u8] {
fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize> {
let Ok(start) = usize::try_from(offset) else {
return Ok(0);
};
if start >= <[u8]>::len(self) {
return Ok(0);
}
let n = buf.len().min(<[u8]>::len(self) - start);
buf[..n].copy_from_slice(&self[start..start + n]);
Ok(n)
}
fn len(&self) -> u64 {
<[u8]>::len(self) as u64
}
}
impl ReadAt for Vec<u8> {
fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize> {
self.as_slice().read_at(offset, buf)
}
fn len(&self) -> u64 {
<[u8]>::len(self) as u64
}
}
/// A range of a file: `len` bytes from `start`.
pub struct FileRange {
file: Arc<File>,
start: u64,
len: u64,
}
impl FileRange {
/// The range `start..start + len` of `file`.
pub fn new(file: Arc<File>, start: u64, len: u64) -> Self {
Self { file, start, len }
}
/// The whole of `file`.
pub fn whole(file: File) -> io::Result<Self> {
let len = file.metadata()?.len();
Ok(Self::new(Arc::new(file), 0, len))
}
}
impl ReadAt for FileRange {
fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize> {
if offset >= self.len {
return Ok(0);
}
let n = (buf.len() as u64).min(self.len - offset) as usize;
self.file.read_at(&mut buf[..n], self.start + offset)
}
fn len(&self) -> u64 {
self.len
}
}
/// A range of another source.
pub struct SubRange<S> {
inner: S,
start: u64,
len: u64,
}
impl<S: ReadAt> SubRange<S> {
/// `len` bytes of `inner` from `start`; fails if they don't lie within it.
pub fn new(inner: S, start: u64, len: u64) -> io::Result<Self> {
if start.checked_add(len).is_none_or(|end| end > inner.len()) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("range {start}+{len} lies outside {} bytes", inner.len()),
));
}
Ok(Self { inner, start, len })
}
}
impl<S: ReadAt> ReadAt for SubRange<S> {
fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize> {
if offset >= self.len {
return Ok(0);
}
let n = (buf.len() as u64).min(self.len - offset) as usize;
self.inner.read_at(self.start + offset, &mut buf[..n])
}
fn len(&self) -> u64 {
self.len
}
}
/// A `Read` + `Seek` cursor over a source.
pub struct Cursor<S> {
inner: S,
pos: u64,
}
impl<S: ReadAt> Cursor<S> {
/// A cursor at the start of `inner`.
pub fn new(inner: S) -> Self {
Self { inner, pos: 0 }
}
}
impl<S: ReadAt> io::Read for Cursor<S> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let n = self.inner.read_at(self.pos, buf)?;
self.pos += n as u64;
Ok(n)
}
}
impl<S: ReadAt> io::Seek for Cursor<S> {
fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
let new = match pos {
io::SeekFrom::Start(p) => Some(p),
io::SeekFrom::End(d) => self.inner.len().checked_add_signed(d),
io::SeekFrom::Current(d) => self.pos.checked_add_signed(d),
};
self.pos = new
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "seek before the start"))?;
Ok(self.pos)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::{Read, Seek, SeekFrom};
#[test]
fn sub_range_reads_only_its_bytes() {
let data: Vec<u8> = (0..100).collect();
let r = SubRange::new(data, 10, 20).unwrap();
let mut buf = [0u8; 30];
assert_eq!(r.read_at(15, &mut buf).unwrap(), 5);
assert_eq!(&buf[..5], &[25, 26, 27, 28, 29]);
assert_eq!(r.read_at(20, &mut buf).unwrap(), 0);
}
#[test]
fn sub_range_outside_its_source_is_refused() {
let data = vec![0u8; 10];
assert!(SubRange::new(data, 5, 6).is_err());
}
#[test]
fn cursor_reads_and_seeks() {
let data: Vec<u8> = (0..10).collect();
let mut c = Cursor::new(data);
c.seek(SeekFrom::End(-3)).unwrap();
let mut v = Vec::new();
c.read_to_end(&mut v).unwrap();
assert_eq!(v, [7, 8, 9]);
assert!(c.seek(SeekFrom::Current(-11)).is_err());
}
}
+126
View File
@@ -0,0 +1,126 @@
//! A local HTTP/1.1 server for the tests of what the tool fetches (http.rs, catalog.rs,
//! download.rs): each request is answered by a handler, one connection per request, and the
//! requests are recorded.
use std::io::{Read as _, Write as _};
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, Mutex};
/// An answer: its status, headers and body, and where the body is cut off by closing the
/// connection (a download that drops part way).
pub struct Reply {
pub status: u16,
pub headers: Vec<(String, String)>,
pub body: Vec<u8>,
pub cut: Option<usize>,
}
impl From<(u16, Vec<(String, String)>, Vec<u8>)> for Reply {
fn from((status, headers, body): (u16, Vec<(String, String)>, Vec<u8>)) -> Reply {
Reply {
status,
headers,
body,
cut: None,
}
}
}
/// A request as the server saw it: its path, and its headers with lowercased names.
#[derive(Clone, Debug)]
pub struct Seen {
pub path: String,
pub headers: Vec<(String, String)>,
}
impl Seen {
pub fn header(&self, name: &str) -> Option<&str> {
self.headers
.iter()
.find(|(k, _)| k == name)
.map(|(_, v)| v.as_str())
}
}
type Handler = dyn Fn(&str, &Seen) -> Reply + Send + Sync;
pub struct Server {
port: u16,
seen: Arc<Mutex<Vec<Seen>>>,
}
impl Server {
/// Starts a server answering each request with `handler(path, request)`; it runs until the
/// test process ends.
pub fn start<R: Into<Reply>>(
handler: impl Fn(&str, &Seen) -> R + Send + Sync + 'static,
) -> Server {
let l = TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
let seen = Arc::new(Mutex::new(Vec::new()));
let handler: Arc<Handler> = Arc::new(move |p: &str, s: &Seen| handler(p, s).into());
let log = seen.clone();
std::thread::spawn(move || {
for s in l.incoming() {
let Ok(s) = s else { continue };
let (handler, log) = (handler.clone(), log.clone());
std::thread::spawn(move || serve(s, &*handler, &log));
}
});
Server { port, seen }
}
pub fn url(&self, path: &str) -> String {
format!("http://127.0.0.1:{}{path}", self.port)
}
/// The paths requested, in order.
pub fn paths(&self) -> Vec<String> {
self.requests().into_iter().map(|s| s.path).collect()
}
pub fn requests(&self) -> Vec<Seen> {
self.seen.lock().unwrap().clone()
}
}
fn serve(mut s: TcpStream, handler: &Handler, log: &Mutex<Vec<Seen>>) {
let mut req = Vec::new();
let mut b = [0u8; 4096];
let end = loop {
if let Some(i) = req.windows(4).position(|w| w == b"\r\n\r\n") {
break i + 4;
}
match s.read(&mut b) {
Ok(0) | Err(_) => return,
Ok(n) => req.extend_from_slice(&b[..n]),
}
};
let head = String::from_utf8_lossy(&req[..end]).to_string();
let mut lines = head.split("\r\n");
let path = lines
.next()
.and_then(|l| l.split(' ').nth(1))
.unwrap_or_default()
.to_owned();
let headers = lines
.take_while(|l| !l.is_empty())
.filter_map(|l| l.split_once(':'))
.map(|(k, v)| (k.trim().to_ascii_lowercase(), v.trim().to_owned()))
.collect();
let seen = Seen { path, headers };
log.lock().unwrap().push(seen.clone());
let r = handler(&seen.path, &seen);
let mut out = format!("HTTP/1.1 {} X\r\n", r.status);
for (k, v) in &r.headers {
out.push_str(&format!("{k}: {v}\r\n"));
}
out.push_str(&format!(
"Content-Length: {}\r\nConnection: close\r\n\r\n",
r.body.len()
));
let _ = s.write_all(out.as_bytes());
let body = &r.body[..r.cut.unwrap_or(r.body.len()).min(r.body.len())];
let _ = s.write_all(body);
let _ = s.flush();
}
File diff suppressed because it is too large. Load diff
+489
View File
@@ -0,0 +1,489 @@
//! UDIF disk images (`.dmg`), read at random offsets without unpacking them: the koly trailer,
//! the `blkx` tables of its resource fork, and each chunk decompressed when first read, with the
//! last few kept.
use std::collections::VecDeque;
use std::io::{self, Read};
use std::sync::{Arc, Mutex};
use anyhow::{Context, Result, bail, ensure};
use plist::Value;
use crate::source::ReadAt;
const SECTOR: u64 = 512;
/// The most bytes one chunk may expand to: a UDIF chunk is at most a few MiB.
const MAX_CHUNK: u64 = 64 << 20;
/// How many decompressed chunks are kept.
const CACHE_CHUNKS: usize = 48;
/// What a chunk holds.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
Zero,
Raw,
Adc,
Zlib,
Bzip2,
Lzfse,
Lzma,
}
/// One chunk of the image: sectors `start..start + count`, from `len` bytes at `offset`.
#[derive(Clone, Copy, Debug)]
struct Chunk {
kind: Kind,
start: u64,
count: u64,
offset: u64,
len: u64,
}
/// One partition the image's `blkx` tables describe.
#[derive(Clone, Debug)]
pub struct Partition {
/// Its name, such as `Apple_APFS : 4` or `Protective Master Boot Record (MBR : 0)`.
pub name: String,
/// Its first byte in the image.
pub offset: u64,
/// Its length in bytes.
pub len: u64,
}
/// A UDIF image over a source of its bytes.
pub struct Udif<S> {
src: S,
chunks: Vec<Chunk>,
partitions: Vec<Partition>,
len: u64,
cache: Mutex<VecDeque<(usize, Arc<Vec<u8>>)>>,
}
fn be32(b: &[u8], o: usize) -> u32 {
u32::from_be_bytes(b[o..o + 4].try_into().unwrap())
}
fn be64(b: &[u8], o: usize) -> u64 {
u64::from_be_bytes(b[o..o + 8].try_into().unwrap())
}
impl<S: ReadAt> Udif<S> {
/// Opens the image `src` holds: reads its trailer and chunk tables.
pub fn open(src: S) -> Result<Self> {
let total = src.len();
ensure!(
total >= 512,
"the image is {total} bytes, too short for a UDIF trailer"
);
let mut koly = [0u8; 512];
src.read_exact_at(total - 512, &mut koly)
.context("read the image's trailer")?;
ensure!(&koly[..4] == b"koly", "not a UDIF image: no koly trailer");
let data_fork = be64(&koly, 24);
let xml_offset = be64(&koly, 216);
let xml_len = be64(&koly, 224);
ensure!(
xml_len > 0 && xml_len <= 64 << 20,
"the image's plist is {xml_len} bytes"
);
ensure!(
xml_offset.checked_add(xml_len).is_some_and(|e| e <= total),
"the image's plist lies past its end"
);
let mut xml = vec![0u8; xml_len as usize];
src.read_exact_at(xml_offset, &mut xml)
.context("read the image's plist")?;
let plist = Value::from_reader(io::Cursor::new(&xml)).context("parse the image's plist")?;
let blkx = plist
.as_dictionary()
.and_then(|d| d.get("resource-fork"))
.and_then(Value::as_dictionary)
.and_then(|d| d.get("blkx"))
.and_then(Value::as_array)
.context("the image's plist has no resource-fork blkx")?;
let mut chunks = Vec::new();
let mut partitions = Vec::new();
for entry in blkx {
let d = entry
.as_dictionary()
.context("a blkx entry is not a dictionary")?;
let name = d
.get("Name")
.or_else(|| d.get("CFName"))
.and_then(Value::as_string)
.unwrap_or("")
.to_owned();
let data = d
.get("Data")
.and_then(Value::as_data)
.context("a blkx entry has no Data")?;
ensure!(
data.len() >= 204 && &data[..4] == b"mish",
"blkx {name:?} is not a mish table"
);
let first = be64(data, 8);
let count = be64(data, 16);
let base = data_fork + be64(data, 24);
let n = be32(data, 200) as usize;
ensure!(
data.len() >= 204 + n * 40,
"blkx {name:?} is shorter than its {n} chunks"
);
for i in 0..n {
let c = &data[204 + i * 40..204 + (i + 1) * 40];
let kind = match be32(c, 0) {
0x0000_0000 | 0x0000_0002 => Kind::Zero,
0x0000_0001 => Kind::Raw,
0x8000_0004 => Kind::Adc,
0x8000_0005 => Kind::Zlib,
0x8000_0006 => Kind::Bzip2,
0x8000_0007 => Kind::Lzfse,
0x8000_0008 => Kind::Lzma,
0x7fff_fffe | 0xffff_ffff => continue,
t => bail!(
"blkx {name:?} has a chunk of type {t:#x}, which this reader doesn't know"
),
};
let ch = Chunk {
kind,
start: first + be64(c, 8),
count: be64(c, 16),
offset: base + be64(c, 24),
len: be64(c, 32),
};
// Zero and raw chunks are read in place, at any size; a compressed one is
// expanded whole.
ensure!(
matches!(kind, Kind::Zero | Kind::Raw) || ch.count * SECTOR <= MAX_CHUNK,
"blkx {name:?} has a compressed chunk of {} sectors",
ch.count
);
ensure!(
ch.offset.checked_add(ch.len).is_some_and(|e| e <= total),
"blkx {name:?} has a chunk past the image's end: the image is truncated"
);
if ch.count > 0 {
chunks.push(ch);
}
}
partitions.push(Partition {
name,
offset: first * SECTOR,
len: count * SECTOR,
});
}
chunks.sort_by_key(|c| c.start);
for w in chunks.windows(2) {
ensure!(
w[0].start + w[0].count <= w[1].start,
"the image's chunks overlap"
);
}
let len = chunks.last().map_or(0, |c| (c.start + c.count) * SECTOR);
Ok(Self {
src,
chunks,
partitions,
len,
cache: Mutex::new(VecDeque::new()),
})
}
/// The partitions its `blkx` tables name.
pub fn partitions(&self) -> &[Partition] {
&self.partitions
}
/// The one partition whose name contains `what`, such as `Apple_APFS`.
pub fn partition(&self, what: &str) -> Result<&Partition> {
let mut found = self.partitions.iter().filter(|p| p.name.contains(what));
let p = found
.next()
.with_context(|| format!("the image has no {what} partition"))?;
ensure!(
found.next().is_none(),
"the image has more than one {what} partition"
);
Ok(p)
}
/// The decompressed bytes of chunk `i`.
fn chunk(&self, i: usize) -> io::Result<Arc<Vec<u8>>> {
if let Some((_, d)) = self.cache.lock().unwrap().iter().find(|(j, _)| *j == i) {
return Ok(d.clone());
}
let c = self.chunks[i];
let want = (c.count * SECTOR) as usize;
let mut packed = vec![0u8; c.len as usize];
self.src.read_exact_at(c.offset, &mut packed)?;
let bad = |what: &str| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("a {what} chunk of the image is damaged"),
)
};
let mut out = Vec::with_capacity(want);
match c.kind {
Kind::Zlib => {
flate2::read::ZlibDecoder::new(&packed[..])
.take(want as u64)
.read_to_end(&mut out)
.map_err(|_| bad("zlib"))?;
}
Kind::Bzip2 => {
bzip2::read::BzDecoder::new(&packed[..])
.take(want as u64)
.read_to_end(&mut out)
.map_err(|_| bad("bzip2"))?;
}
Kind::Lzfse => {
lzfse_rust::decode_bytes(&packed, &mut out).map_err(|_| bad("LZFSE"))?;
}
Kind::Lzma => {
lzma_rs::xz_decompress(&mut &packed[..], &mut out).map_err(|_| bad("LZMA"))?;
}
Kind::Adc => adc_decode(&packed, &mut out, want).map_err(|_| bad("ADC"))?,
Kind::Zero | Kind::Raw => unreachable!("read in place"),
}
if out.len() != want {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"a chunk of the image expands to {} bytes, not {want}",
out.len()
),
));
}
let out = Arc::new(out);
let mut cache = self.cache.lock().unwrap();
if cache.len() >= CACHE_CHUNKS {
cache.pop_front();
}
cache.push_back((i, out.clone()));
Ok(out)
}
}
impl<S: ReadAt> ReadAt for Udif<S> {
fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize> {
if offset >= self.len || buf.is_empty() {
return Ok(0);
}
let sector = offset / SECTOR;
// The chunk holding `sector`, or the gap before the next one, which reads as zeroes.
let i = self.chunks.partition_point(|c| c.start + c.count <= sector);
let Some(c) = self.chunks.get(i).copied() else {
return Ok(0);
};
if sector < c.start {
let n = buf.len().min((c.start * SECTOR - offset) as usize);
buf[..n].fill(0);
return Ok(n);
}
let within = offset - c.start * SECTOR;
let n = buf.len().min((c.count * SECTOR - within) as usize);
match c.kind {
Kind::Zero => buf[..n].fill(0),
Kind::Raw => {
// A raw chunk may hold fewer bytes than its sectors; the rest reads as zeroes.
let have = c.len.saturating_sub(within).min(n as u64) as usize;
self.src
.read_exact_at(c.offset + within, &mut buf[..have])?;
buf[have..n].fill(0);
}
_ => {
let d = self.chunk(i)?;
buf[..n].copy_from_slice(&d[within as usize..within as usize + n]);
}
}
Ok(n)
}
fn len(&self) -> u64 {
self.len
}
}
/// Apple Data Compression, the oldest UDIF codec.
fn adc_decode(input: &[u8], out: &mut Vec<u8>, max: usize) -> Result<(), ()> {
let mut i = 0;
while i < input.len() && out.len() < max {
let b = input[i];
if b & 0x80 != 0 {
let n = (b & 0x7f) as usize + 1;
out.extend_from_slice(input.get(i + 1..i + 1 + n).ok_or(())?);
i += 1 + n;
} else if b & 0x40 != 0 {
let n = (b & 0x3f) as usize + 4;
let d = u16::from_be_bytes([*input.get(i + 1).ok_or(())?, *input.get(i + 2).ok_or(())?])
as usize
+ 1;
copy_back(out, d, n)?;
i += 3;
} else {
let n = ((b & 0x3c) >> 2) as usize + 3;
let d = (((b & 0x03) as usize) << 8 | *input.get(i + 1).ok_or(())? as usize) + 1;
copy_back(out, d, n)?;
i += 2;
}
}
Ok(())
}
fn copy_back(out: &mut Vec<u8>, distance: usize, n: usize) -> Result<(), ()> {
if distance > out.len() {
return Err(());
}
for _ in 0..n {
out.push(out[out.len() - distance]);
}
Ok(())
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use std::io::Write;
/// A UDIF image written from scratch: one partition holding `data`, in 4-sector chunks
/// of each kind in turn, with a run of zeroes left as a zero-fill chunk.
pub fn synthetic(data: &[u8]) -> Vec<u8> {
assert_eq!(data.len() % 2048, 0);
let mut fork = Vec::new();
let mut table = Vec::new();
let sectors = data.len() as u64 / SECTOR;
let mut chunks: Vec<[u8; 40]> = Vec::new();
for (n, piece) in data.chunks(2048).enumerate() {
let start = n as u64 * 4;
let (kind, packed): (u32, Vec<u8>) = if piece.iter().all(|&b| b == 0) {
(0x2, Vec::new())
} else {
match n % 4 {
0 => (0x1, piece.to_vec()),
1 => {
let mut e = flate2::write::ZlibEncoder::new(
Vec::new(),
flate2::Compression::default(),
);
e.write_all(piece).unwrap();
(0x8000_0005, e.finish().unwrap())
}
2 => {
let mut e =
bzip2::write::BzEncoder::new(Vec::new(), bzip2::Compression::default());
e.write_all(piece).unwrap();
(0x8000_0006, e.finish().unwrap())
}
_ => {
let mut out = Vec::new();
lzfse_rust::encode_bytes(piece, &mut out).unwrap();
(0x8000_0007, out)
}
}
};
let mut c = [0u8; 40];
c[0..4].copy_from_slice(&kind.to_be_bytes());
c[8..16].copy_from_slice(&start.to_be_bytes());
c[16..24].copy_from_slice(&4u64.to_be_bytes());
c[24..32].copy_from_slice(&(fork.len() as u64).to_be_bytes());
c[32..40].copy_from_slice(&(packed.len() as u64).to_be_bytes());
fork.extend_from_slice(&packed);
chunks.push(c);
}
let mut end = [0u8; 40];
end[0..4].copy_from_slice(&0xffff_ffffu32.to_be_bytes());
chunks.push(end);
table.extend_from_slice(b"mish");
table.extend_from_slice(&1u32.to_be_bytes());
table.extend_from_slice(&0u64.to_be_bytes());
table.extend_from_slice(&sectors.to_be_bytes());
table.extend_from_slice(&0u64.to_be_bytes());
table.resize(200, 0);
table.extend_from_slice(&(chunks.len() as u32).to_be_bytes());
for c in &chunks {
table.extend_from_slice(c);
}
let mut part = plist::Dictionary::new();
part.insert("Name".into(), Value::String("Apple_APFS : 1".into()));
part.insert("Data".into(), Value::Data(table));
let mut rf = plist::Dictionary::new();
rf.insert("blkx".into(), Value::Array(vec![Value::Dictionary(part)]));
let mut root = plist::Dictionary::new();
root.insert("resource-fork".into(), Value::Dictionary(rf));
let mut xml = Vec::new();
Value::Dictionary(root).to_writer_xml(&mut xml).unwrap();
let mut img = fork;
let xml_off = img.len() as u64;
img.extend_from_slice(&xml);
let mut koly = [0u8; 512];
koly[0..4].copy_from_slice(b"koly");
koly[4..8].copy_from_slice(&4u32.to_be_bytes());
koly[8..12].copy_from_slice(&512u32.to_be_bytes());
koly[32..40].copy_from_slice(&xml_off.to_be_bytes());
koly[216..224].copy_from_slice(&xml_off.to_be_bytes());
koly[224..232].copy_from_slice(&(xml.len() as u64).to_be_bytes());
koly[492..500].copy_from_slice(&sectors.to_be_bytes());
img.extend_from_slice(&koly);
img
}
fn pattern(len: usize) -> Vec<u8> {
let mut v: Vec<u8> = (0..len as u32)
.map(|i| (i.wrapping_mul(2654435761) >> 13) as u8)
.collect();
// A zero run that becomes a zero-fill chunk.
if len >= 2048 * 6 {
v[2048 * 5..2048 * 6].fill(0);
}
v
}
#[test]
fn reads_every_chunk_kind_at_any_offset() {
let data = pattern(2048 * 12);
let img = Udif::open(synthetic(&data)).unwrap();
assert_eq!(img.len(), data.len() as u64);
assert_eq!(img.partition("Apple_APFS").unwrap().len, data.len() as u64);
for (off, n) in [
(0usize, 100usize),
(2000, 5000),
(2048 * 5 - 3, 2060),
(data.len() - 7, 7),
(1, data.len() - 1),
] {
let mut buf = vec![0u8; n];
img.read_exact_at(off as u64, &mut buf).unwrap();
assert_eq!(buf, data[off..off + n], "at {off}+{n}");
}
let mut buf = [0u8; 4];
assert_eq!(img.read_at(data.len() as u64, &mut buf).unwrap(), 0);
}
#[test]
fn a_damaged_chunk_is_an_error_not_wrong_bytes() {
let data = pattern(2048 * 4);
let mut raw = synthetic(&data);
// Chunk 1 is zlib; it starts right after chunk 0's 2048 raw bytes.
raw[2048 + 10] ^= 0xff;
let img = Udif::open(raw).unwrap();
let mut buf = vec![0u8; 2048];
assert!(img.read_exact_at(2048, &mut buf).is_err());
}
#[test]
fn a_truncated_image_is_refused() {
let data = pattern(2048 * 4);
let raw = synthetic(&data);
assert!(Udif::open(raw[100..].to_vec()).is_err());
assert!(Udif::open(raw[..raw.len() - 600].to_vec()).is_err());
}
#[test]
fn adc_decodes_literals_and_copies() {
// "abc" literal, then a 4-byte copy from 3 back: "abcabca".
let input = [0x82, b'a', b'b', b'c', 0x40, 0x00, 0x02];
let mut out = Vec::new();
adc_decode(&input, &mut out, 100).unwrap();
assert_eq!(out, b"abcabca");
}
}
+122
View File
@@ -0,0 +1,122 @@
//! XML property lists in the form Apple's own writer gives them: a dictionary's keys sorted, one
//! tab per level, and data in base64 lines that end by column 76 with a tab counted as 8. The
//! restore writes the plists a fresh restore leaves in this form, so that each matches its
//! counterpart byte for byte (docs/design.md, "The disk").
use std::fmt::Write as _;
use base64::Engine as _;
use plist::Value;
const HEAD: &str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \
\"-//Apple//DTD PLIST 1.0//EN\" \
\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist \
version=\"1.0\">\n";
/// `v` as an XML property list.
pub fn to_xml(v: &Value) -> Vec<u8> {
let mut s = String::from(HEAD);
value(&mut s, v, 0);
s.push_str("</plist>\n");
s.into_bytes()
}
fn indent(s: &mut String, level: usize) {
for _ in 0..level {
s.push('\t');
}
}
fn line(s: &mut String, level: usize, text: &str) {
indent(s, level);
s.push_str(text);
s.push('\n');
}
fn escape(t: &str) -> String {
t.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
}
fn value(s: &mut String, v: &Value, level: usize) {
match v {
Value::Dictionary(d) if d.is_empty() => line(s, level, "<dict/>"),
Value::Dictionary(d) => {
line(s, level, "<dict>");
let mut keys: Vec<&String> = d.keys().collect();
keys.sort();
for k in keys {
line(s, level + 1, &format!("<key>{}</key>", escape(k)));
value(s, &d[k], level + 1);
}
line(s, level, "</dict>");
}
Value::Array(a) if a.is_empty() => line(s, level, "<array/>"),
Value::Array(a) => {
line(s, level, "<array>");
for x in a {
value(s, x, level + 1);
}
line(s, level, "</array>");
}
Value::String(t) => line(s, level, &format!("<string>{}</string>", escape(t))),
Value::Integer(i) => line(s, level, &format!("<integer>{i}</integer>")),
Value::Real(r) => line(s, level, &format!("<real>{r:?}</real>")),
Value::Boolean(b) => line(s, level, if *b { "<true/>" } else { "<false/>" }),
Value::Date(d) => line(s, level, &format!("<date>{}</date>", d.to_xml_format())),
Value::Data(d) => {
line(s, level, "<data>");
// Each line holds as many whole 4-character groups as fit before column 76.
let width = 76usize.saturating_sub(8 * level).max(16) / 4 * 3;
let b64 = base64::engine::general_purpose::STANDARD;
for chunk in d.chunks(width) {
indent(s, level);
let _ = writeln!(s, "{}", b64.encode(chunk));
}
line(s, level, "</data>");
}
Value::Uid(u) => line(s, level, &format!("<integer>{}</integer>", u.get())),
_ => line(s, level, "<string></string>"),
}
}
#[cfg(test)]
mod tests {
use super::*;
use plist::Dictionary;
#[test]
fn a_plist_is_written_in_apples_form() {
let mut inner = Dictionary::new();
inner.insert("Digest".into(), Value::Data((0u8..40).collect()));
inner.insert("Trusted".into(), Value::Boolean(true));
let mut d = Dictionary::new();
d.insert("b".into(), Value::Integer(7.into()));
d.insert("a & <z>".into(), Value::String("x<y".into()));
d.insert(
"c".into(),
Value::Array(vec![Value::Dictionary(inner), Value::Array(vec![])]),
);
d.insert("e".into(), Value::Dictionary(Dictionary::new()));
let got = String::from_utf8(to_xml(&Value::Dictionary(d))).unwrap();
let want = format!(
"{HEAD}<dict>\n\t<key>a &amp; &lt;z&gt;</key>\n\t<string>x&lt;y</string>\n\
\t<key>b</key>\n\t<integer>7</integer>\n\t<key>c</key>\n\t<array>\n\t\t<dict>\n\
\t\t\t<key>Digest</key>\n\t\t\t<data>\n\
\t\t\tAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUm\n\t\t\tJw==\n\t\t\t</data>\n\t\t\t<key>Trusted</key>\n\t\t\t<true/>\n\
\t\t</dict>\n\t\t<array/>\n\t</array>\n\t<key>e</key>\n\t<dict/>\n</dict>\n</plist>\n"
);
assert_eq!(got, want);
}
#[test]
fn what_is_written_reads_back() {
let mut d = Dictionary::new();
d.insert("k".into(), Value::Data(vec![0xab; 300]));
d.insert("n".into(), Value::Integer(u64::MAX.into()));
let v = Value::Dictionary(d);
let back = Value::from_reader_xml(std::io::Cursor::new(to_xml(&v))).unwrap();
assert_eq!(back, v);
}
}
+2
View File
@@ -112,6 +112,8 @@ one. A new trap found the same way goes here.
## Tools and worktrees
- A hard link shares a file's bytes, so code that may write the file it opens writes the original too. A live check of the IPSW download hard-linked the owner's cached 27.2.1 IPSW into a scratch cache as a finished `.part`, expecting the downloader only to hash it and read the CDN's 416 for a range past the file's end. Apple's CDN answers that 416 with `Content-Range: */25595954706`, without the `bytes` unit RFC 9110 puts there (**measured** 2026-11-11), which the downloader's parser didn't read, so it took the part for a wrong one, and its start-over truncated the part in place, and with it the owner's file. The downloader now never truncates or rewrites a file: it starts over by unlinking the part and making a new one, and learns the length first, so a whole part is only hashed. How to avoid the next: a live check never links an owner's file; it uses an APFS clone (`cp -c`) or a reflink, whose writes don't reach the original, or a cache of its own. Before linking anything, read the code for every write and truncate it could reach.
- A shell script under `set -u` with an EXIT trap passes when it aborts, on macOS. **Measured** with macOS's `/bin/bash`, 3.2.57, 2026-11-08: a script that reads an unset variable under `set -u` stops there and exits 1, but with any `trap ... EXIT` set it exits 0, and `$?` is 0 inside the trap too, so even a trap that exits with the status it saw passes it on. `guest/rgfxgate/tests/payload_test.sh` removed its scratch from such a trap, and a case that read a shifted-away argument stopped the script at its first bundle while `make -C guest test` went on green. Each script that pairs them now keeps an `ended` flag, set at each deliberate success end, and its trap turns an exit 0 short of that end into 1 and keeps any other status: `trap 'rc=$?; CLEANUP; [[ $rc != 0 || $ended == 1 ]] || rc=1; exit $rc' EXIT` (an `exit 1` from the trap does set the status after such an abort). How to spot the next one: a check that reports green with less output than it should, its last lines missing; look for `set -u` (or `set -euo pipefail`) beside `trap ... EXIT` in a script that runs on a Mac, and give it the flag.
- `git stash` is one list, shared by every worktree of a repository (`refs/stash` is not per worktree), so a stash pushed in one worktree can be popped into another. Set work aside with a WIP commit on the worktree's own branch, or a patch file under `/tmp`, never a stash. When changes appear that nobody in the tree made, or a pop conflicts with files the tree never touched, suspect another worktree's stash.
- A shared `CARGO_TARGET_DIR` runs another tree's `xtask`. Cargo keys a workspace member's build by its path inside the workspace, not by where the workspace is, and calls the binary fresh when no source file at those relative paths is newer than its last build. So a worktree whose files predate the other tree's last build of `xtask` runs that build, made from the other tree's sources (**measured** on two copies of one package sharing a target directory: the second `cargo run -v` printed `Fresh` and ran the first copy's binary). Give each worktree its own target directory under `~/.cache`. When a tool behaves as if a change were missing, look for `Fresh` in `cargo run -v`.