-
Notifications
You must be signed in to change notification settings - Fork 68
/
lockdown.go
652 lines (537 loc) · 16.1 KB
/
lockdown.go
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
package giDevice
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"github.com/electricbubble/gidevice/pkg/libimobiledevice"
uuid "github.com/satori/go.uuid"
"math/big"
"strconv"
"strings"
"time"
)
var _ Lockdown = (*lockdown)(nil)
func newLockdown(dev *device) *lockdown {
return &lockdown{
umClient: dev.umClient,
client: dev.lockdownClient,
dev: dev,
}
}
type lockdown struct {
umClient *libimobiledevice.UsbmuxClient
client *libimobiledevice.LockdownClient
sessionID string
dev *device
iOSVersion []int
pairRecord *PairRecord
}
func (c *lockdown) QueryType() (LockdownType, error) {
pkt, err := c.client.NewXmlPacket(
c.client.NewBasicRequest(libimobiledevice.RequestTypeQueryType),
)
if err != nil {
return LockdownType{}, err
}
if err = c.client.SendPacket(pkt); err != nil {
return LockdownType{}, err
}
var respPkt libimobiledevice.Packet
if respPkt, err = c.client.ReceivePacket(); err != nil {
return LockdownType{}, err
}
var reply libimobiledevice.LockdownTypeResponse
if err = respPkt.Unmarshal(&reply); err != nil {
return LockdownType{}, err
}
return LockdownType{Type: reply.Type}, nil
}
func (c *lockdown) GetValue(domain, key string) (v interface{}, err error) {
pkt, err := c.client.NewXmlPacket(
c.client.NewGetValueRequest(domain, key),
)
if err != nil {
return nil, err
}
if err = c.client.SendPacket(pkt); err != nil {
return nil, err
}
var respPkt libimobiledevice.Packet
if respPkt, err = c.client.ReceivePacket(); err != nil {
return nil, err
}
var reply libimobiledevice.LockdownValueResponse
if err = respPkt.Unmarshal(&reply); err != nil {
return nil, err
}
v = reply.Value
return
}
func (c *lockdown) SetValue(domain, key string, value interface{}) (err error) {
var pkt libimobiledevice.Packet
if pkt, err = c.client.NewXmlPacket(
c.client.NewSetValueRequest(domain, key, value),
); err != nil {
return err
}
if err = c.client.SendPacket(pkt); err != nil {
return err
}
var respPkt libimobiledevice.Packet
if respPkt, err = c.client.ReceivePacket(); err != nil {
return err
}
var reply libimobiledevice.LockdownValueResponse
if err = respPkt.Unmarshal(&reply); err != nil {
return err
}
if !reply.Value.(bool) {
return errors.New("lockdown SetValue: Failed")
}
return
}
func (c *lockdown) EnterRecovery() (err error) {
var pkt libimobiledevice.Packet
if pkt, err = c.client.NewXmlPacket(
c.client.NewEnterRecoveryRequest(),
); err != nil {
return err
}
if err = c.client.SendPacket(pkt); err != nil {
return err
}
if _, err = c.client.ReceivePacket(); err != nil {
return err
}
return
}
func (c *lockdown) handshake() (err error) {
var lockdownType LockdownType
if lockdownType, err = c.QueryType(); err != nil {
return err
}
if lockdownType.Type != "com.apple.mobile.lockdown" {
return fmt.Errorf("lockdown handshake 'QueryType': %s", lockdownType.Type)
}
// if (device->version < DEVICE_VERSION(7,0,0))
// for older devices, we need to validate pairing to receive trusted host status
if c.pairRecord, err = c.dev.ReadPairRecord(); err == nil {
return nil
}
if !strings.Contains(err.Error(), libimobiledevice.ReplyCodeBadDevice.String()) {
return err
}
if c.pairRecord, err = c.Pair(); err != nil {
return err
}
err = c.dev.SavePairRecord(c.pairRecord)
return
}
func (c *lockdown) Pair() (pairRecord *PairRecord, err error) {
var buid string
if buid, err = newUsbmux(c.umClient).ReadBUID(); err != nil {
return nil, err
}
var devPublicKeyPem []byte
var devWiFiAddr string
if lockdownValue, err := c.GetValue("", "DevicePublicKey"); err != nil {
return nil, err
} else {
devPublicKeyPem = lockdownValue.([]byte)
}
if lockdownValue, err := c.GetValue("", "WiFiAddress"); err != nil {
return nil, err
} else {
devWiFiAddr = lockdownValue.(string)
}
if pairRecord, err = generatePairRecord(devPublicKeyPem); err != nil {
return nil, err
}
pairRecord.SystemBUID = buid
pairRecord.HostID = strings.ToUpper(uuid.NewV4().String())
hostPrivateKey := pairRecord.HostPrivateKey
pairRecord.HostPrivateKey = nil
rootPrivateKey := pairRecord.RootPrivateKey
pairRecord.RootPrivateKey = nil
var pkt libimobiledevice.Packet
if pkt, err = c.client.NewXmlPacket(
c.client.NewPairRequest(pairRecord),
); err != nil {
return nil, err
}
if err = c.client.SendPacket(pkt); err != nil {
return nil, err
}
var respPkt libimobiledevice.Packet
if respPkt, err = c.client.ReceivePacket(); err != nil {
return nil, err
}
var reply libimobiledevice.LockdownPairResponse
if err = respPkt.Unmarshal(&reply); err != nil {
return nil, err
}
pairRecord.EscrowBag = reply.EscrowBag
pairRecord.WiFiMACAddress = devWiFiAddr
pairRecord.HostPrivateKey = hostPrivateKey
pairRecord.RootPrivateKey = rootPrivateKey
return
}
func (c *lockdown) startSession(pairRecord *PairRecord) (err error) {
// if we have a running session, stop current one first
if c.sessionID != "" {
if err = c.stopSession(); err != nil {
return err
}
}
var pkt libimobiledevice.Packet
if pkt, err = c.client.NewXmlPacket(
c.client.NewStartSessionRequest(pairRecord.SystemBUID, pairRecord.HostID),
); err != nil {
return err
}
if err = c.client.SendPacket(pkt); err != nil {
return err
}
var respPkt libimobiledevice.Packet
if respPkt, err = c.client.ReceivePacket(); err != nil {
return fmt.Errorf("lockdown start session: %w", err)
}
var reply libimobiledevice.LockdownStartSessionResponse
if err = respPkt.Unmarshal(&reply); err != nil {
return err
}
if reply.EnableSessionSSL {
if err = c.client.EnableSSL(c.iOSVersion, pairRecord); err != nil {
return err
}
}
c.sessionID = reply.SessionID
return
}
func (c *lockdown) stopSession() (err error) {
if c.sessionID == "" {
return nil
}
var pkt libimobiledevice.Packet
if pkt, err = c.client.NewXmlPacket(
c.client.NewStopSessionRequest(c.sessionID),
); err != nil {
return err
}
if err = c.client.SendPacket(pkt); err != nil {
return err
}
var respPkt libimobiledevice.Packet
if respPkt, err = c.client.ReceivePacket(); err != nil {
return fmt.Errorf("lockdown stop session: %w", err)
}
var reply libimobiledevice.LockdownBasicResponse
if err = respPkt.Unmarshal(&reply); err != nil {
return err
}
c.sessionID = ""
return
}
func (c *lockdown) startService(service string, escrowBag []byte) (dynamicPort int, enableSSL bool, err error) {
req := c.client.NewStartServiceRequest(service)
if escrowBag != nil {
req.EscrowBag = escrowBag
}
var pkt libimobiledevice.Packet
if pkt, err = c.client.NewXmlPacket(req); err != nil {
return 0, false, err
}
if err = c.client.SendPacket(pkt); err != nil {
return 0, false, err
}
respPkt, err := c.client.ReceivePacket()
if err != nil {
return 0, false, err
}
var reply libimobiledevice.LockdownStartServiceResponse
if err = respPkt.Unmarshal(&reply); err != nil {
return 0, false, err
}
if reply.Error != "" {
return 0, false, fmt.Errorf("lockdown start service: %s", reply.Error)
}
dynamicPort = reply.Port
enableSSL = reply.EnableServiceSSL
return
}
func (c *lockdown) ImageMounterService() (imageMounter ImageMounter, err error) {
var innerConn InnerConn
if innerConn, err = c._startService(libimobiledevice.ImageMounterServiceName, nil); err != nil {
return nil, err
}
imageMounterClient := libimobiledevice.NewImageMounterClient(innerConn)
imageMounter = newImageMounter(imageMounterClient)
return
}
func (c *lockdown) ScreenshotService() (screenshot Screenshot, err error) {
var innerConn InnerConn
if innerConn, err = c._startService(libimobiledevice.ScreenshotServiceName, nil); err != nil {
return nil, err
}
screenshotClient := libimobiledevice.NewScreenshotClient(innerConn)
screenshot = newScreenshot(screenshotClient)
return
}
func (c *lockdown) SimulateLocationService() (simulateLocation SimulateLocation, err error) {
var innerConn InnerConn
if innerConn, err = c._startService(libimobiledevice.SimulateLocationServiceName, nil); err != nil {
return nil, err
}
simulateLocationClient := libimobiledevice.NewSimulateLocationClient(innerConn)
simulateLocation = newSimulateLocation(simulateLocationClient)
return
}
func (c *lockdown) InstallationProxyService() (installationProxy InstallationProxy, err error) {
var innerConn InnerConn
if innerConn, err = c._startService(libimobiledevice.InstallationProxyServiceName, nil); err != nil {
return nil, err
}
installationProxyClient := libimobiledevice.NewInstallationProxyClient(innerConn)
installationProxy = newInstallationProxy(installationProxyClient)
return
}
func (c *lockdown) InstrumentsService() (instruments Instruments, err error) {
service := libimobiledevice.InstrumentsServiceName
if DeviceVersion(c.iOSVersion...) >= DeviceVersion(14, 0, 0) {
service = libimobiledevice.InstrumentsSecureProxyServiceName
}
var innerConn InnerConn
if innerConn, err = c._startService(service, nil); err != nil {
return nil, err
}
instrumentsClient := libimobiledevice.NewInstrumentsClient(innerConn)
instruments = newInstruments(instrumentsClient)
if service == libimobiledevice.InstrumentsServiceName {
_ = innerConn.DismissSSL()
}
if err = instruments.notifyOfPublishedCapabilities(); err != nil {
return nil, err
}
return
}
func (c *lockdown) TestmanagerdService() (testmanagerd Testmanagerd, err error) {
service := libimobiledevice.TestmanagerdServiceName
if DeviceVersion(c.iOSVersion...) >= DeviceVersion(14, 0, 0) {
service = libimobiledevice.TestmanagerdSecureServiceName
}
var innerConn InnerConn
if innerConn, err = c._startService(service, nil); err != nil {
return nil, err
}
testmanagerdClient := libimobiledevice.NewTestmanagerdClient(innerConn)
testmanagerd = newTestmanagerd(testmanagerdClient, c.iOSVersion)
if service == libimobiledevice.TestmanagerdServiceName {
_ = innerConn.DismissSSL()
}
if err = testmanagerd.notifyOfPublishedCapabilities(); err != nil {
return nil, err
}
return
}
func (c *lockdown) AfcService() (afc Afc, err error) {
var innerConn InnerConn
if innerConn, err = c._startService(libimobiledevice.AfcServiceName, nil); err != nil {
return nil, err
}
afcClient := libimobiledevice.NewAfcClient(innerConn)
afc = newAfc(afcClient)
return
}
func (c *lockdown) HouseArrestService() (houseArrest HouseArrest, err error) {
var innerConn InnerConn
if innerConn, err = c._startService(libimobiledevice.HouseArrestServiceName, nil); err != nil {
return nil, err
}
houseArrestClient := libimobiledevice.NewHouseArrestClient(innerConn)
houseArrest = newHouseArrest(houseArrestClient)
return
}
func (c *lockdown) SyslogRelayService() (syslogRelay SyslogRelay, err error) {
var innerConn InnerConn
if innerConn, err = c._startService(libimobiledevice.SyslogRelayServiceName, nil); err != nil {
return nil, err
}
syslogRelayClient := libimobiledevice.NewSyslogRelayClient(innerConn)
syslogRelay = newSyslogRelay(syslogRelayClient)
return
}
func (c *lockdown) CrashReportMoverService() (crashReportMover CrashReportMover, err error) {
var innerConn InnerConn
if innerConn, err = c._startService(libimobiledevice.CrashReportMoverServiceName, nil); err != nil {
return nil, err
}
mover := newCrashReportMover(libimobiledevice.NewCrashReportMoverClient(innerConn))
if err = mover.readPing(); err != nil {
return nil, err
}
if innerConn, err = c._startService(libimobiledevice.CrashReportCopyMobileServiceName, nil); err != nil {
return nil, err
}
mover.afc = newAfc(libimobiledevice.NewAfcClient(innerConn))
crashReportMover = mover
return
}
func (c *lockdown) _startService(serviceName string, escrowBag []byte) (innerConn InnerConn, err error) {
if err = c.handshake(); err != nil {
return nil, err
}
if err = c.startSession(c.pairRecord); err != nil {
return nil, err
}
dynamicPort, enableSSL, err := c.startService(serviceName, escrowBag)
if err != nil {
return nil, err
}
if err = c.stopSession(); err != nil {
return nil, err
}
if innerConn, err = c.dev.NewConnect(dynamicPort, 0); err != nil {
return nil, err
}
// clean deadline
innerConn.Timeout(0)
if enableSSL {
if err = innerConn.Handshake(c.iOSVersion, c.pairRecord); err != nil {
return nil, err
}
}
return
}
func (c *lockdown) _getProductVersion() (version []int, err error) {
if c.iOSVersion != nil {
return c.iOSVersion, nil
}
var devProductVersion []string
if lockdownValue, err := c.GetValue("", "ProductVersion"); err != nil {
return nil, err
} else {
devProductVersion = strings.Split(lockdownValue.(string), ".")
}
version = make([]int, len(devProductVersion))
for i, v := range devProductVersion {
version[i], _ = strconv.Atoi(v)
}
// if len(version) == 2 {
// version = append(version, 0)
// }
c.iOSVersion = version
return
}
func generatePairRecord(devPublicKeyPem []byte) (pairRecord *PairRecord, err error) {
block, _ := pem.Decode(devPublicKeyPem)
var deviceKey *rsa.PublicKey
if deviceKey, err = x509.ParsePKCS1PublicKey(block.Bytes); err != nil {
return nil, err
}
var rootKey, hostKey *rsa.PrivateKey
if rootKey, err = rsa.GenerateKey(rand.Reader, 2048); err != nil {
return nil, err
}
if hostKey, err = rsa.GenerateKey(rand.Reader, 2048); err != nil {
return nil, err
}
serialNumber := big.NewInt(0)
notBefore := time.Now()
notAfter := notBefore.Add(time.Hour * (24 * 365) * 10)
rootTemplate := x509.Certificate{
IsCA: true,
SerialNumber: serialNumber,
Version: 2,
SignatureAlgorithm: x509.SHA1WithRSA,
PublicKeyAlgorithm: x509.RSA,
NotBefore: notBefore,
NotAfter: notAfter,
BasicConstraintsValid: true,
}
var caCert, cert []byte
if caCert, err = x509.CreateCertificate(rand.Reader, &rootTemplate, &rootTemplate, rootKey.Public(), rootKey); err != nil {
return nil, err
}
hostTemplate := x509.Certificate{
SerialNumber: serialNumber,
Version: 2,
SignatureAlgorithm: x509.SHA1WithRSA,
PublicKeyAlgorithm: x509.RSA,
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
BasicConstraintsValid: true,
}
if cert, err = x509.CreateCertificate(rand.Reader, &hostTemplate, &rootTemplate, hostKey.Public(), rootKey); err != nil {
return nil, err
}
h := sha1.New()
if _, err = h.Write(rootKey.N.Bytes()); err != nil {
return nil, err
}
subjectKeyId := h.Sum(nil)
deviceTemplate := x509.Certificate{
SerialNumber: serialNumber,
Version: 2,
SignatureAlgorithm: x509.SHA1WithRSA,
PublicKeyAlgorithm: x509.RSA,
NotBefore: notBefore,
NotAfter: notAfter,
BasicConstraintsValid: true,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
SubjectKeyId: subjectKeyId,
}
var deviceCert []byte
if deviceCert, err = x509.CreateCertificate(rand.Reader, &deviceTemplate, &rootTemplate, deviceKey, rootKey); err != nil {
return nil, err
}
var deviceCertPEM []byte
if deviceCertPEM, err = encodePemCertificate(deviceCert); err != nil {
return nil, err
}
var caPEM, caPrivatePEM []byte
if caPEM, caPrivatePEM, err = encodePairPemFormat(caCert, rootKey); err != nil {
return nil, err
}
var certPEM, certPrivatePEM []byte
if certPEM, certPrivatePEM, err = encodePairPemFormat(cert, hostKey); err != nil {
return nil, err
}
pairRecord = new(PairRecord)
pairRecord.DeviceCertificate = deviceCertPEM
pairRecord.HostCertificate = certPEM
pairRecord.HostPrivateKey = certPrivatePEM
pairRecord.RootCertificate = caPEM
pairRecord.RootPrivateKey = caPrivatePEM
return
}
func encodePairPemFormat(cert []byte, key *rsa.PrivateKey) ([]byte, []byte, error) {
p, err := encodePemCertificate(cert)
if err != nil {
return nil, nil, err
}
buf := new(bytes.Buffer)
if err := pem.Encode(buf, &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
}); err != nil {
return nil, nil, err
}
privy := buf.Bytes()
return p, privy, nil
}
func encodePemCertificate(cert []byte) ([]byte, error) {
buf := new(bytes.Buffer)
if err := pem.Encode(buf, &pem.Block{
Type: "CERTIFICATE",
Bytes: cert,
}); err != nil {
return nil, err
}
return buf.Bytes(), nil
}