Skip to main content

iphone_cli/
ddi.rs

1//! The developer disk image. The accessibility, screen and input services iph
2//! uses come from it, and the phone forgets it when it restarts.
3//!
4//! iph does not ship Apple's image. It uses Xcode's copy when the Mac has one,
5//! and otherwise fetches the Cryptex variant once from the public
6//! DeveloperDiskImage repository (pinned commit, every file checked against
7//! its SHA-256) into its own folder. Apple's signing server personalizes it
8//! for the phone either way.
9//!
10//! The Cryptex route (`cryptexd` over the tunnel) is the one that works from
11//! iOS 17.4 on and is the only one for phones newer than the image's own
12//! device list (iPhone18,5 for Xcode 27.1's image).
13
14use std::path::{Path, PathBuf};
15
16use anyhow::{Context, Result, anyhow, bail};
17use idevice::services::cryptexd::{Cryptex1Assets, install_ddi, installed_ddi};
18use sha2::{Digest, Sha256};
19
20use crate::{device::conn::Tunnel, paths};
21
22const REPO_COMMIT: &str = "a1020f81b6429f5ce40408cbe21c690512b613b5";
23const REPO_DIR: &str = "PersonalizedImages/Xcode_iOS_DDI_Cryptex";
24
25/// The files of the Cryptex image at `REPO_COMMIT`, with their SHA-256.
26const FILES: [(&str, &str); 5] = [
27    ("BuildManifest.plist", "537391eb2f37e604fc693f422c1568af97220067853e663391ba3e8258569d6e"),
28    ("Image.dmg", "500d4139f7963650e6c796d950267ed38909e7d183ad26bba073257529bfe173"),
29    ("Image.dmg.cryptex_info", "0180ee20ce5daa7978fe38f24c742361726789ea6af82c3c1d2afc480734a531"),
30    ("Image.dmg.root_hash", "5f3281961396be5fe008e11641ffc25c7db24c11d3789ff0c4ff0fa6d47b94ca"),
31    ("Image.dmg.trustcache", "2719aa3f1c99245432512116fb8a56d55ec224c706e545772d4c17c1233ac475"),
32];
33
34/// Where Xcode keeps the image (macOS only).
35pub fn xcode_restore() -> Option<PathBuf> {
36    [
37        PathBuf::from("/Library/Developer/DeveloperDiskImages/iOS_DDI/Restore"),
38        paths::home().join("Library/Developer/DeveloperDiskImages/iOS_DDI/Restore"),
39    ]
40    .into_iter()
41    .find(|p| p.join("BuildManifest.plist").exists())
42}
43
44fn sha256_of(path: &Path) -> Result<String> {
45    let bytes = std::fs::read(path).with_context(|| format!("read {}", path.display()))?;
46    Ok(format!("{:x}", Sha256::digest(&bytes)))
47}
48
49fn cache_ok(dir: &Path) -> bool {
50    FILES
51        .iter()
52        .all(|(name, sum)| sha256_of(&dir.join(name)).is_ok_and(|s| s == *sum))
53}
54
55/// The fetched image's folder, fetching it first when it is missing or does
56/// not match. Uses the system's `curl` (macOS, and Windows 10 and later).
57pub async fn fetched() -> Result<PathBuf> {
58    let dir = paths::ddi_cache().join(&REPO_COMMIT[..12]);
59    if cache_ok(&dir) {
60        return Ok(dir);
61    }
62    paths::ensure_private_dir(&dir)?;
63    for (name, sum) in FILES {
64        let target = dir.join(name);
65        if sha256_of(&target).is_ok_and(|s| s == sum) {
66            continue;
67        }
68        let url = format!("https://raw.githubusercontent.com/doronz88/DeveloperDiskImage/{REPO_COMMIT}/{REPO_DIR}/{name}");
69        let partial = dir.join(format!("{name}.part"));
70        let status = tokio::process::Command::new("curl")
71            .args(["-fsSL", "--retry", "2", "-o"])
72            .arg(&partial)
73            .arg(&url)
74            .status()
75            .await
76            .context("run curl")?;
77        if !status.success() {
78            bail!("download {name} failed ({status})");
79        }
80        let got = sha256_of(&partial)?;
81        if got != sum {
82            let _ = std::fs::remove_file(&partial);
83            bail!("{name}: checksum {got} does not match {sum}");
84        }
85        std::fs::rename(&partial, &target)?;
86    }
87    Ok(dir)
88}
89
90/// Install the image through `cryptexd`. Returns where the image came from.
91pub async fn install(tunnel: &mut Tunnel) -> Result<String> {
92    let mut adapter = tunnel.adapter.clone();
93    if installed_ddi(&mut adapter, &mut tunnel.rsd).await.ok().flatten().is_some() {
94        return Ok("already installed".into());
95    }
96    // Xcode's copy first; it is the same image when Xcode is current.
97    let mut errors = Vec::new();
98    let mut sources = Vec::new();
99    if let Some(dir) = xcode_restore() {
100        sources.push(("Xcode", dir));
101    }
102    match fetched().await {
103        Ok(dir) => sources.push(("DeveloperDiskImage repository", dir)),
104        Err(e) => errors.push(format!("fetch: {e:#}")),
105    }
106    for (label, dir) in sources {
107        let assets = match Cryptex1Assets::load(&dir).await {
108            Ok(a) => a,
109            Err(e) => {
110                errors.push(format!("{label}: {e:?}"));
111                continue;
112            }
113        };
114        let mut adapter = tunnel.adapter.clone();
115        match install_ddi(&mut adapter, &mut tunnel.rsd, &assets).await {
116            Ok(_) => return Ok(label.to_string()),
117            Err(e) => errors.push(format!("{label}: {e:?}")),
118        }
119    }
120    Err(anyhow!(errors.join("; ")))
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    /// Network: fetches about 18 MB. `cargo test ddi -- --ignored`.
128    #[tokio::test]
129    #[ignore]
130    async fn fetch_and_load() {
131        let dir = std::env::temp_dir().join(format!("iph-ddi-{}", std::process::id()));
132        unsafe { std::env::set_var("IPH_STATE_DIR", &dir) };
133        let restore = fetched().await.unwrap();
134        assert!(cache_ok(&restore));
135        let assets = Cryptex1Assets::load(&restore).await.unwrap();
136        assert!(assets.image.len() > 1_000_000);
137        // A second call finds the cache and downloads nothing.
138        assert_eq!(fetched().await.unwrap(), restore);
139        std::fs::remove_dir_all(&dir).unwrap();
140    }
141}