idevice 0.1.65

A Rust library to interact with services on iOS devices.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
//! Ticket Signature Server (TSS) Client
//!
//! Provides functionality for interacting with Apple's TSS service to:
//! - Request personalized firmware components
//! - Apply restore request rules for device-specific parameters
//! - Handle cryptographic signing operations

use plist::Value;
use plist_macro::plist_to_xml_bytes;
use tracing::{debug, warn};

use crate::IdeviceError;

/// TSS client version string sent in requests
const TSS_CLIENT_VERSION_STRING: &str = "libauthinstall-1033.0.2";
/// Apple's TSS endpoint URL
const TSS_CONTROLLER_ACTION_URL: &str = "http://gs.apple.com/TSS/controller?action=2";

/// Represents a TSS request to Apple's signing server
#[derive(Debug)]
pub struct TSSRequest {
    /// The underlying plist dictionary containing request parameters
    inner: plist::Dictionary,
}

impl TSSRequest {
    /// Creates a new TSS request with default headers
    ///
    /// Initializes with:
    /// - Host platform info
    /// - Client version string
    /// - Random UUID for request identification
    pub fn new() -> Self {
        let inner = plist_macro::plist!(dict {
            "@HostPlatformInfo": "mac",
            "@VersionInfo": TSS_CLIENT_VERSION_STRING,
            "@UUID": uuid::Uuid::new_v4().to_string().to_uppercase()
        });
        Self { inner }
    }

    /// Inserts a key-value pair into the TSS request
    ///
    /// # Arguments
    /// * `key` - The parameter name
    /// * `val` - The parameter value (will be converted to plist::Value)
    pub fn insert(&mut self, key: impl Into<String>, val: impl Into<Value>) {
        let key = key.into();
        let val = val.into();
        self.inner.insert(key, val);
    }

    /// Sends the TSS request to Apple's servers
    ///
    /// # Returns
    /// The parsed plist response from Apple
    ///
    /// # Errors
    /// Returns `IdeviceError` if:
    /// - The request fails
    /// - The response is malformed
    /// - Apple returns a non-success status
    ///
    /// # Example
    /// ```rust
    /// let mut request = TSSRequest::new();
    /// request.insert("ApBoardID", board_id);
    /// request.insert("ApChipID", chip_id);
    /// let response = request.send().await?;
    /// ```
    pub async fn send(&self) -> Result<plist::Value, IdeviceError> {
        debug!(
            "Sending TSS request: {}",
            crate::pretty_print_dictionary(&self.inner)
        );
        let client = reqwest::Client::new();

        let res = client
            .post(TSS_CONTROLLER_ACTION_URL)
            .header("Cache-Control", "no-cache")
            .header("Content-type", "text/xml; charset=\"utf-8\"")
            .header("User-Agent", "InetURL/1.0")
            .body(plist_to_xml_bytes(&self.inner))
            .send()
            .await?
            .text()
            .await?;

        debug!("Apple responded with {res}");
        let trimmed = res.trim_start_matches("STATUS=0&");
        let trimmed = trimmed.trim_start_matches("MESSAGE=");
        if !trimmed.starts_with("SUCCESS") {
            // On failure Apple returns `STATUS=<n>&MESSAGE=<text>` (no
            // REQUEST_STRING); surface it so the caller sees why it was rejected.
            let detail = res
                .split("&REQUEST_STRING=")
                .next()
                .unwrap_or(res.as_str())
                .trim();
            warn!("TSS responded with non-success value: {detail}");
            return Err(IdeviceError::UnexpectedResponse(format!(
                "TSS server responded with non-success status ({detail})"
            )));
        }
        let res = res.split("REQUEST_STRING=").collect::<Vec<&str>>();
        if res.len() < 2 {
            warn!("Response didn't contain a request string");
            return Err(IdeviceError::UnexpectedResponse(
                "TSS response missing REQUEST_STRING".into(),
            ));
        }
        Ok(plist::from_bytes(res[1].as_bytes())?)
    }

