Skip to main content

idevice/services/
lockdown.rs

1//! iOS Lockdown Service Client
2//!
3//! Provides functionality for interacting with the lockdown service on iOS devices,
4//! which is the primary service for device management and service discovery.
5
6use plist::Value;
7use tracing::error;
8
9use crate::{Idevice, IdeviceError, IdeviceService, obf, pairing_file};
10
11/// Client for interacting with the iOS lockdown service
12///
13/// This is the primary service for device management and provides:
14/// - Access to device information and settings
15/// - Service discovery and port allocation
16/// - Session management and security
17#[derive(Debug)]
18pub struct LockdownClient {
19    /// The underlying device connection with established lockdown service
20    pub idevice: crate::Idevice,
21    pub session_id: Option<String>,
22}
23
24#[cfg(feature = "rsd")]
25impl crate::RsdService for LockdownClient {
26    fn rsd_service_name() -> std::borrow::Cow<'static, str> {
27        crate::obf!("com.apple.mobile.lockdown.remote.trusted")
28    }
29    async fn from_stream(stream: Box<dyn crate::ReadWrite>) -> Result<Self, crate::IdeviceError> {
30        let mut idevice = crate::Idevice::new(stream, "");
31        idevice.rsd_checkin().await?;
32        Ok(Self::new(idevice))
33    }
34}
35
36impl IdeviceService for LockdownClient {
37    /// Returns the lockdown service name as registered with the device
38    fn service_name() -> std::borrow::Cow<'static, str> {
39        obf!("com.apple.mobile.lockdown")
40    }
41
42    /// Establishes a connection to the lockdown service
43    ///
44    /// # Arguments
45    /// * `provider` - Device connection provider
46    ///
47    /// # Returns
48    /// A connected `LockdownClient` instance
49    ///
50    /// # Errors
51    /// Returns `IdeviceError` if connection fails
52    async fn connect(
53        provider: &dyn crate::provider::IdeviceProvider,
54    ) -> Result<Self, IdeviceError> {
55        let idevice = provider.connect(Self::LOCKDOWND_PORT).await?;
56        Ok(Self::new(idevice))
57    }
58
59    async fn from_stream(idevice: Idevice) -> Result<Self, crate::IdeviceError> {
60        Ok(Self::new(idevice))
61    }
62}
63
64impl LockdownClient {
65    /// The default TCP port for the lockdown service
66    pub const LOCKDOWND_PORT: u16 = 62078;
67
68    /// Creates a new lockdown client from an existing device connection
69    ///
70    /// # Arguments
71    /// * `idevice` - Pre-established device connection
72    pub fn new(idevice: Idevice) -> Self {
73        Self {
74            idevice,
75            session_id: None,
76        }
77    }
78
79    /// Retrieves a specific value from the device
80    ///
81    /// # Arguments
82    /// * `value` - The name of the value to retrieve (e.g., "DeviceName")
83    ///
84    /// # Returns
85    /// The requested value as a plist Value
86    ///
87    /// # Errors
88    /// Returns `IdeviceError` if:
89    /// - Communication fails
90    /// - The requested value doesn't exist
91    /// - The response is malformed
92    ///
93    /// # Example
94    /// ```rust
95    /// let device_name = client.get_value("DeviceName").await?;
96    /// println!("Device name: {:?}", device_name);
97    /// ```
98    pub async fn get_value(
99        &mut self,
100        key: Option<&str>,
101        domain: Option<&str>,
102    ) -> Result<Value, IdeviceError> {
103        let request = crate::plist!({
104            "Label": self.idevice.label.clone(),
105            "Request": "GetValue",
106            "Key":? key,
107            "Domain":? domain
108        });
109        self.idevice.send_plist(request).await?;
110        let message: plist::Dictionary = self.idevice.read_plist().await?;
111        match message.get("Value") {
112            Some(m) => Ok(m.to_owned()),
113            None => Err(IdeviceError::UnexpectedResponse(
114                "missing Value in GetValue response".into(),
115            )),
116        }
117    }
118
119    /// Sets a value on the device
120    ///
121    /// # Arguments
122    /// * `key` - The key to set
123    /// * `value` - The plist value to set
124    /// * `domain` - An optional domain to set by
125    ///
126    /// # Errors
127    /// Returns `IdeviceError` if:
128    /// - Communication fails
129    /// - The response is malformed
130    ///
131    /// # Example
132    /// ```rust
133    /// client.set_value("EnableWifiDebugging", true.into(), Some("com.apple.mobile.wireless_lockdown".to_string())).await?;
134    /// ```
135    pub async fn set_value(
136        &mut self,
137        key: impl Into<String>,
138        value: Value,
139        domain: Option<&str>,
140    ) -> Result<(), IdeviceError> {
141        let key = key.into();
142
143        let req = crate::plist!({
144            "Label": self.idevice.label.clone(),
145            "Request": "SetValue",
146            "Key": key,
147            "Value": value,
148            "Domain":? domain
149        });
150
151        self.idevice.send_plist(req).await?;
152        self.idevice.read_plist().await?;
153
154        Ok(())
155    }
156
157    /// Removes a value on the device
158    ///
159    /// Sends a lockdown `RemoveValue` request. Wire format matches Apple's
160    /// `AMDeviceRemoveValue`: `{ "Request": "RemoveValue", "Domain"?: domain, "Key": key }`.
161    ///
162    /// # Arguments
163    /// * `key` - The key to remove
164    /// * `domain` - An optional domain to remove from
165    ///
166    /// # Errors
167    /// Returns `IdeviceError` if communication fails or the device replies with an `Error`
168    pub async fn remove_value(
169        &mut self,
170        key: impl Into<String>,
171        domain: Option<&str>,
172    ) -> Result<(), IdeviceError> {
173        let key = key.into();
174
175        let req = crate::plist!({
176            "Label": self.idevice.label.clone(),
177            "Request": "RemoveValue",
178            "Key": key,
179            "Domain":? domain
180        });
181
182        self.idevice.send_plist(req).await?;
183        let response: plist::Dictionary = self.idevice.read_plist().await?;
184        if let Some(plist::Value::String(e)) = response.get("Error") {
185            return Err(IdeviceError::UnexpectedResponse(format!(
186                "RemoveValue failed: {e}"
187            )));
188        }
189
190        Ok(())
191    }
192
193    /// Unpairs the host from the device
194    ///
195    /// Sends a lockdown `Unpair` request carrying the host pair-record identity.
196    ///
197    /// Note this only removes the pairing from the device side. The host-side pairing record
198    /// (stored by usbmuxd) should be removed separately via
199    /// [`crate::usbmuxd::UsbmuxdConnection::delete_pair_record`].
200    ///
201    /// # Arguments
202    /// * `host_id` - The `HostID` from the pairing record (see
203    ///   [`crate::pairing_file::PairingFile::host_id`])
204    ///
205    /// # Errors
206    /// Returns `IdeviceError` if communication fails or the device replies with an `Error`.
207    pub async fn unpair(&mut self, host_id: impl Into<String>) -> Result<(), IdeviceError> {
208        let host_id = host_id.into();
209
210        let req = crate::plist!({
211            "Label": self.idevice.label.clone(),
212            "Request": "Unpair",
213            "PairRecord": {
214                "HostID": host_id
215            }
216        });
217
218        self.idevice.send_plist(req).await?;
219        let response: plist::Dictionary = self.idevice.read_plist().await?;
220        if let Some(plist::Value::String(e)) = response.get("Error") {
221            return Err(IdeviceError::UnexpectedResponse(format!(
222                "Unpair failed: {e}"
223            )));
224        }
225
226        Ok(())
227    }
228
229    /// Starts a secure TLS session with the device
230    ///
231    /// # Arguments
232    /// * `pairing_file` - Contains the device's identity and certificates
233    ///
234    /// # Returns
235    /// `Ok(legacy)` on successful session establishment, where `legacy` indicates
236    /// whether the device is running iOS < 5 and requires legacy TLS settings
237    ///
238    /// # Errors
239    /// Returns `IdeviceError` if:
240    /// - No connection is established
241    /// - The session request is denied
242    /// - TLS handshake fails
243    pub async fn start_session(
244        &mut self,
245        pairing_file: &pairing_file::PairingFile,
246    ) -> Result<bool, IdeviceError> {
247        if self.idevice.socket.is_none() {
248            return Err(IdeviceError::NoEstablishedConnection);
249        }
250
251        let legacy = self
252            .get_value(Some("ProductVersion"), None)
253            .await
254            .ok()
255            .as_ref()
256            .and_then(|x| x.as_string())
257            .and_then(|x| x.split(".").next())
258            .and_then(|x| x.parse::<u8>().ok())
259            .map(|x| x < 5)
260            .unwrap_or(false);
261
262        let request = crate::plist!({
263            "Label": self.idevice.label.clone(),
264            "Request": "StartSession",
265            "HostID": pairing_file.host_id.clone(),
266            "SystemBUID": pairing_file.system_buid.clone()
267
268        });
269        self.idevice.send_plist(request).await?;
270
271        let response = self.idevice.read_plist().await?;
272        match response.get("EnableSessionSSL") {
273            Some(plist::Value::Boolean(enable)) => {
274                if !enable {
275                    return Err(IdeviceError::UnexpectedResponse(
276                        "EnableSessionSSL is false in StartSession response".into(),
277                    ));
278                }
279            }
280            _ => {
281                return Err(IdeviceError::UnexpectedResponse(
282                    "missing EnableSessionSSL in StartSession response".into(),
283                ));
284            }
285        }
286
287        // Capture the SessionID so we can later formally StopSession (see `stop_session`).
288        self.session_id = response
289            .get("SessionID")
290            .and_then(|v| v.as_string())
291            .map(String::from);
292
293        self.idevice.start_session(pairing_file, legacy).await?;
294        Ok(legacy)
295    }
296
297    /// Stops the secure lockdown session previously started with [`start_session`](Self::start_session).
298    ///
299    /// Sends a lockdown `StopSession` request carrying the `SessionID` the device returned when the
300    /// session was started. Note this does NOT tear down the TLS socket in place, the caller is
301    /// expected to drop the connection.
302    ///
303    /// # Errors
304    /// Returns `IdeviceError` if communication fails or the device replies with an `Error`.
305    pub async fn stop_session(&mut self) -> Result<(), IdeviceError> {
306        let mut req = crate::plist!({
307            "Label": self.idevice.label.clone(),
308            "Request": "StopSession"
309        });
310        if let (Some(id), plist::Value::Dictionary(d)) = (&self.session_id, &mut req) {
311            d.insert("SessionID".into(), plist::Value::String(id.clone()));
312        }
313
314        self.idevice.send_plist(req).await?;
315        let response: plist::Dictionary = self.idevice.read_plist().await?;
316        if let Some(plist::Value::String(e)) = response.get("Error") {
317            return Err(IdeviceError::UnexpectedResponse(format!(
318                "StopSession failed: {e}"
319            )));
320        }
321
322        self.session_id = None;
323        Ok(())
324    }
325
326    /// Requests to start a service on the device
327    ///
328    /// # Arguments
329    /// * `identifier` - The service identifier (e.g., "com.apple.debugserver")
330    ///
331    /// # Returns
332    /// A tuple containing:
333    /// - The port number where the service is available
334    /// - A boolean indicating whether SSL should be used
335    ///
336    /// # Errors
337    /// Returns `IdeviceError` if:
338    /// - The service cannot be started
339    /// - The response is malformed
340    /// - The requested service doesn't exist
341    pub async fn start_service(
342        &mut self,
343        identifier: impl Into<String>,
344    ) -> Result<(u16, bool), IdeviceError> {
345        self.start_service_with_escrow(identifier, None).await
346    }
347
348    /// Requests to start a service, optionally presenting an escrow keybag so the device unlocks
349    /// its data protection for the service session.
350    ///
351    /// This mirrors Apple's `AMDeviceSecureStartService` with `UnlockEscrowBag = true`: the
352    /// `StartService` lockdown request gains an `EscrowBag` key. Without it the device leaves data
353    /// protection locked, so a service that must write protection-class files (mobilebackup2
354    /// restore of an *encrypted* backup, house_arrest) fails device-side with
355    /// "setting protection class (device locked?)" (MBErrorDomain 208). Non-protected data is
356    /// unaffected, which is why a non-encrypted restore succeeds without the escrow bag.
357    ///
358    /// # Arguments
359    /// * `identifier` - The service identifier (e.g., "com.apple.mobilebackup2")
360    /// * `escrow_bag` - The device's escrow keybag from the pairing record; `None` behaves exactly
361    ///   like [`start_service`](Self::start_service).
362    pub async fn start_service_with_escrow(
363        &mut self,
364        identifier: impl Into<String>,
365        escrow_bag: Option<Vec<u8>>,
366    ) -> Result<(u16, bool), IdeviceError> {
367        let identifier = identifier.into();
368        let mut req = crate::plist!({
369            "Request": "StartService",
370            "Service": identifier,
371        });
372        if let (Some(bag), plist::Value::Dictionary(d)) = (escrow_bag, &mut req) {
373            d.insert("EscrowBag".into(), plist::Value::Data(bag));
374        }
375        self.idevice.send_plist(req).await?;
376        let response = self.idevice.read_plist().await?;
377
378        let ssl = match response.get("EnableServiceSSL") {
379            Some(plist::Value::Boolean(ssl)) => ssl.to_owned(),
380            _ => false, // over USB, this option won't exist
381        };
382
383        match response.get("Port") {
384            Some(plist::Value::Integer(port)) => {
385                if let Some(port) = port.as_unsigned() {
386                    Ok((port as u16, ssl))
387                } else {
388                    error!("Port isn't an unsigned integer!");
389                    Err(IdeviceError::UnexpectedResponse(
390                        "Port is not an unsigned integer in StartService response".into(),
391                    ))
392                }
393            }
394            _ => {
395                error!("Response didn't contain an integer port");
396                Err(IdeviceError::UnexpectedResponse(
397                    "missing Port in StartService response".into(),
398                ))
399            }
400        }
401    }
402
403    /// Generates a pairing file and sends it to the device for trusting.
404    /// Note that this does NOT save the file to usbmuxd's cache. That's a responsibility of the
405    /// caller.
406    /// Note that this function is computationally heavy in a debug build.
407    ///
408    /// # Arguments
409    /// * `host_id` - The host ID, in the form of a UUID. Typically generated from the host name
410    /// * `system_buid` - UUID fetched from usbmuxd. Doesn't appear to affect function.
411    ///
412    /// # Returns
413    /// The newly generated pairing record
414    ///
415    /// # Errors
416    /// Returns `IdeviceError`
417    #[cfg(feature = "pair")]
418    pub async fn pair(
419        &mut self,
420        host_id: impl Into<String>,
421        system_buid: impl Into<String>,
422        host_name: Option<&str>,
423    ) -> Result<crate::pairing_file::PairingFile, IdeviceError> {
424        let host_id = host_id.into();
425        let system_buid = system_buid.into();
426
427        let (req, mut pair_record, private_key) = self
428            .build_pair_request(&host_id, &system_buid, host_name)
429            .await?;
430
431        loop {
432            self.idevice.send_plist(req.clone()).await?;
433            match self.idevice.read_plist().await {
434                Ok(escrow) => {
435                    pair_record.insert(
436                        "HostPrivateKey".into(),
437                        plist::Value::Data(private_key.clone()),
438                    );
439                    if let Some(escrow) = escrow.get("EscrowBag").and_then(|x| x.as_data()) {
440                        pair_record.insert("EscrowBag".into(), plist::Value::Data(escrow.to_vec()));
441                    }
442
443                    let p = crate::pairing_file::PairingFile::from_value(
444                        &plist::Value::Dictionary(pair_record),
445                    )?;
446
447                    break Ok(p);
448                }
449                Err(IdeviceError::PairingDialogResponsePending) => {
450                    crate::time::sleep(std::time::Duration::from_secs(1)).await;
451                }
452                Err(e) => break Err(e),
453            }
454        }
455    }
456
457    /// Builds the lockdown `Pair` request and the accompanying host pair record.
458    ///
459    /// This fetches the device public key and WiFi MAC, generates the pairing certificates, and
460    /// assembles the pair record (WITHOUT `HostPrivateKey`, which is inserted only after the device
461    /// accepts the pairing) plus the outgoing request.
462    ///
463    /// # Returns
464    /// A tuple of `(request, pair_record_without_host_private_key, ca_private_key)`.
465    #[cfg(feature = "pair")]
466    async fn build_pair_request(
467        &mut self,
468        host_id: &str,
469        system_buid: &str,
470        host_name: Option<&str>,
471    ) -> Result<(plist::Value, plist::Dictionary, Vec<u8>), IdeviceError> {
472        let pub_key = self.get_value(Some("DevicePublicKey"), None).await?;
473        let pub_key = match pub_key.as_data().map(|x| x.to_vec()) {
474            Some(p) => p,
475            None => {
476                tracing::warn!("Did not get public key data response");
477                return Err(IdeviceError::UnexpectedResponse(
478                    "missing DevicePublicKey data in pair response".into(),
479                ));
480            }
481        };
482
483        let wifi_mac = self.get_value(Some("WiFiAddress"), None).await?;
484        let wifi_mac = match wifi_mac.as_string() {
485            Some(w) => w,
486            None => {
487                tracing::warn!("Did not get WiFiAddress string");
488                return Err(IdeviceError::UnexpectedResponse(
489                    "missing WiFiAddress string in pair response".into(),
490                ));
491            }
492        };
493
494        let ca = crate::ca::generate_certificates(&pub_key, None).unwrap();
495        let pair_record = crate::plist!(dict {
496            "DevicePublicKey": pub_key,
497            "DeviceCertificate": ca.dev_cert,
498            "HostCertificate": ca.host_cert.clone(),
499            "HostID": host_id,
500            "RootCertificate": ca.host_cert,
501            "RootPrivateKey": ca.private_key.clone(),
502            "WiFiMACAddress": wifi_mac,
503            "SystemBUID": system_buid,
504        });
505
506        let req = crate::plist!({
507            "Label": self.idevice.label.clone(),
508            "Request": "Pair",
509            "HostName":? host_name,
510            "PairRecord": pair_record.clone(),
511            "ProtocolVersion": "2",
512            "PairingOptions": {
513                "ExtendedPairingErrors": true
514            }
515        });
516
517        Ok((req, pair_record, ca.private_key))
518    }
519
520    /// Attempts to pair with the device exactly ONCE, without looping or sleeping.
521    ///
522    /// Unlike [`LockdownClient::pair`], this does NOT block on
523    /// [`IdeviceError::PairingDialogResponsePending`]: the pending/denied/password-protected
524    /// errors are propagated directly to the caller so it can drive its own retry/UI flow (e.g.
525    /// showing a "Trust This Computer" prompt). The lockdown "Error" field is mapped to the
526    /// corresponding [`IdeviceError`] variant by `read_plist`.
527    ///
528    /// Note that this does NOT save the file to usbmuxd's cache. That's a responsibility of the
529    /// caller.
530    ///
531    /// # Arguments
532    /// * `host_id` - The host ID, in the form of a UUID. Typically generated from the host name
533    /// * `system_buid` - UUID fetched from usbmuxd. Doesn't appear to affect function.
534    ///
535    /// # Returns
536    /// The newly generated pairing record on success.
537    ///
538    /// # Errors
539    /// Returns `IdeviceError`, including `PairingDialogResponsePending`, `UserDeniedPairing`, and
540    /// `PasswordProtected` surfaced directly from the device.
541    #[cfg(feature = "pair")]
542    pub async fn pair_once(
543        &mut self,
544        host_id: impl Into<String>,
545        system_buid: impl Into<String>,
546        host_name: Option<&str>,
547    ) -> Result<crate::pairing_file::PairingFile, IdeviceError> {
548        let host_id = host_id.into();
549        let system_buid = system_buid.into();
550
551        let (req, mut pair_record, private_key) = self
552            .build_pair_request(&host_id, &system_buid, host_name)
553            .await?;
554
555        self.idevice.send_plist(req).await?;
556        // Propagates Err(PairingDialogResponsePending)/UserDeniedPairing/PasswordProtected etc.
557        let escrow = self.idevice.read_plist().await?;
558
559        pair_record.insert("HostPrivateKey".into(), plist::Value::Data(private_key));
560        if let Some(escrow) = escrow.get("EscrowBag").and_then(|x| x.as_data()) {
561            pair_record.insert("EscrowBag".into(), plist::Value::Data(escrow.to_vec()));
562        }
563
564        crate::pairing_file::PairingFile::from_value(&plist::Value::Dictionary(pair_record))
565    }
566
567    /// Tell the device to enter recovery mode
568    pub async fn enter_recovery(&mut self) -> Result<(), IdeviceError> {
569        self.idevice
570            .send_plist(crate::plist!({
571                "Request": "EnterRecovery"
572            }))
573            .await?;
574
575        let res = self.idevice.read_plist().await?;
576
577        if res.get("Request").and_then(|x| x.as_string()) == Some("EnterRecovery") {
578            Ok(())
579        } else {
580            Err(IdeviceError::UnexpectedResponse(
581                "EnterRecovery request not acknowledged".into(),
582            ))
583        }
584    }
585}
586
587impl From<Idevice> for LockdownClient {
588    /// Converts an existing device connection into a lockdown client
589    fn from(value: Idevice) -> Self {
590        Self::new(value)
591    }
592}