feat(restore): request personalized root tickets from TSS, bound to the ECID and the restore's AP and SEP nonces

This commit is contained in:
Tyler Smith committed 2026-10-20 20:18:31 +00:00
1 parent 86fcc28c9e
commit dfd60bf248
9 files changed
+685 -54

No files matched your search

+12 -2
View File
@@ -1721,8 +1721,8 @@ pub extern "sysv64" fn entry(handoff: u64) -> ! {
));
if options.tss {
output::arguments(format_args!(
"TSS OPT-IN: the restore host may send this machine's ECID and component hashes \
to gs.apple.com; this build's restore host does not request a LocalPolicy yet\n"
"TSS OPT-IN: the restore host sends this machine's ECID, the restore's nonces and \
its component hashes to gs.apple.com for its root tickets and recoveryOS LocalPolicy\n"
));
}
// Waits return to this loop often enough that a press of the host's
@@ -1754,8 +1754,18 @@ pub extern "sysv64" fn entry(handoff: u64) -> ! {
"--tss needs the bundle's machine ECID (stela boot prepare --ecid)",
)
});
// Stela holds the boot ROM's and the SEP ROM's nonces for the
// restore, drawn once from the CPU's entropy.
let mut nonces = stela_runtime::restore::tss::Nonces {
ap: [0; 32],
sep: [0; 20],
};
bundle::entropy(&mut nonces.ap)
.and_then(|()| bundle::entropy(&mut nonces.sep))
.unwrap_or_else(|error| output::fatal(error));
stela_runtime::restore::tss::Signer {
ecid,
nonces,
transport: alloc::boxed::Box::new(
host_network.take().expect("--tss opens the host network"),
),
+46 -11
View File
@@ -221,6 +221,8 @@ pub struct Answers<R> {
pub staged: Staged,
/// Apple's signing service, only when the user enables it (`tss`).
pub signer: Option<tss::Signer>,
/// The root tickets Apple personalized for this restore, each asked once.
roots: BTreeMap<tss::Root, Ticket>,
/// The host's wall clock, in seconds since the Unix epoch.
pub clock: Option<Box<dyn FnMut() -> u64>>,
}
@@ -230,6 +232,7 @@ impl<R: ReadAt> Answers<R> {
store,
staged: Staged::default(),
signer: None,
roots: BTreeMap::new(),
clock: None,
}
}
@@ -274,12 +277,7 @@ impl<R: ReadAt> Answers<R> {
}
fn identity(&self, args: &Value) -> Result<Identity> {
let current = self.store.identity();
if !args
.get("IsRecoveryOS")
.map(Value::boolean)
.transpose()?
.unwrap_or(false)
{
if !recovery_os(args)? {
return Ok(current.clone());
}
let matches: Vec<_> = self
@@ -323,6 +321,35 @@ impl<R: ReadAt> Answers<R> {
let path = self.global_path(identity, args, cryptex)?;
Ticket::global(self.store.read_small(&path)?, identity)
}
/// The AP root ticket for `identity`: with the signing service, the one
/// Apple personalizes for this machine and restore over the restore
/// identity (idevicerestore's `tss` and `tss_recoveryos_root_ticket`),
/// else the IPSW's global one.
fn root(&mut self, identity: &Identity, args: &Value) -> Result<Ticket> {
let Some(signer) = self.signer.as_mut() else {
return self.global(identity, args, false);
};
let root = match recovery_os(args)? {
true => tss::Root::RecoveryOs,
false => tss::Root::Ap,
};
if let Some(ticket) = self.roots.get(&root) {
return Ok(ticket.clone());
}
let restore = self.store.identity();
let bytes = tss::request_root_ticket(signer, restore, root)?;
let ticket = Ticket::personalized(bytes, restore, signer.ecid, Some(&signer.nonces))?;
self.roots.insert(root, ticket.clone());
Ok(ticket)
}
/// The ticket that covers component `name`: Cryptex1 components keep the
/// IPSW's global cryptex ticket, every other one the AP root ticket.
fn ticket_for(&mut self, identity: &Identity, args: &Value, name: &str) -> Result<Ticket> {
match name.starts_with("Cryptex1,") {
true => self.global(identity, args, true),
false => self.root(identity, args),
}
}
fn member_bytes(&mut self, path: &str) -> Result<Vec<u8>> {
let size = self.store.member_len(path)?;
if size > MAX_REPLY_BYTES as u64 {
@@ -348,7 +375,7 @@ impl<R: ReadAt> Answers<R> {
let head = self.store.read_at(&path, 0, size.min(64) as usize)?;
let (stored, at) = bare_type(&head, size)?;
let digest = identity.component(name)?.required("Digest")?.data()?;
let global = self.global(identity, args, name.starts_with("Cryptex1,"))?;
let global = self.ticket_for(identity, args, name)?;
// Image4 finds the object by its IM4P type: send the type under which
// the ticket covers the manifest digest (`Ticket::retype_covered`).
let tag = if self.store.digest384(&path)?.as_slice() == digest {
@@ -357,7 +384,7 @@ impl<R: ReadAt> Answers<R> {
let tags = global.tags_with(digest);
if tags.is_empty() {
return Err(Error::Invalid(
"global manifest does not cover exact component digest",
"the ticket does not cover the exact component digest",
));
}
let mut found = None;
@@ -411,7 +438,7 @@ impl<R: ReadAt> Answers<R> {
let path = identity.path(name)?;
let mut bytes = self.member_bytes(path)?;
let digest = identity.component(name)?.required("Digest")?.data()?;
let global = self.global(identity, args, name.starts_with("Cryptex1,"))?;
let global = self.ticket_for(identity, args, name)?;
global.retype_covered(&mut bytes, digest)?;
global.wrap(&bytes, digest)
}
@@ -433,7 +460,7 @@ impl<R: ReadAt> Answers<R> {
),
]))),
"RootTicket" | "RecoveryOSRootTicketData" => {
let g = self.global(&identity, args, false)?;
let g = self.root(&identity, args)?;
Ok(Plan::Reply(Value::dict([(
"RootTicketData",
Value::Data(g.bytes().to_vec()),
@@ -538,7 +565,7 @@ impl<R: ReadAt> Answers<R> {
"recoveryOS LocalPolicy needs Apple's signing service (opt-in --tss); a Stela-signed policy fails libbootpolicy's Apple root",
))?;
let bytes = tss::request_local_policy(signer, identity, args)?;
let ticket = Ticket::personalized(bytes, identity, signer.ecid)?;
let ticket = Ticket::personalized(bytes, identity, signer.ecid, None)?;
let policy = ticket.wrap(&tss::LOCAL_POLICY, &Sha384::digest(tss::LOCAL_POLICY))?;
Ok(Plan::Reply(Value::dict([(
"Ap,LocalPolicy",
@@ -931,6 +958,14 @@ fn framed_binary(v: &Streamed) -> Result<Vec<Segment>> {
segments.insert(0, Segment::Bytes(length.to_be_bytes().to_vec()));
Ok(segments)
}
/// Whether a request is for the recoveryOS (`IsRecoveryOS`).
fn recovery_os(args: &Value) -> Result<bool> {
Ok(args
.get("IsRecoveryOS")
.map(Value::boolean)
.transpose()?
.unwrap_or(false))
}
/// The variant directory of a global manifest: the request's `Variant`, else
/// the identity's macOS variant. An erase or upgrade identity names it as
/// `MacOSVariant`; the `macOS Customer` identity restored selects with
@@ -577,6 +577,7 @@ pub(crate) mod tests {
("ApChipID", Value::from("0x8112")),
("ApBoardID", Value::from("0x24")),
("ApSecurityDomain", Value::from("0x1")),
("UniqueBuildID", Value::Data(vec![0x12; 8])),
("Manifest", Value::Dict(components)),
]);
let build = plist::encode_xml(
+62 -14
View File
@@ -4,7 +4,7 @@
//! chip/board/domain (and, personalized, the device's ECID) plus the SHA-384 of
//! the original IM4P before constructing an IMG4. No new signature, nonce
//! substitution, type rewrite or certificate is manufactured.
use super::{Error, Result, plist::Value, store::Identity};
use super::{Error, Result, plist::Value, store::Identity, tss::Nonces};
use alloc::{collections::BTreeMap, vec::Vec};
use sha2::{Digest, Sha384};
const MAX_TICKET_BYTES: usize = 1024 * 1024;
@@ -97,6 +97,7 @@ fn integer(b: &[u8]) -> Result<u64> {
}
Ok(b.iter().fold(0, |n, &v| (n << 8) | v as u64))
}
#[derive(Clone)]
pub struct Ticket {
bytes: Vec<u8>,
entries: BTreeMap<[u8; 4], BTreeMap<[u8; 4], Value>>,
@@ -109,9 +110,14 @@ impl Ticket {
}
/// A ticket personalized for the device whose ECID is `ecid`: its `MANP`
/// must name exactly that ECID. A nonce-bound property (`BNCH`, `snon`)
/// still refuses, since no request here sends a nonce.
pub fn personalized(bytes: Vec<u8>, identity: &Identity, ecid: u64) -> Result<Self> {
let ticket = Self::parse(bytes, identity, Some(ecid))?;
/// must equal the nonce the request sent, and refuses without one.
pub fn personalized(
bytes: Vec<u8>,
identity: &Identity,
ecid: u64,
nonces: Option<&Nonces>,
) -> Result<Self> {
let ticket = Self::parse(bytes, identity, Some((ecid, nonces)))?;
let named = ticket
.entries
.get(b"MANP")
@@ -123,7 +129,12 @@ impl Ticket {
}
Ok(ticket)
}
fn parse(bytes: Vec<u8>, identity: &Identity, ecid: Option<u64>) -> Result<Self> {
fn parse(
bytes: Vec<u8>,
identity: &Identity,
binding: Option<(u64, Option<&Nonces>)>,
) -> Result<Self> {
let nonces = binding.and_then(|(_, nonces)| nonces);
if bytes.len() > MAX_TICKET_BYTES {
return Err(Error::Limit("IM4M bytes"));
}
@@ -162,10 +173,16 @@ impl Ticket {
let (key, mut property) = named(first, tag, b)?;
let (first, _, b) = property.next()?;
property.end()?;
if matches!(&key, b"BNCH" | b"snon")
|| (key == *b"ECID" && (ecid.is_none() || name != *b"MANP"))
{
return Err(Error::Invalid("manifest is personalized/nonce-bound"));
let sent = match &key {
b"BNCH" => nonces.map(|n| &n.ap[..]),
b"snon" => nonces.map(|n| &n.sep[..]),
_ => Some(b),
};
if sent != Some(b) {
return Err(Error::Invalid("ticket is bound to another nonce"));
}
if key == *b"ECID" && (binding.is_none() || name != *b"MANP") {
return Err(Error::Invalid("manifest is personalized"));
}
let value = match first {
2 => Value::Integer(integer(b)?),
@@ -273,7 +290,7 @@ impl Ticket {
crate::img4::set_payload_type(im4p, original)
.map_err(|_| Error::Invalid("IM4P payload type"))?;
Err(Error::Invalid(
"global manifest does not cover exact component digest",
"the ticket does not cover the exact component digest",
))
}
pub fn wrap(&self, source: &[u8], manifest_digest: &[u8]) -> Result<Vec<u8>> {
@@ -289,7 +306,7 @@ impl Ticket {
let digest = Sha384::digest(parts.payload);
if digest.as_slice() != manifest_digest || !self.covers(tag, manifest_digest) {
return Err(Error::Invalid(
"global manifest does not cover exact component digest",
"the ticket does not cover the exact component digest",
));
}
Ok(tlv(
@@ -343,6 +360,15 @@ pub(crate) mod tests {
/// A synthetic ticket covering `payload` as `tag`, personalized for
/// `ecid` when given.
pub(crate) fn ticket_for(tag: &[u8; 4], payload: &[u8], ecid: Option<u64>) -> Vec<u8> {
bound_ticket(tag, payload, ecid, None)
}
/// `ticket_for`, bound to `nonces` (`BNCH`, `snon`) when given.
pub(crate) fn bound_ticket(
tag: &[u8; 4],
payload: &[u8],
ecid: Option<u64>,
nonces: Option<&Nonces>,
) -> Vec<u8> {
let mut p = [
entry(b"CHIP", &tlv(2, &[0, 0x81, 0x12])),
entry(b"BORD", &tlv(2, &[0x24])),
@@ -359,6 +385,10 @@ pub(crate) mod tests {
}
p.extend(entry(b"ECID", &tlv(2, &digits)));
}
if let Some(nonces) = nonces {
p.extend(entry(b"BNCH", &tlv(4, &nonces.ap)));
p.extend(entry(b"snon", &tlv(4, &nonces.sep)));
}
let entries = [
entry(b"MANP", &tlv(0x31, &p)),
entry(
@@ -380,16 +410,34 @@ pub(crate) mod tests {
)
}
#[test]
fn a_nonce_bound_ticket_must_name_the_sent_nonces() {
let store = super::super::store::tests::fixture(b"x", false);
let identity = store.identity();
let sent = Nonces {
ap: [1; 32],
sep: [2; 20],
};
let bound = bound_ticket(b"krnl", b"k", Some(7), Some(&sent));
assert!(Ticket::personalized(bound.clone(), identity, 7, Some(&sent)).is_ok());
assert!(Ticket::personalized(bound.clone(), identity, 7, None).is_err());
let other = Nonces {
ap: [3; 32],
..sent
};
assert!(Ticket::personalized(bound.clone(), identity, 7, Some(&other)).is_err());
assert!(Ticket::global(bound, identity).is_err());
}
#[test]
fn a_personalized_ticket_must_name_this_devices_ecid() {
let store = super::super::store::tests::fixture(b"x", false);
let identity = store.identity();
let bytes = ticket_for(b"lpol", b"policy", Some(0xabcd_1234));
assert!(Ticket::global(bytes.clone(), identity).is_err());
assert!(Ticket::personalized(bytes.clone(), identity, 0xabcd_1235).is_err());
let ticket = Ticket::personalized(bytes, identity, 0xabcd_1234).unwrap();
assert!(Ticket::personalized(bytes.clone(), identity, 0xabcd_1235, None).is_err());
let ticket = Ticket::personalized(bytes, identity, 0xabcd_1234, None).unwrap();
assert!(ticket.covers(*b"lpol", &Sha384::digest(b"policy")));
let global = ticket_for(b"lpol", b"policy", None);
assert!(Ticket::personalized(global, identity, 0xabcd_1234).is_err());
assert!(Ticket::personalized(global, identity, 0xabcd_1234, None).is_err());
}
#[test]
fn only_exact_payload_digest_can_be_wrapped() {
+435 -10
View File
@@ -1,14 +1,19 @@
//! The opt-in request to Apple's signing service (TSS) for the recoveryOS
//! LocalPolicy, the one object restored verifies against Apple's fixed roots
//! The opt-in requests to Apple's signing service (TSS): the personalized AP
//! root tickets a restore installs, and the recoveryOS LocalPolicy, the one
//! object restored verifies against Apple's fixed roots
//! (`docs/research/restore-trust.md`), so no Stela key can sign it.
//!
//! Wire: libtatsu `tss.c` (`tss_request_new`,
//! `tss_request_add_local_policy_tags`, `tss_request_send`) and idevicerestore
//! 4b3e847e `idevicerestore.c` (`get_recovery_os_local_policy_tss_response`,
//! `lpol_file`). The request carries the device's ECID, its chip, board and
//! security domain, and the hashes restored supplies; nothing is sent without
//! a [`Transport`], which the user enables explicitly. The answer is Apple's
//! ticket, unchanged: the guest's libbootpolicy authenticates it.
//! Wire: libtatsu `tss.c` (`tss_request_new`, `tss_parameters_add_from_manifest`,
//! `tss_request_add_common_tags`, `tss_request_add_ap_tags`,
//! `tss_request_add_ap_recovery_tags`, `tss_request_add_ap_img4_tags`,
//! `tss_entry_apply_restore_request_rules`, `tss_request_add_local_policy_tags`,
//! `tss_request_send`) and idevicerestore 4b3e847e `idevicerestore.c`
//! (`get_tss_response`, `get_recoveryos_root_ticket_tss_response`,
//! `get_recovery_os_local_policy_tss_response`, `lpol_file`). A request carries
//! the device's ECID, its chip, board and security domain, the build's
//! component digests and the boot's nonces; nothing is sent without a
//! [`Transport`], which the user enables explicitly. The answer is Apple's
//! ticket, unchanged: the guest authenticates it.
use super::{Error, Result, plist, plist::Value, store::Identity};
use alloc::{format, string::String, vec::Vec};
use sha2::{Digest, Sha256, Sha384};
@@ -36,9 +41,244 @@ pub trait Transport {
/// The device the request personalizes for, and the way out to Apple.
pub struct Signer {
pub ecid: u64,
pub nonces: Nonces,
pub transport: alloc::boxed::Box<dyn Transport>,
}
/// The nonces a root ticket binds (`BNCH`, `snon`). On a Mac the boot ROM
/// and iBEC hold the AP nonce and the SEP ROM its own when the host asks for
/// the restore's tickets; under Stela, which plays both roles, they are drawn
/// once for the restore, and a ticket naming any other refuses.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Nonces {
/// The AP nonce: 32 bytes under `boot-nonce-hash-method` sha2-384.
pub ap: [u8; 32],
/// The SEP nonce, a 20-byte ROM nonce (`generateROMNonce`).
pub sep: [u8; 20],
}
/// Which root ticket a restore asks for.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Root {
/// The AP ticket (`RootTicket`): every trusted component of the restore
/// identity, restore-only firmware and the FDR trust objects included.
Ap,
/// The recoveryOS root ticket (`RecoveryOSRootTicketData`): the same
/// identity without the components libtatsu leaves out of it.
RecoveryOs,
}
/// Build-identity keys libtatsu copies from the identity into every AP
/// request (`tss_parameters_add_from_manifest`, then
/// `tss_request_add_ap_img4_tags`), when present.
const IDENTITY_STRINGS: [&str; 8] = [
"Ap,OSLongVersion",
"Ap,OSReleaseType",
"Ap,ProductMarketingVersion",
"Ap,ProductType",
"Ap,SDKPlatform",
"Ap,Target",
"Ap,TargetType",
"Ap,Timestamp",
];
/// Components no AP request carries (`tss_request_add_ap_tags`).
const AP_SKIPPED: [&str; 5] = [
"BasebandFirmware",
"SE,UpdatePayload",
"BaseSystem",
"Diags",
"Ap,ExclaveOS",
];
/// Components the recoveryOS root ticket also leaves out
/// (`tss_request_add_ap_recovery_tags`); it keeps `Ap,ExclaveOS`.
const RECOVERY_SKIPPED: [&str; 30] = [
"BasebandFirmware",
"SE,UpdatePayload",
"BaseSystem",
"ANS",
"Ap,AudioBootChime",
"Ap,CIO",
"Ap,RestoreCIO",
"Ap,RestoreTMU",
"Ap,TMU",
"Ap,rOSLogo1",
"Ap,rOSLogo2",
"AppleLogo",
"DCP",
"LLB",
"RecoveryMode",
"RestoreANS",
"RestoreDCP",
"RestoreDeviceTree",
"RestoreKernelCache",
"RestoreLogo",
"RestoreRamDisk",
"RestoreSEP",
"SEP",
"ftap",
"ftsp",
"iBEC",
"iBSS",
"rfta",
"rfts",
"Diags",
];
/// The TSS request for `root` over the restore identity, as
/// idevicerestore's `get_tss_response` (AP) and
/// `get_recoveryos_root_ticket_tss_response` build it for an Image4 device
/// in production and security mode.
pub fn root_ticket_request(
identity: &Identity,
ecid: u64,
nonces: &Nonces,
root: Root,
) -> Result<Value> {
if ecid == 0 {
return Err(Error::Invalid("TSS needs the machine's nonzero ECID"));
}
let mut request = Value::dict([
("@HostPlatformInfo", Value::from("mac")),
("@VersionInfo", Value::from(VERSION)),
("@ApImg4Ticket", Value::Boolean(true)),
("ApECID", Value::Integer(ecid)),
(
"UniqueBuildID",
Value::Data(identity.value.required("UniqueBuildID")?.data()?.to_vec()),
),
("ApChipID", Value::Integer(identity.number("ApChipID")?)),
("ApBoardID", Value::Integer(identity.number("ApBoardID")?)),
(
"ApSecurityDomain",
Value::Integer(identity.number("ApSecurityDomain")?),
),
("ApNonce", Value::Data(nonces.ap.to_vec())),
("SepNonce", Value::Data(nonces.sep.to_vec())),
("ApSecurityMode", Value::Boolean(true)),
("ApProductionMode", Value::Boolean(true)),
]);
let Value::Dict(fields) = &mut request else {
unreachable!()
};
for key in IDENTITY_STRINGS {
if let Some(value) = identity.value.get(key) {
fields.insert(key.into(), Value::from(value.string()?));
}
}
let Value::Dict(manifest) = identity.value.required("Manifest")? else {
return Err(Error::Invalid("identity Manifest dictionary"));
};
let skipped: &[&str] = match root {
Root::Ap => &AP_SKIPPED,
Root::RecoveryOs => &RECOVERY_SKIPPED,
};
for (name, entry) in manifest {
if skipped.contains(&name.as_str()) {
continue;
}
if let Some(component) = component_entry(entry, root)? {
fields.insert(name.clone(), component);
}
}
// libtatsu sends a random GUID that only names the request; this one
// names it by its contents, so a retry of the same request keeps it.
let id = guid(&plist::encode_xml(&request, plist::Limits::default())?);
if let Value::Dict(fields) = &mut request {
fields.insert("@UUID".into(), Value::String(id));
}
Ok(request)
}
/// One manifest entry as an AP request carries it, or `None` for one it
/// leaves out: the entry without its `Info`, its `RestoreRequestRules`
/// applied, and an empty `Digest` for a trusted entry that has none.
fn component_entry(entry: &Value, root: Root) -> Result<Option<Value>> {
let Value::Dict(fields) = entry else {
return Err(Error::Invalid("BuildManifest entry dictionary"));
};
let Some(info) = entry.get("Info") else {
return Ok(None);
};
let trusted = entry
.get("Trusted")
.map(Value::boolean)
.transpose()?
.unwrap_or(false);
let rules = info.get("RestoreRequestRules");
if root == Root::Ap {
let ftab = info
.get("IsFTAB")
.map(Value::boolean)
.transpose()?
.unwrap_or(false);
if (rules.is_none() && !trusted) || ftab {
return Ok(None);
}
}
let mut out = fields.clone();
out.remove("Info");
match rules {
Some(rules) => apply_rules(&mut out, rules)?,
None if root == Root::Ap => {
out.insert("EPRO".into(), Value::Boolean(true));
out.insert("ESEC".into(), Value::Boolean(true));
}
None => {}
}
if trusted && !fields.contains_key("Digest") {
out.insert("Digest".into(), Value::Data(Vec::new()));
}
// The AP request drops an empty entry; the recovery request keeps it.
Ok((root == Root::RecoveryOs || !out.is_empty()).then_some(Value::Dict(out)))
}
/// `tss_entry_apply_restore_request_rules` for a production, security-mode
/// Image4 request: a rule applies when each of its conditions names one of
/// those parameters with an equal value; the Boolean actions of each rule
/// that applies are set, in order. A condition on a parameter this request
/// does not have (`ApDemotionPolicyOverride`, `ApInRomDFU`) never holds.
fn apply_rules(
entry: &mut alloc::collections::BTreeMap<String, Value>,
rules: &Value,
) -> Result<()> {
for rule in rules.array()? {
let Value::Dict(conditions) = rule.required("Conditions")? else {
return Err(Error::Invalid("RestoreRequestRules conditions"));
};
let holds = conditions.iter().all(|(key, value)| {
matches!(
key.as_str(),
"ApRawProductionMode"
| "ApCurrentProductionMode"
| "ApRawSecurityMode"
| "ApRequiresImage4"
) && *value == Value::Boolean(true)
});
if !holds {
continue;
}
let Value::Dict(actions) = rule.required("Actions")? else {
return Err(Error::Invalid("RestoreRequestRules actions"));
};
for (key, value) in actions {
if let Value::Boolean(_) = value {
entry.insert(key.clone(), value.clone());
}
}
}
Ok(())
}
/// Ask Apple for `root`'s ticket.
pub fn request_root_ticket(
signer: &mut Signer,
identity: &Identity,
root: Root,
) -> Result<Vec<u8>> {
let request = root_ticket_request(identity, signer.ecid, &signer.nonces, root)?;
send(signer, &request)
}
/// The TSS request for a recoveryOS LocalPolicy, from restored's
/// `RecoveryOSLocalPolicy` arguments (`Ap,NextStageIM4MHash`,
/// `Ap,RecoveryOSPolicyNonceHash`, `Ap,VolumeUUID`).
@@ -129,7 +369,11 @@ pub fn request_local_policy(
args: &Value,
) -> Result<Vec<u8>> {
let request = local_policy_request(identity, signer.ecid, args)?;
let body = plist::encode_xml(&request, plist::Limits::default())?;
send(signer, &request)
}
fn send(signer: &mut Signer, request: &Value) -> Result<Vec<u8>> {
let body = plist::encode_xml(request, plist::Limits::default())?;
let response = signer.transport.post(HOST, PATH, CONTENT_TYPE, &body)?;
ticket(&response)
}
@@ -227,6 +471,185 @@ mod tests {
assert!(local_policy_request(store.identity(), 0, &args()).is_err());
}
fn nonces() -> Nonces {
Nonces {
ap: [0xa5; 32],
sep: [0x5a; 20],
}
}
/// An identity with one component of each kind libtatsu treats apart.
fn root_identity() -> Identity {
let rule = |conditions: Value, actions: Value| {
Value::dict([("Conditions", conditions), ("Actions", actions)])
};
let trusted = |info: Value, digest: Option<u8>| {
let mut entry = Value::dict([("Info", info), ("Trusted", Value::Boolean(true))]);
if let (Value::Dict(fields), Some(byte)) = (&mut entry, digest) {
fields.insert("Digest".into(), Value::Data(vec![byte; 48]));
}
entry
};
let rules = Value::dict([(
"RestoreRequestRules",
Value::Array(vec![
rule(
Value::dict([
("ApRawProductionMode", Value::Boolean(true)),
("ApRequiresImage4", Value::Boolean(true)),
]),
Value::dict([("EPRO", Value::Boolean(true))]),
),
rule(
Value::dict([("ApInRomDFU", Value::Boolean(true))]),
Value::dict([("ESEC", Value::Boolean(false))]),
),
]),
)]);
let manifest = Value::dict([
("KernelCache", trusted(rules, Some(1))),
("ftap", trusted(Value::dict([]), Some(2))),
("SEP", trusted(Value::dict([]), None)),
("BaseSystem", trusted(Value::dict([]), Some(3))),
("Logo", Value::dict([("Info", Value::dict([]))])),
("NoInfo", Value::dict([("Trusted", Value::Boolean(true))])),
]);
Identity {
index: 20,
value: Value::dict([
("ApChipID", Value::from("0x8112")),
("ApBoardID", Value::from("0x24")),
("ApSecurityDomain", Value::from("0x01")),
("UniqueBuildID", Value::Data(vec![0x12; 8])),
("Ap,ProductType", Value::from("Mac14,3")),
("Manifest", manifest),
]),
}
}
#[test]
fn the_ap_request_carries_libtatsus_tags_and_applies_the_rules() {
let request = root_ticket_request(&root_identity(), 0x77, &nonces(), Root::Ap).unwrap();
let Value::Dict(fields) = &request else {
panic!()
};
let keys: Vec<_> = fields.keys().map(String::as_str).collect();
assert_eq!(
keys,
[
"@ApImg4Ticket",
"@HostPlatformInfo",
"@UUID",
"@VersionInfo",
"Ap,ProductType",
"ApBoardID",
"ApChipID",
"ApECID",
"ApNonce",
"ApProductionMode",
"ApSecurityDomain",
"ApSecurityMode",
"KernelCache",
"SEP",
"SepNonce",
"UniqueBuildID",
"ftap",
]
);
let kernel = request.required("KernelCache").unwrap();
assert_eq!(kernel.get("EPRO"), Some(&Value::Boolean(true)));
assert_eq!(kernel.get("ESEC"), None);
assert!(kernel.get("Info").is_none());
let ftap = request.required("ftap").unwrap();
assert_eq!(ftap.get("ESEC"), Some(&Value::Boolean(true)));
assert_eq!(ftap.required("Digest").unwrap().data().unwrap(), [2; 48]);
let sep = request.required("SEP").unwrap();
assert_eq!(sep.required("Digest").unwrap().data().unwrap(), b"");
assert_eq!(
request.required("ApNonce").unwrap().data().unwrap(),
nonces().ap
);
assert_eq!(
request.required("ApChipID").unwrap().uint().unwrap(),
0x8112
);
assert!(root_ticket_request(&root_identity(), 0, &nonces(), Root::Ap).is_err());
}
#[test]
fn the_recovery_request_leaves_out_restore_only_components() {
let request =
root_ticket_request(&root_identity(), 0x77, &nonces(), Root::RecoveryOs).unwrap();
for absent in ["ftap", "SEP", "BaseSystem", "NoInfo"] {
assert!(request.get(absent).is_none(), "{absent}");
}
// Without the AP request's defaults, an untrusted entry is sent empty.
assert_eq!(request.get("Logo"), Some(&Value::dict([])));
let kernel = request.required("KernelCache").unwrap();
assert_eq!(kernel.get("EPRO"), Some(&Value::Boolean(true)));
}
struct Signing {
posts: alloc::rc::Rc<core::cell::Cell<usize>>,
nonces: Nonces,
}
impl Transport for Signing {
fn post(&mut self, _: &str, _: &str, _: &str, body: &[u8]) -> Result<Vec<u8>> {
self.posts.set(self.posts.get() + 1);
let request = plist::decode(body, plist::Limits::default())?;
assert_eq!(request.required("ApNonce")?.data()?, nonces().ap);
let ticket = super::super::ticket::tests::bound_ticket(
b"krnl",
b"k",
Some(request.required("ApECID")?.uint()?),
Some(&self.nonces),
);
let answer = Value::dict([("ApImg4Ticket", Value::Data(ticket))]);
let mut response = b"STATUS=0&MESSAGE=SUCCESS&REQUEST_STRING=".to_vec();
response.extend(plist::encode_xml(&answer, plist::Limits::default())?);
Ok(response)
}
}
#[test]
fn the_root_ticket_is_apples_personalized_one_asked_once() {
use super::super::answers::{Answers, Plan};
let store = super::super::store::tests::fixture(b"x", false);
let mut answers = Answers::new(store);
let posts = alloc::rc::Rc::new(core::cell::Cell::new(0));
answers.signer = Some(Signer {
ecid: 0x77,
nonces: nonces(),
transport: alloc::boxed::Box::new(Signing {
posts: posts.clone(),
nonces: nonces(),
}),
});
let request = Value::dict([("DataType", Value::from("RootTicket"))]);
for _ in 0..2 {
let Plan::Reply(reply) = answers.plan(&request).unwrap() else {
panic!()
};
let ticket = reply.required("RootTicketData").unwrap().data().unwrap();
assert!(ticket.windows(4).any(|w| w == b"BNCH"));
}
assert_eq!(posts.get(), 1);
// A ticket bound to nonces this restore never sent refuses.
let mut answers = Answers::new(super::super::store::tests::fixture(b"x", false));
answers.signer = Some(Signer {
ecid: 0x77,
nonces: nonces(),
transport: alloc::boxed::Box::new(Signing {
posts,
nonces: Nonces {
sep: [0; 20],
..nonces()
},
}),
});
assert!(answers.plan(&request).is_err());
}
#[test]
fn a_volume_uuid_must_be_canonical() {
assert!(volume_uuid("15C1EDB0A41443F89AF64E28F13D8956").is_err());
@@ -272,6 +695,7 @@ mod tests {
assert!(answers.plan(&request).is_err());
answers.signer = Some(Signer {
ecid: 0x77,
nonces: nonces(),
transport: alloc::boxed::Box::new(Apple {
sent: vec![],
ecid: 0x77,
@@ -286,6 +710,7 @@ mod tests {
assert!(parts.manifest.is_some());
answers.signer = Some(Signer {
ecid: 0x77,
nonces: nonces(),
transport: alloc::boxed::Box::new(Apple {
sent: vec![],
ecid: 0x78,
+5 -1
View File
@@ -88,7 +88,8 @@ pub struct RestoreDryRun {
#[arg(long, value_enum, default_value = "install")]
mode: Mode,
/// In the study, also answer signing-service requests from the
/// synthetic ticket, as `--tss` does (the install always does).
/// synthetic signing service, as `--tss` does (the install always does):
/// personalized root tickets and the recoveryOS LocalPolicy.
#[arg(long)]
tss: bool,
/// Check recorded hashes only on the blocks each request reads, as
@@ -619,10 +620,13 @@ impl RestoreDryRun {
ctx.number("ApSecurityDomain").context("ApSecurityDomain")?,
ECID,
);
let root = ctx.personalize(tss::NONCES)?;
answers.signer = Some(Signer {
ecid: ECID,
nonces: tss::NONCES,
transport: Box::new(tss::Synthetic {
ticket,
root,
requests: tss::REQUESTS.with(|r| r.clone()),
}),
});
+42 -4
View File
@@ -2,7 +2,10 @@
//! selected identity and its board's other identities, decoded with the
//! `plist` crate; IPSW members, read with the `zip` crate; and the global
//! tickets. Checks compare the host's answers against these.
use super::image4::{self, Im4m, Property};
use super::{
image4::{self, Im4m, Property},
tss,
};
use anyhow::{Context, Result, anyhow, bail, ensure};
use std::{
collections::{BTreeMap, BTreeSet, HashMap},
@@ -13,7 +16,7 @@ use std::{
rc::Rc,
};
use stela_cli::restore::archive;
use stela_runtime::payload::PayloadManifest;
use stela_runtime::{payload::PayloadManifest, restore::tss::Nonces};
/// Members read whole for comparison; larger ones are only streamed.
pub const SMALL: u64 = 96 << 20;
@@ -41,9 +44,13 @@ pub struct Ctx {
pub recovery: Option<(usize, plist::Dictionary)>,
pub inventory: PayloadManifest,
pub zip: BTreeMap<String, (u64, bool)>,
/// The IPSW's global AP ticket, or under `--tss` the synthetic signing
/// service's personalization of it ([`Ctx::personalize`]).
pub global: Option<Ticket>,
pub cryptex: Option<Ticket>,
pub ecid: u64,
/// The nonces the AP ticket binds, once personalized.
pub nonces: Option<Nonces>,
pub full: bool,
cache: HashMap<String, Rc<Vec<u8>>>,
}
@@ -112,6 +119,7 @@ impl Ctx {
global: None,
cryptex: None,
ecid,
nonces: None,
full,
cache: HashMap::new(),
};
@@ -282,6 +290,33 @@ impl Ctx {
}
bail!("{name}: the manifest digest covers no candidate type of {path}")
}
/// Replace the global AP ticket with the synthetic signing service's
/// personalization of it for this ECID and `nonces`: the root ticket a
/// `--tss` host serves and stitches.
pub fn personalize(&mut self, nonces: Nonces) -> Result<Vec<u8>> {
let global = self.global.as_mut().ok_or_else(|| anyhow!("no apticket"))?;
let bytes = tss::personalize(&global.manifest, self.ecid, &nonces);
global.manifest = image4::im4m(&bytes)?;
global.path = format!("the synthetic personalization of {}", global.path);
global.bytes = bytes.clone();
self.nonces = Some(nonces);
Ok(bytes)
}
/// An AP root ticket: personalized for this ECID and nonces once
/// [`Ctx::personalize`]d, else global.
pub fn check_root(&self, m: &Im4m) -> Result<()> {
let Some(nonces) = &self.nonces else {
return self.check_ticket(m, None);
};
self.check_ticket(m, Some(self.ecid))?;
for (tag, sent) in [("BNCH", &nonces.ap[..]), ("snon", &nonces.sep[..])] {
ensure!(
m.manp(tag) == Some(&Property::Data(sent.to_vec())),
"the root ticket's {tag} is not the restore's nonce"
);
}
Ok(())
}
/// A ticket for this board: chip, board and security domain match the
/// identity; a global one names no ECID or nonce.
pub fn check_ticket(&self, m: &Im4m, ecid: Option<u64>) -> Result<()> {
@@ -326,7 +361,10 @@ impl Ctx {
want.kind
);
let m = image4::im4m(ticket)?;
self.check_ticket(&m, None)?;
match name.starts_with("Cryptex1,") {
true => self.check_ticket(&m, None)?,
false => self.check_root(&m)?,
}
let digest = image4::sha384(payload);
ensure!(
m.covers(&kind, &digest),
@@ -335,7 +373,7 @@ impl Ctx {
let expected = self.ticket_for(name).map(|t| t.bytes.as_slice());
ensure!(
Some(ticket) == expected,
"the stitched ticket is not the IPSW's global ticket"
"the stitched ticket is not the AP or cryptex1 root ticket"
);
Ok(format!(
"IMG4 {kind}{} covered by the {}",
+1 -1
View File
@@ -408,7 +408,7 @@ pub fn answers(route: Route, ctx: &Ctx) -> Vec<Step> {
let global = ctx.global.as_ref().ok_or_else(|| anyhow!("no apticket"))?;
ensure!(t == global.bytes, "RootTicketData is not {}", global.path);
let m = image4::im4m(t)?;
ctx.check_ticket(&m, None)?;
ctx.check_root(&m)?;
let names = ctx.components(false);
let covered = names
.iter()
+81 -11
View File
@@ -1,11 +1,25 @@
//! A synthetic signing service for `--tss`: it records the request the
//! host would send to Apple and answers with an unsigned ticket naming the
//! dry run's ECID and covering the bare `lpol` policy. Nothing leaves the
//! machine; the ticket only exercises the host's request and stitching.
use super::{context::Ctx, image4};
//! dry run's ECID: for the recoveryOS LocalPolicy one covering the bare
//! `lpol` policy, for a root ticket the IPSW's global AP ticket personalized
//! with the dry run's nonces. Nothing leaves the machine; the tickets only
//! exercise the host's requests and stitching.
use super::{
context::Ctx,
image4::{self, Im4m, Property},
};
use anyhow::{Result, anyhow, ensure};
use std::{cell::RefCell, io::Cursor, rc::Rc};
use stela_runtime::restore::{Result as HostResult, tss::Transport};
use stela_runtime::restore::{
Result as HostResult,
tss::{Nonces, Transport},
};
/// The nonces the dry run's restore binds its root tickets to.
pub const NONCES: Nonces = Nonces {
ap: [0xa5; 32],
sep: [0x5a; 20],
};
/// idevicerestore's `lpol_file`: an IM4P typed `lpol`, version `1.0`, with
/// a one-byte zero payload, written out independently of `restore::tss`.
@@ -101,8 +115,51 @@ pub fn ticket(chip: u64, board: u64, domain: u64, ecid: u64) -> Vec<u8> {
}
/// The recorded requests and the response the synthetic service gives.
/// `global` as Apple personalizes it: its `MANP` with the device's `ECID`
/// and the restore's `BNCH` and `snon` added, every object unchanged.
pub fn personalize(global: &Im4m, ecid: u64, nonces: &Nonces) -> Vec<u8> {
let property = |key: &str, value: &Property| {
let tag = <[u8; 4]>::try_from(key.as_bytes()).unwrap();
let value = match value {
Property::Integer(n) => integer(*n),
Property::Data(d) => tlv(0x04, d),
Property::Boolean(b) => tlv(0x01, &[if *b { 0xff } else { 0 }]),
};
private(&tag, &value)
};
let mut objects = Vec::new();
for (tag, properties) in &global.entries {
let mut body: Vec<u8> = properties
.iter()
.map(|(key, value)| property(key, value))
.collect::<Vec<_>>()
.concat();
if tag == "MANP" {
body.extend(private(b"ECID", &integer(ecid)));
body.extend(private(b"BNCH", &tlv(0x04, &nonces.ap)));
body.extend(private(b"snon", &tlv(0x04, &nonces.sep)));
}
let tag = <[u8; 4]>::try_from(tag.as_bytes()).unwrap();
objects.extend(private(&tag, &tlv(0x31, &body)));
}
tlv(
0x30,
&[
tlv(0x16, b"IM4M"),
integer(0),
tlv(0x31, &private(b"MANB", &tlv(0x31, &objects))),
tlv(0x04, b"unsigned dry-run ticket"),
tlv(0x30, b""),
]
.concat(),
)
}
pub struct Synthetic {
/// The answer to a LocalPolicy request.
pub ticket: Vec<u8>,
/// The answer to a root ticket request.
pub root: Vec<u8>,
pub requests: Rc<RefCell<Vec<Vec<u8>>>>,
}
impl Transport for Synthetic {
@@ -110,11 +167,13 @@ impl Transport for Synthetic {
assert_eq!((host, path), ("gs.apple.com", "/TSS/controller?action=2"));
assert!(kind.starts_with("text/xml"));
self.requests.borrow_mut().push(body.to_vec());
let request = plist::Value::from_reader(Cursor::new(body)).unwrap();
let policy = request
.as_dictionary()
.is_some_and(|d| d.contains_key("Ap,LocalPolicy"));
let ticket = if policy { &self.ticket } else { &self.root };
let mut answer = plist::Dictionary::new();
answer.insert(
"ApImg4Ticket".into(),
plist::Value::Data(self.ticket.clone()),
);
answer.insert("ApImg4Ticket".into(), plist::Value::Data(ticket.clone()));
let mut xml = Vec::new();
plist::Value::Dictionary(answer)
.to_writer_xml(&mut xml)
@@ -132,9 +191,20 @@ thread_local! {
/// The host's `Ap,LocalPolicy` and the request it sent the service.
pub fn check_policy(ctx: &mut Ctx, reply: &plist::Dictionary) -> Result<String> {
let request = REQUESTS
.with(|r| r.borrow().last().cloned())
.ok_or_else(|| anyhow!("the host sent no TSS request"))?;
let request = plist::Value::from_reader(Cursor::new(request))?;
.with(|r| {
r.borrow()
.iter()
.rev()
.map(|body| plist::Value::from_reader(Cursor::new(body)))
.find(|request| {
request
.as_ref()
.ok()
.and_then(plist::Value::as_dictionary)
.is_some_and(|d| d.contains_key("Ap,LocalPolicy"))
})
})
.ok_or_else(|| anyhow!("the host sent no LocalPolicy TSS request"))??;
let r = request
.as_dictionary()
.ok_or_else(|| anyhow!("TSS request is not a dictionary"))?;