    /// Sets the `@ApImg4Ticket` request flag.
    ///
    /// When true, the server returns a signed IMG4 manifest (`ApImg4Ticket`).
    pub fn set_ap_img4_ticket(&mut self, value: bool) {
        self.insert("@ApImg4Ticket", value);
    }

    /// Sets the `@BBTicket` request flag (request a baseband ticket).
    pub fn set_bb_ticket(&mut self, value: bool) {
        self.insert("@BBTicket", value);
    }

    /// Adds the common `Ap*` identity tags shared by the developer-disk-image
    /// personalization flow and the full IPSW restore flow.
    ///
    /// Sets `ApBoardID`, `ApChipID`, `ApECID`, `ApProductionMode` (true),
    /// `ApSecurityDomain` (1), `ApSecurityMode` (true) and `UID_MODE` (false).
    /// `ap_nonce`/`sep_nonce`, when supplied, are inserted as `ApNonce`/`SepNonce`
    /// data blobs.
    pub fn add_common_tags(
        &mut self,
        board_id: u64,
        chip_id: u64,
        ecid: u64,
        ap_nonce: Option<Vec<u8>>,
        sep_nonce: Option<Vec<u8>>,
    ) {
        self.insert("ApBoardID", board_id);
        self.insert("ApChipID", chip_id);
        self.insert("ApECID", ecid);
        self.insert("ApProductionMode", true);
        self.insert("ApSecurityDomain", 1);
        self.insert("ApSecurityMode", true);
        self.insert("UID_MODE", false);
        if let Some(n) = ap_nonce {
            self.insert("ApNonce", plist::Value::Data(n));
        }
        if let Some(n) = sep_nonce {
            self.insert("SepNonce", plist::Value::Data(n));
        }
    }

    /// Removes a key from the request, returning the removed value if present.
    pub fn remove(&mut self, key: &str) -> Option<Value> {
        self.inner.remove(key)
    }

    pub fn add_build_identity_tags(&mut self, build_identity: &plist::Dictionary, keys: &[&str]) {
        for &key in keys {
            if let Some(v) = build_identity.get(key) {
                let converted = match v {
                    Value::String(s) if s.starts_with("0x") => {
                        match u64::from_str_radix(s.trim_start_matches("0x"), 16) {
                            Ok(n) => Value::from(n),
                            Err(_) => v.clone(),
                        }
                    }
                    _ => v.clone(),
                };
                self.insert(key, converted);
            }
        }
    }

    pub fn add_ap_personalization_identifiers(&mut self, identifiers: &plist::Dictionary) {
        for (key, val) in identifiers {
            if key.starts_with("Ap,") {
                self.insert(key.clone(), val.clone());
            }
        }
    }

