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
//! iOS Lockdown Service Client
//!
//! Provides functionality for interacting with the lockdown service on iOS devices,
//! which is the primary service for device management and service discovery.
use plist::Value;
use tracing::error;
use crate::{Idevice, IdeviceError, IdeviceService, obf, pairing_file};
/// Client for interacting with the iOS lockdown service
///
/// This is the primary service for device management and provides:
/// - Access to device information and settings
/// - Service discovery and port allocation
/// - Session management and security
#[derive(Debug)]
pub struct LockdownClient {
/// The underlying device connection with established lockdown service
pub idevice: crate::Idevice,
}
#[cfg(feature = "rsd")]
impl crate::RsdService for LockdownClient {
fn rsd_service_name() -> std::borrow::Cow<'static, str> {
crate::obf!("com.apple.mobile.lockdown.remote.trusted")
}
async fn from_stream(stream: Box<dyn crate::ReadWrite>) -> Result<Self, crate::IdeviceError> {
let mut idevice = crate::Idevice::new(stream, "");
idevice.rsd_checkin().await?;
Ok(Self::new(idevice))
}
}
impl IdeviceService for LockdownClient {
/// Returns the lockdown service name as registered with the device
fn service_name() -> std::borrow::Cow<'static, str> {
obf!("com.apple.mobile.lockdown")
}
/// Establishes a connection to the lockdown service
///
/// # Arguments
/// * `provider` - Device connection provider
///
/// # Returns
/// A connected `LockdownClient` instance
///
/// # Errors
/// Returns `IdeviceError` if connection fails
async fn connect(
provider: &dyn crate::provider::IdeviceProvider,
) -> Result<Self, IdeviceError> {
let idevice = provider.connect(Self::LOCKDOWND_PORT).await?;
Ok(Self::new(idevice))
}
async fn from_stream(idevice: Idevice) -> Result<Self, crate::IdeviceError> {
Ok(Self::new(idevice))
}
}
impl LockdownClient {
/// The default TCP port for the lockdown service
pub const LOCKDOWND_PORT: u16 = 62078;
/// Creates a new lockdown client from an existing device connection
///
/// # Arguments
/// * `idevice` - Pre-established device connection
pub fn new(idevice: Idevice) -> Self {
Self { idevice }
}
/// Retrieves a specific value from the device
///
/// # Arguments
/// * `value` - The name of the value to retrieve (e.g., "DeviceName")
///
/// # Returns
/// The requested value as a plist Value
///
/// # Errors
/// Returns `IdeviceError` if:
/// - Communication fails
/// - The requested value doesn't exist
/// - The response is malformed
///
/// # Example
/// ```rust
/// let device_name = client.get_value("DeviceName").await?;
/// println!("Device name: {:?}", device_name);
/// ```
pub async fn get_value(
&mut self,
key: Option<&str>,
domain: Option<&str>,
) -> Result<Value, IdeviceError> {
let request = crate::plist!({
"Label": self.idevice.label.clone(),
"Request": "GetValue",
"Key":? key,
"Domain":? domain
});
self.idevice.send_plist(request).await?;
let message: plist::Dictionary = self.idevice.read_plist().await?;
match message.get("Value") {
Some(m) => Ok(m.to_owned()),
None => Err(IdeviceError::UnexpectedResponse(
"missing Value in GetValue response".into(),
)),
}
}
/// Sets a value on the device
///
/// # Arguments
/// * `key` - The key to set
/// * `value` - The plist value to set
/// * `domain` - An optional domain to set by
///
/// # Errors
/// Returns `IdeviceError` if:
/// - Communication fails
/// - The response is malformed
///
/// # Example
/// ```rust
/// client.set_value("EnableWifiDebugging", true.into(), Some("com.apple.mobile.wireless_lockdown".to_string())).await?;
/// ```
pub async fn set_value(
&mut self,
key: impl Into<String>,
value: Value,
domain: Option<&str>,
) -> Result<(), IdeviceError> {
let key = key.into();
let req = crate::plist!({
"Label": self.idevice.label.clone(),
"Request": "SetValue",
"Key": key,
"Value": value,
"Domain":? domain
});
self.idevice.send_plist(req).await?;
self.idevice.read_plist().await?;
Ok(())
}
/// Starts a secure TLS session with the device
///
/// # Arguments
/// * `pairing_file` - Contains the device's identity and certificates
///
/// # Returns
/// `Ok(())` on successful session establishment
///
/// # Errors
/// Returns `IdeviceError` if:
/// - No connection is established
/// - The session request is denied
/// - TLS handshake fails
pub async fn start_session(
&mut self,
pairing_file: &pairing_file::PairingFile,
) -> Result<(), IdeviceError> {
if self.idevice.socket.is_none() {
return Err(IdeviceError::NoEstablishedConnection);
}
let legacy = self
.get_value(Some("ProductVersion"), None)
.await
.ok()
.as_ref()
.and_then(|x| x.as_string())
.and_then(|x| x.split(".").next())
.and_then(|x| x.parse::<u8>().ok())
.map(|x| x < 5)
.unwrap_or(false);
let request = crate::plist!({
"Label": self.idevice.label.clone(),
"Request": "StartSession",
"HostID": pairing_file.host_id.clone(),
"SystemBUID": pairing_file.system_buid.clone()
});
self.idevice.send_plist(request).await?;
let response = self.idevice.read_plist().await?;
match response.get("EnableSessionSSL") {
Some(plist::Value::Boolean(enable)) => {
if !enable {
return Err(IdeviceError::UnexpectedResponse(
"EnableSessionSSL is false in StartSession response".into(),
));
}
}
_ => {
return Err(IdeviceError::UnexpectedResponse(
"missing EnableSessionSSL in StartSession response".into(),
));
}
}
self.idevice.start_session(pairing_file, legacy).await?;
Ok(())
}
/// Requests to start a service on the device
///
/// # Arguments
/// * `identifier` - The service identifier (e.g., "com.apple.debugserver")
///
/// # Returns
/// A tuple containing:
/// - The port number where the service is available
/// - A boolean indicating whether SSL should be used
///
/// # Errors
/// Returns `IdeviceError` if:
/// - The service cannot be started
/// - The response is malformed
/// - The requested service doesn't exist
pub async fn start_service(
&mut self,
identifier: impl Into<String>,
) -> Result<(u16, bool), IdeviceError> {
let identifier = identifier.into();
let req = crate::plist!({
"Request": "StartService",
"Service": identifier,
});
self.idevice.send_plist(req).await?;
let response = self.idevice.read_plist().await?;
let ssl = match response.get("EnableServiceSSL") {
Some(plist::Value::Boolean(ssl)) => ssl.to_owned(),
_ => false, // over USB, this option won't exist
};
match response.get("Port") {
Some(plist::Value::Integer(port)) => {
if let Some(port) = port.as_unsigned() {
Ok((port as u16, ssl))
} else {
error!("Port isn't an unsigned integer!");
Err(IdeviceError::UnexpectedResponse(
"Port is not an unsigned integer in StartService response".into(),
))
}
}
_ => {
error!("Response didn't contain an integer port");
Err(IdeviceError::UnexpectedResponse(
"missing Port in StartService response".into(),
))
}
}
}
/// Generates a pairing file and sends it to the device for trusting.
/// Note that this does NOT save the file to usbmuxd's cache. That's a responsibility of the
/// caller.
/// Note that this function is computationally heavy in a debug build.
///
/// # Arguments
/// * `host_id` - The host ID, in the form of a UUID. Typically generated from the host name
/// * `system_buid` - UUID fetched from usbmuxd. Doesn't appear to affect function.
///
/// # Returns
/// The newly generated pairing record
///
/// # Errors
/// Returns `IdeviceError`
#[cfg(all(feature = "pair", feature = "rustls"))]
pub async fn pair(
&mut self,
host_id: impl Into<String>,
system_buid: impl Into<String>,
host_name: Option<&str>,
) -> Result<crate::pairing_file::PairingFile, IdeviceError> {
let host_id = host_id.into();
let system_buid = system_buid.into();
let pub_key = self.get_value(Some("DevicePublicKey"), None).await?;
let pub_key = match pub_key.as_data().map(|x| x.to_vec()) {
Some(p) => p,
None => {
tracing::warn!("Did not get public key data response");
return Err(IdeviceError::UnexpectedResponse(
"missing DevicePublicKey data in pair response".into(),
));
}
};
let wifi_mac = self.get_value(Some("WiFiAddress"), None).await?;
let wifi_mac = match wifi_mac.as_string() {
Some(w) => w,
None => {
tracing::warn!("Did not get WiFiAddress string");
return Err(IdeviceError::UnexpectedResponse(
"missing WiFiAddress string in pair response".into(),
));
}
};
let ca = crate::ca::generate_certificates(&pub_key, None).unwrap();
let mut pair_record = crate::plist!(dict {
"DevicePublicKey": pub_key,
"DeviceCertificate": ca.dev_cert,
"HostCertificate": ca.host_cert.clone(),
"HostID": host_id,
"RootCertificate": ca.host_cert,
"RootPrivateKey": ca.private_key.clone(),
"WiFiMACAddress": wifi_mac,
"SystemBUID": system_buid,
});
let req = crate::plist!({
"Label": self.idevice.label.clone(),
"Request": "Pair",
"HostName":? host_name,
"PairRecord": pair_record.clone(),
"ProtocolVersion": "2",
"PairingOptions": {
"ExtendedPairingErrors": true
}
});
loop {
self.idevice.send_plist(req.clone()).await?;
match self.idevice.read_plist().await {
Ok(escrow) => {
pair_record.insert("HostPrivateKey".into(), plist::Value::Data(ca.private_key));
if let Some(escrow) = escrow.get("EscrowBag").and_then(|x| x.as_data()) {
pair_record.insert("EscrowBag".into(), plist::Value::Data(escrow.to_vec()));
}
let p = crate::pairing_file::PairingFile::from_value(
&plist::Value::Dictionary(pair_record),
)?;
break Ok(p);
}
Err(IdeviceError::PairingDialogResponsePending) => {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
}
Err(e) => break Err(e),
}
}
}
/// Tell the device to enter recovery mode
pub async fn enter_recovery(&mut self) -> Result<(), IdeviceError> {
self.idevice
.send_plist(crate::plist!({
"Request": "EnterRecovery"
}))
.await?;
let res = self.idevice.read_plist().await?;
if res.get("Request").and_then(|x| x.as_string()) == Some("EnterRecovery") {
Ok(())
} else {
Err(IdeviceError::UnexpectedResponse(
"EnterRecovery request not acknowledged".into(),
))
}
}
}
impl From<Idevice> for LockdownClient {
/// Converts an existing device connection into a lockdown client
fn from(value: Idevice) -> Self {
Self::new(value)
}
}