    pub fn add_ap_tags(&mut self, build_identity: &plist::Dictionary) {
        const KEYS: &[&str] = &[
            "UniqueBuildID",
            "Ap,OSLongVersion",
            "Ap,OSReleaseType",
            "Ap,ProductType",
            "Ap,SDKPlatform",
            "Ap,SikaFuse",
            "Ap,Target",
            "Ap,TargetType",
            "Ap,ProductMarketingVersion",
            "ApBoardID",
            "ApChipID",
            "ApSecurityDomain",
            "BMU,BoardID",
            "BMU,ChipID",
            "BbChipID",
            "BbProvisioningManifestKeyHash",
            "BbActivationManifestKeyHash",
            "BbCalibrationManifestKeyHash",
            "BbFactoryActivationManifestKeyHash",
            "BbFDRSecurityKeyHash",
            "BbSkeyId",
            "SE,ChipID",
            "Savage,ChipID",
            "Savage,PatchEpoch",
            "Yonkers,BoardID",
            "Yonkers,ChipID",
            "Yonkers,PatchEpoch",
            "Rap,BoardID",
            "Rap,ChipID",
            "Rap,SecurityDomain",
            "Baobab,BoardID",
            "Baobab,ChipID",
            "Baobab,ManifestEpoch",
            "Baobab,SecurityDomain",
            "eUICC,ChipID",
            "PearlCertificationRootPub",
            "Timer,BoardID,1",
            "Timer,BoardID,2",
            "Timer,ChipID,1",
            "Timer,ChipID,2",
            "Timer,SecurityDomain,1",
            "Timer,SecurityDomain,2",
            "NeRDEpoch",
        ];
        for &key in KEYS {
            if let Some(v) = build_identity.get(key) {
                let converted = match v {
                    Value::String(s) if s.starts_with("0x") => {
                        match u64::from_str_radix(s.trim_start_matches("0x"), 16) {
                            Ok(n) => Value::from(n),
                            Err(_) => v.clone(),
                        }
                    }
                    _ => v.clone(),
                };
                self.insert(key, converted);
            }
        }

        if let Some(r) = build_identity
            .get("Info")
            .and_then(|i| i.as_dictionary())
            .and_then(|i| i.get("RequiresUIDMode"))
        {
            self.insert("RequiresUIDMode", r.clone());
        }
    }

    pub fn add_ap_manifest_tags(
        &mut self,
        build_identity: &plist::Dictionary,
        parameters: &plist::Dictionary,
    ) -> Result<(), IdeviceError> {
        const SKIP_KEYS: &[&str] = &[
            "BasebandFirmware",
            "SE,UpdatePayload",
            "BaseSystem",
            "Diags",
            "Ap,ExclaveOS",
        ];

        let manifest = match build_identity.get("Manifest") {
            Some(plist::Value::Dictionary(m)) => m,
            _ => return Err(IdeviceError::BadBuildManifest),
        };
        let supports_img4 = parameters
            .get("ApSupportsImg4")
            .and_then(Value::as_boolean)
            .unwrap_or(false);

        for (key, manifest_item) in manifest {
            if SKIP_KEYS.contains(&key.as_str()) || key.starts_with("Cryptex1,") {
                continue;
            }
            let manifest_item = match manifest_item {
                plist::Value::Dictionary(m) => m,
                _ => continue,
            };
            let info = match manifest_item.get("Info") {
                Some(plist::Value::Dictionary(i)) => i,
                _ => continue,
            };
            // For IMG4 devices, only components with RestoreRequestRules belong
            // in the AP ticket.
            let has_rules = info.contains_key("RestoreRequestRules");
            if supports_img4 && !has_rules {
                debug!("skipping {key}: no RestoreRequestRules");
                continue;
            }
            if info
                .get("IsFTAB")
                .and_then(Value::as_boolean)
                .unwrap_or(false)
            {
                continue;
            }

            let mut tss_entry = manifest_item.clone();
            tss_entry.remove("Info");

            if let Some(plist::Value::Array(rules)) = info.get("RestoreRequestRules") {
                apply_restore_request_rules(&mut tss_entry, parameters, rules);
            }

            let trusted = manifest_item
                .get("Trusted")
                .and_then(Value::as_boolean)
                .unwrap_or(false);
            if trusted && !tss_entry.contains_key("Digest") {
                tss_entry.insert("Digest".into(), plist::Value::Data(Vec::new()));
            }

            self.insert(key.clone(), tss_entry);
        }

        Ok(())
    }

    pub fn add_baseband_tags(&mut self, parameters: &plist::Dictionary) {
        self.insert("@BBTicket", true);

        const KEYS: &[&str] = &[
            "BbChipID",
            "BbProvisioningManifestKeyHash",
            "BbActivationManifestKeyHash",
            "BbCalibrationManifestKeyHash",
            "BbFactoryActivationManifestKeyHash",
            "BbFDRSecurityKeyHash",
            "BbSkeyId",
            "BbNonce",
            "BbGoldCertId",
            "BbSNUM",
            "PearlCertificationRootPub",
            "Ap,OSLongVersion",
        ];
        for &key in KEYS {
            if let Some(v) = parameters.get(key) {
                self.insert(key, v.clone());
            }
        }

        if let Some(bbfw) = parameters
            .get("Manifest")
            .and_then(|m| m.as_dictionary())
            .and_then(|m| m.get("BasebandFirmware"))
            .and_then(|b| b.as_dictionary())
        {
            let mut bbfwdict = bbfw.clone();
            bbfwdict.remove("Info");

            let bb_chip_id = parameters
                .get("BbChipID")
                .and_then(Value::as_unsigned_integer);
            let bb_cert_id = parameters
                .get("BbGoldCertId")
                .and_then(Value::as_unsigned_integer);
            if bb_chip_id == Some(0x68) {
                if matches!(bb_cert_id, Some(0x26F3_FACC | 0x5CF2_EC4E | 0x8399_785A)) {
                    bbfwdict.remove("PSI2-PartialDigest");
                    bbfwdict.remove("RestorePSI2-PartialDigest");
                } else {
                    bbfwdict.remove("PSI-PartialDigest");
                    bbfwdict.remove("RestorePSI-PartialDigest");
                }
            }
            self.insert("BasebandFirmware", Value::Dictionary(bbfwdict));
        }
    }

    pub fn populate_from_manifest(
        &mut self,
        build_identity: &plist::Dictionary,
        parameters: &plist::Dictionary,
        rules_override: Option<&[plist::Value]>,
    ) -> Result<(), IdeviceError> {
        let manifest = match build_identity.get("Manifest") {
            Some(plist::Value::Dictionary(m)) => m,
            _ => return Err(IdeviceError::BadBuildManifest),
        };

        for (key, manifest_item) in manifest {
            let manifest_item = match manifest_item {
                plist::Value::Dictionary(m) => m,
                _ => {
                    debug!("Manifest item {key} wasn't a dictionary");
                    continue;
                }
            };

            let info = match manifest_item.get("Info") {
                Some(plist::Value::Dictionary(i)) => i,
                _ => {
                    debug!("Manifest item {key} didn't contain Info");
                    continue;
                }
            };

            if !matches!(
                manifest_item.get("Trusted"),
                Some(plist::Value::Boolean(true))
            ) {
                debug!("Manifest item {key} isn't trusted");
                continue;
            }

            let mut tss_entry = manifest_item.clone();
            tss_entry.remove("Info");

            let rules = match rules_override {
                Some(r) => Some(r),
                None => info
                    .get("RestoreRequestRules")
                    .and_then(|v| v.as_array())
                    .map(|v| v.as_slice()),
            };
            if let Some(rules) = rules {
                apply_restore_request_rules(&mut tss_entry, parameters, rules);
            }

            if manifest_item.get("Digest").is_none() {
                tss_entry.insert("Digest".into(), plist::Value::Data(Vec::new()));
            }

            self.insert(key.clone(), tss_entry);
        }

        Ok(())
    }
}

impl Default for TSSRequest {
    /// Creates a default TSS request (same as `new()`)
    fn default() -> Self {
        Self::new()
    }
}

/// Applies restore request rules to modify input parameters
///
/// # Arguments
/// * `input` - The dictionary to modify based on rules
/// * `parameters` - Device parameters to check conditions against
/// * `rules` - List of rules to apply
///
/// # Process
/// For each rule:
/// 1. Checks all conditions against the parameters
/// 2. If all conditions are met, applies the rule's actions
/// 3. Actions can add, modify or remove parameters
pub fn apply_restore_request_rules(
    input: &mut plist::Dictionary,
    parameters: &plist::Dictionary,
    rules: &[plist::Value],
) {
    for rule in rules {
        if let plist::Value::Dictionary(rule) = rule {
            let conditions = match rule.get("Conditions") {
                Some(plist::Value::Dictionary(c)) => c,
                _ => {
                    warn!("Conditions doesn't exist or wasn't a dictionary!");
                    continue;
                }
            };

            let mut conditions_fulfilled = true;
            for (key, value) in conditions {
                let value2 = match key.as_str() {
                    "ApRawProductionMode" => parameters.get("ApProductionMode"),
                    "ApCurrentProductionMode" => parameters.get("ApProductionMode"),
                    "ApRawSecurityMode" => parameters.get("ApSecurityMode"),
                    "ApRequiresImage4" => parameters.get("ApSupportsImg4"),
                    "ApDemotionPolicyOverride" => parameters.get("DemotionPolicy"),
                    "ApInRomDFU" => parameters.get("ApInRomDFU"),
                    _ => {
                        warn!("Unhandled key {key}");
                        None
                    }
                };

                if value2.is_none() || value2 != Some(value) {
                    conditions_fulfilled = false;
                    break; // Stop checking other conditions immediately
                }
            }

            if !conditions_fulfilled {
                continue;
            }

            let actions = match rule.get("Actions") {
                Some(plist::Value::Dictionary(a)) => a,
                _ => {
                    warn!("Actions doesn't exist or wasn't a dictionary!");
                    continue;
                }
            };

            for (key, value) in actions {
                // Skip special values (255 typically means "ignore")
                if let Some(i) = value.as_unsigned_integer()
                    && i == 255
                {
                    continue;
                }
                if let Some(i) = value.as_signed_integer()
                    && i == 255
                {
                    continue;
                }

                input.remove(key); // Explicitly remove before inserting
                input.insert(key.to_owned(), value.to_owned());
            }
        } else {
            warn!("Rule wasn't a dictionary");
        }
    }
}

fn parse_hex_field(v: Option<&plist::Value>) -> Option<u64> {
    match v {
        Some(plist::Value::String(s)) => u64::from_str_radix(s.trim_start_matches("0x"), 16).ok(),
        Some(plist::Value::Integer(i)) => i.as_unsigned(),
        _ => None,
    }
}

pub fn select_build_identity<'a>(
    build_manifest: &'a plist::Dictionary,
    board_id: u64,
    chip_id: u64,
    restore_behavior: Option<&str>,
) -> Result<&'a plist::Dictionary, IdeviceError> {
    let identities = match build_manifest.get("BuildIdentities") {
        Some(plist::Value::Array(i)) => i,
        _ => return Err(IdeviceError::BadBuildManifest),
    };

    for id in identities {
        let id = match id {
            plist::Value::Dictionary(id) => id,
            _ => {
                debug!("build identity wasn't a dictionary");
                continue;
            }
        };

        if parse_hex_field(id.get("ApBoardID")) != Some(board_id) {
            continue;
        }
        if parse_hex_field(id.get("ApChipID")) != Some(chip_id) {
            continue;
        }
        if let Some(behavior) = restore_behavior {
            let matches = id
                .get("Info")
                .and_then(|i| i.as_dictionary())
                .and_then(|i| i.get("RestoreBehavior"))
                .and_then(|b| b.as_string())
                == Some(behavior);
            if !matches {
                continue;
            }
        }
        return Ok(id);
    }

    Err(IdeviceError::BadBuildManifest)
}

/// Extracts the `ApImg4Ticket` blob from a TSS response dictionary.
///
/// # Errors
/// Returns [`IdeviceError::UnexpectedResponse`] if the ticket is absent.
pub fn extract_img4_ticket(response: &plist::Dictionary) -> Result<Vec<u8>, IdeviceError> {
    match response.get("ApImg4Ticket") {
        Some(plist::Value::Data(d)) => Ok(d.clone()),
        _ => Err(IdeviceError::UnexpectedResponse(
            "missing ApImg4Ticket data in TSS response".into(),
        )),
    }
}