-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathtetherKitAppDelegate.m
6480 lines (4874 loc) · 200 KB
/
tetherKitAppDelegate.m
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// tetherKitAppDelegate.m
// Seas0nPass
//
// Created by Kevin Bradley on 12/27/10.
// Copyright 2011 Fire Core, LLC. All rights reserved.
//
// Portions Copyright 2010 Joshua Hill & Chronic-Dev Team
// Portions Copyright 2010 planetbeing & iPhone-Dev Team
// libpois0n/libsyringe by Joshua Hill & Chronic-Dev Team. ( feel free to help me update these credits )
// xpwntool by planetbeing
// limera1n exploit by George Hotz
// 4.3.x exploit by i0n1c (steffan esser)
// 4.3.3 exploit by comex
// 4.4.x exploit by pod2g
//4.3b1 md5 for iBSS 0b03c11af9bd013a6cf98be65eb0e146
//4.3b1 patched md5 for iBSS
#import <Security/Authorization.h>
#include <Security/AuthorizationTags.h>
#import "tetherKitAppDelegate.h"
#import "include/libpois0n.h"
#import "include/libpartial.h"
#import <Foundation/Foundation.h>
//#import "IPhoneUSB.h"
#include <assert.h>
#include <pthread.h>
//#import "libusb.h"
#import <mach/mach_time.h>
//#import "IPhoneUSB.h"
#define FORCE_APPLE_STITCH
//CURRENT_BUNDLE is the finally the only place that the bundle name needs to be replaced to change default version for future versions.
//previous @"AppleTV2,1_5.0.2_9B830"
//AppleTV2,1_5.2_10B144b
//AppleTV2,1_5.2.1_10B329a
#define CURRENT_BUNDLE @"AppleTV2,1_5.3_10B809"
#define CURRENT_IPSW [NSString stringWithFormat:@"%@_Restore.ipsw", CURRENT_BUNDLE]
#define DL [tetherKitAppDelegate downloadLocation]
#define KCACHE @"kernelcache.release.k66"
#define iBSSDFU @"iBSS.k66ap.RELEASE.dfu"
#define iBECDFU @"iBEC.k66ap.RELEASE.dfu"
#define HCIPSW [DL stringByAppendingPathComponent:CURRENT_IPSW]
#define BUNDLE_LOCATION [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"bundles"]
#define BUNDLES [FM contentsOfDirectoryAtPath:BUNDLE_LOCATION error:nil]
#define BLOB_KEY @"sentLocalBlobs"
#define BLOBS_SENT [[NSUserDefaults standardUserDefaults] boolForKey:BLOB_KEY]
#define DID_MIGRATE [[NSUserDefaults standardUserDefaults] boolForKey:@"newVersionMigrate"]
#define LAST_BUNDLE [[NSUserDefaults standardUserDefaults] valueForKey:@"lastUsedBundle"]
#define KILL_ITUNES [[NSUserDefaults standardUserDefaults] boolForKey:@"killiTunes"]
#define DEFAULTS [NSUserDefaults standardUserDefaults]
#define IFAITH_BLOB_DONE @"iFaithBlobFinished"
//int received_cb(irecv_client_t client, const irecv_event_t* event);
int progress_cb(irecv_client_t client, const irecv_event_t* event);
static NSString *ChipID_ = nil;
BOOL limera1ned = FALSE;
BOOL tetheredBoot = FALSE;
static UKDevice *staticDevice = nil;
int shatterStatus = 0;
@implementation tetherKitAppDelegate
@synthesize window, downloadIndex, processing, enableScripting, firstView, secondView, poisoning, currentBundle, bundleController, counter, otherWindow, commandTextField, tetherLabel, countdownField, runMode, theEcid;
@synthesize deviceClass;
@synthesize restoreStatus;
@synthesize currentIPSWPath;
/*
this application is a bit of an amalgam of code from libsyringe, a few random classes from hawkeye and atvPwn and then iphone wiki notes / deciphering what pwnagetool does
by hand / creation of the bundles for PwnageTool
this could be seperated into several (or at least a few) different classes, but TBH, im lazy. The only reason im even putting these comments in here are the inevitability
of having to open source this because i know at very least libsyringe is GPL (and i wouldn't be surprised if xpwn is as well).
*/
/* probably not using this callback data variable properly, but i couldnt figure out how else to set download progress from the double values sent during uploading of iBSS and kernelcache */
void print_progress(double progress, void* data) {
int i = 0;
if(progress < 0) {
return;
}
if(progress > 100) {
progress = 100;
}
[(id)data setDownloadProgress:progress];
printf("\r[");
for(i = 0; i < 50; i++) {
if(i < progress / 2) {
printf("=");
} else {
printf(" ");
}
}
printf("] %3.1f%%", progress);
if(progress == 100) {
printf("\n");
}
}
/*
code for in case i ever add a fancy timer
- (void)nextCountdown
{
counter = 7;
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(secondTimer:) userInfo:nil repeats:YES];
}
- (void)firstTimer:(NSTimer *)timer
{
[self setCounter:(counter -1)];
//[countdownField setIntegerValue:counter];
if (counter <= 1) {
[timer invalidate];
[self nextCountdown];
}
}
- (void)secondTimer:(NSTimer *)timer
{
[self setCounter:(counter -1)];
[countdownField setIntegerValue:counter];
if (counter <= 1) {
[timer invalidate];
}
}
- (IBAction)startCountdown:(id)sender
{
counter = 5;
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(firstTimer:) userInfo:nil repeats:YES];
}
*/
//if ([theEvent modifierFlags] == 262401){
- (BOOL) optionKeyIsDown
{
return (GetCurrentKeyModifiers() & optionKey) != 0;
}
- (__strong const char *)iBECBoot
{
NSString *iBEC = [[self currentBundle] localiBECBoot];
if (iBEC == nil)
{
NSLog(@"no separate iBec for booting!");
iBEC = [[self currentBundle] localiBEC];
}
//NSLog(@"self current bundle: %@", self.currentBundle);
//NSLog(@"iBEC: %@", iBEC);
return [iBEC UTF8String];
}
- (__strong const char *)iBEC
{
NSString *iBEC = [[self currentBundle] localiBEC];
//NSLog(@"self current bundle: %@", self.currentBundle);
//NSLog(@"iBEC: %@", iBEC);
return [iBEC UTF8String];
}
- (__strong const char *)iBSS
{
NSString *iBSS = [[self currentBundle] localiBSS];
return [iBSS UTF8String];
}
- (__strong const char *)kernelcache
{
NSString *kc = [[self currentBundle] localKernel];
return [kc UTF8String];
}
- (NSString *)kcacheString
{
return [[self currentBundle] localKernel];
}
- (NSString *)iBSSString
{
return [[self currentBundle] localiBSS];
}
- (NSImage *)imageForMode:(int)inputMode
{
NSImage *theImage = nil;
switch (inputMode) {
case kSPATVRestoreImage:
theImage = [NSImage imageNamed:@"restore"];
break;
case kSPATVTetheredImage:
theImage = [NSImage imageNamed:@"tether"];
break;
case kSPSuccessImage:
theImage = [NSImage imageNamed:@"success"];
break;
case kSPIPSWImage:
theImage = [NSImage imageNamed:@"ipsw"];
break;
case kSPATVTetheredRemoteImage:
theImage = [NSImage imageNamed:@"tetheredRemote"];
break;
case kSPATVUntetheredImage:
theImage = [NSImage imageNamed:@"untethered"];
break;
}
return theImage;
}
- (void)dealloc
{
[downloadFiles release];
downloadFiles = nil;
[theEcid release];
theEcid = nil;
[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
- (void)startupAlert //deprecated till theres a tethered default version again.
{
NSUserDefaults *defaults = DEFAULTS;
BOOL warningShown = [defaults boolForKey:@"SPWarningShown"];
if (warningShown == TRUE)
return;
NSAlert *startupAlert = [NSAlert alertWithMessageText:@"Warning! Please read carefully." defaultButton:@"OK" alternateButton:@"More Info" otherButton:@"Cancel" informativeTextWithFormat:@"Currently the jailbreak for the 4.1.1 (iOS 4.2.1) software is 'tethered'. A tethered jailbreak requires the Apple TV to be connected to a computer for a brief moment during startup.\n\nSeas0nPass makes this as easy as possible, but please do not proceed unless you are comfortable with this process."];
int button = [startupAlert runModal];
switch (button) {
case 0: //more info
[self userGuides:nil];
break;
case 1: //okay
break;
case -1: //cancel and quit!!
[[NSApplication sharedApplication] terminate:self];
break;
}
[defaults setBool:YES forKey:@"SPWarningShown"];
}
- (NSString *)ipswOutputPath
{
return [[self currentBundle] outputFile];
}
void LogIt (NSString *format, ...)
{
va_list args;
va_start (args, format);
NSString *string;
string = [[NSString alloc] initWithFormat: format arguments: args];
va_end (args);
printf ("%s", [string UTF8String]);
[string release];
} // LogIt
- (BOOL)isMountainLion
{
unsigned major, minor, bugFix;
[[NSApplication sharedApplication] getSystemVersionMajor:&major minor:&minor bugFix:&bugFix];
NSString *comparisonVersion = @"10.8.0";
NSString *osVersion = [NSString stringWithFormat:@"%u.%u.%u", major, minor, bugFix];
NSComparisonResult theResult = [osVersion compare:comparisonVersion options:NSNumericSearch];
//NSLog(@"theversion: %@ installed version %@", theVersion, installedVersion);
if ( theResult == NSOrderedDescending )
{
//NSLog(@"%@ is greater than %@", osVersion, comparisonVersion);
return YES;
} else if ( theResult == NSOrderedAscending ){
//NSLog(@"%@ is greater than %@", comparisonVersion, osVersion);
return NO;
} else if ( theResult == NSOrderedSame ) {
// NSLog(@"%@ is equal to %@", osVersion, comparisonVersion);
return YES;
}
return NO;
}
- (void)printEnvironment
{
unsigned major, minor, bugFix;
[[NSApplication sharedApplication] getSystemVersionMajor:&major minor:&minor bugFix:&bugFix];
NSDictionary *bundle = [[NSBundle mainBundle] infoDictionary];
//NSLog(@"info: %@", [[NSBundle mainBundle] infoDictionary]);
NSString *bv = [self buildVersion];
NSString *process = [NSString stringWithFormat:@"Process:\t\t%@\n", [bundle valueForKey:@"CFBundleExecutable"] ];
NSString *path = [NSString stringWithFormat:@"Path:\t\t%@\n", [bundle valueForKey:@"CFBundleExecutablePath"] ];
NSString *ident = [NSString stringWithFormat:@"Identifier:\t\t%@\n", [bundle valueForKey:@"CFBundleIdentifier"] ];
NSString *vers = [NSString stringWithFormat:@"Version:\t\t%@ (%@)\n", [bundle valueForKey:@"CFBundleShortVersionString"], [bundle valueForKey:@"CFBundleVersion"]];
//NSString *ct = [NSString stringWithFormat:@"Code Type:\t\t%@\n", @"idontknow"];
//NSString *pp = [NSString stringWithFormat:@"Parent Process:\t\t%@\n\n", [bundle valueForKey:@"CFBundleIdentifier"] ];
NSString *date = [NSString stringWithFormat:@"Date/Time:\t\t%@\n", [[NSDate date] description]];
NSString *osvers = [NSString stringWithFormat:@"OS Version:\t\t%u.%u.%u (%@)\n\n\n", major, minor, bugFix, bv];
NSLog(@"\n");
NSLog(@"BEGIN NEW SESSION\n");
NSLog(@"************************\n");
NSLog(@"%@", process);
NSLog(@"%@", path);
NSLog(@"%@", ident);
NSLog(@"%@", vers);
NSLog(@"%@", date);
NSLog(@"%@", osvers);
//[self gestaltFun];
}
+ (NSString *)applicationSupportFolder {
NSFileManager *man = [NSFileManager defaultManager];
NSArray *paths =
NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory,
NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:
0] : NSTemporaryDirectory();
basePath = [basePath stringByAppendingPathComponent:@"Seas0nPass"];
if (![man fileExistsAtPath:basePath])
[man createDirectoryAtPath:basePath withIntermediateDirectories:YES attributes:nil error:nil];
return basePath;
}
+ (NSString *)wifiFile
{
NSString *wf = [[tetherKitAppDelegate applicationSupportFolder] stringByAppendingPathComponent:@"com.apple.wifi.plist"];
if ([FM fileExistsAtPath:wf]) { return wf; }
return nil;
}
+ (NSString *)ipswFile
{
return HCIPSW;
}
+ (NSRange)customRangeFromString:(NSString *)inputFile
{
//NSLog(@"inputFile: %@", inputFile);
NSString *baseName = [inputFile stringByDeletingPathExtension];
int length = [baseName length];
int start = length - 10;
//NSLog(@"range: (%i, %i)", start, 10);
return NSMakeRange(start, 10);
}
- (void)cleanupHomeFolder
{
/*
search through the ~ folder for any item that ends with SP_Restore.ipsw and move it to the proper folder.
*/
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSFileManager *man = [NSFileManager defaultManager];
NSArray *homeContents = [man contentsOfDirectoryAtPath:NSHomeDirectory() error:nil];
NSEnumerator *homeEnum = [homeContents objectEnumerator];
//NSDirectoryEnumerator *homeEnum = [man enumeratorAtPath:NSHomeDirectory()];
for (id currentObject in homeEnum)
{
if ([[currentObject pathExtension] isEqualToString:@"ipsw"])
{
NSString *endString = [currentObject substringWithRange:[tetherKitAppDelegate customRangeFromString:currentObject]];
//NSLog(@"endString: %@ fromString: %@", endString, currentObject);
if ([endString isEqualToString:@"SP_Restore"])
{
NSLog(@"is sp restore file, migrate: %@", currentObject);
NSString *fullOldPath = [NSHomeDirectory() stringByAppendingPathComponent:currentObject];
NSString *newPath = [[nitoUtility firmwareFolder] stringByAppendingPathComponent:currentObject];
if([man moveItemAtPath:fullOldPath toPath:newPath error:nil])
{
NSLog(@"moved: %@ successfully!", currentObject);
}
}
}
}
[DEFAULTS setBool:YES forKey:@"newVersionMigrate"];
[pool release];
}
- (void)showProgress
{
//LOG_SELF;
[buttonOne setEnabled:FALSE];
[bootButton setEnabled:FALSE];
self.processing = TRUE;
[downloadBar startAnimation:self];
[downloadBar setHidden:FALSE];
[downloadBar setNeedsDisplay:TRUE];
[downloadBar display];
[self setDownloadProgress:0];
[cancelButton setEnabled:FALSE];
}
- (void)hideProgress
{
[buttonOne setEnabled:TRUE];
[bootButton setEnabled:TRUE];
self.processing = FALSE;
[downloadBar stopAnimation:self];
[downloadBar setHidden:YES];
[downloadBar setNeedsDisplay:YES];
[cancelButton setEnabled:TRUE];
}
- (IBAction)versionChanged:(id)sender
{
//NSLog(@"version changed");
self.currentBundle = [FWBundle bundleWithName:LAST_BUNDLE];
//NSLog(@"self.currentBundle: %@", self.currentBundle);
if ([[self currentBundle] untethered])
{
[bootButton setImage:[self imageForMode:kSPATVUntetheredImage]];
[tetherLabel setTextColor:[NSColor lightGrayColor]];
} else {
[bootButton setImage:[self imageForMode:kSPATVTetheredImage]];
[tetherLabel setTextColor:[NSColor blackColor]];
}
}
//NSFileSize
- (BOOL)sufficientSpaceOnDevice:(NSString *)theDevice
{
NSFileManager *man = [NSFileManager defaultManager];
float available = [[[man attributesOfFileSystemForPath:theDevice error:nil] objectForKey:NSFileSystemFreeSize] floatValue];
float totalSize = 3000.0f;
float avail2 = available / 1024 / 1024;
if (avail2 < totalSize)
{
NSAlert *space = [NSAlert alertWithMessageText:NSLocalizedString(@"Free Space needed", nil)
defaultButton:NSLocalizedString(@"OK", nil)
alternateButton:@""
otherButton:@""
informativeTextWithFormat:NSLocalizedString(@"Not enough free space.\n\n Space needed: %.2f MB\n Space Available: %.2f MB", nil), totalSize, avail2 ];
[space runModal];
return NO;
}
return YES;
}
- (IBAction)cancel:(id)sender
{
if (downloadFile != nil)
{
if ([downloadFile isKindOfClass:[ripURL class]])
{
NSLog(@"downloadFile: %@", downloadFile);
if ([downloadFile respondsToSelector:@selector(cancel)])
{
//NSLog(@"cancel?");
[downloadFile cancel];
//self.processing = FALSE;
[self hideProgress];
}
}
}
if (self.poisoning == TRUE)
{
pois0n_exit();
self.poisoning = FALSE;
self.processing = FALSE;
}
if (self.processing == FALSE)
{
[window setContentView:self.firstView];
[self versionChanged:nil];
[window display];
}
}
void print_progress_bar(double progress) {
int i = 0;
if(progress < 0) {
return;
}
if(progress > 100) {
progress = 100;
}
printf("\r[");
for(i = 0; i < 50; i++) {
if(i < progress / 2) {
printf("=");
} else {
printf(" ");
}
}
printf("] %3.1f%%", progress);
fflush(stdout);
if(progress == 100) {
printf("\n");
}
}
int progress_cb(irecv_client_t client, const irecv_event_t* event) {
//NSLog(@"progress");
if (event->type == IRECV_PROGRESS) {
print_progress_bar(event->progress);
}
return 0;
}
- (IBAction)showHelpLog:(id)sender;
{
NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
NSString *logLocation = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Logs/SP_Debug.log"];
[workspace selectFile:logLocation inFileViewerRootedAtPath:[logLocation stringByDeletingLastPathComponent]];
}
- (int)fetch_image:(const char *) path toFile:(const char*) output {
debug("Fetching %s...\n", path);
if (download_file_from_zip(device->url, path, output, NULL)
!= 0) {
error("Unable to fetch %s\n", path);
return -1;
}
return 0;
}
- (int)fetch_dfu_image:(const char*) type toFile:(const char*) output {
char name[64];
char path[255];
memset(name, '\0', 64);
memset(path, '\0', 255);
snprintf(name, 63, "%s.%s.RELEASE.dfu", type, device->model);
snprintf(path, 254, "Firmware/dfu/%s", name);
debug("Preparing to fetch DFU image from Apple's servers\n");
if ([self fetch_image:path toFile:output] < 0 ){
//if (fetch_image(path, output) < 0) {
error("Unable to fetch DFU image from Apple's servers\n");
return -1;
}
return 0;
}
- (NSString *)errorDescriptionForStatus:(NSString *)stringStatus
{
/*
--> If the response is... "failed-1" it means the kernel failed to load from the filesystem (probably due to incomplete restore).
--> If the response is... "failed-2" it means the kernel does not have a KBAG (only happens when someone with a 3GS old bootrom runs redsn0w and redsn0w doesn't bother to re-encrypt the kernel).
--> If the response is... "failed-3" it means One or more of the flashed images on the device do not contain an SHSH blob (usually happens when users find funky tutorials on the web to downgrade without blobs).
--> If the response is... "failed-4" it means an unknown iOS is detected. The payload maybe outdated or user is running a beta firmware.
--> If the response is... "failed-5" it means no valid block devices containing flash images were found (happens when the user's NAND/NOR chip goes).
--> If the response is... "failed-6" it means the user has 24kpwn applied (only occurs on iPhone 3GS old bootroms/iPod Touch 2G MB models). Devices with 24kpwn applied do not have any SHSH blobs applied and never need any.
*/
if ([stringStatus isEqualToString:@"failed-1"]) return @"The kernel failed to load from the filesystem (probably due to incomplete restore).";
if ([stringStatus isEqualToString:@"failed-2"]) return @"The kernel does not have a KBAG (only happens when someone with a 3GS old bootrom runs redsn0w and redsn0w doesn't bother to re-encrypt the kernel).";
if ([stringStatus isEqualToString:@"failed-3"]) return @"One or more of the flashed images on the device do not contain an SHSH blob (usually happens when users find funky tutorials on the web to downgrade without blobs)";
if ([stringStatus isEqualToString:@"failed-4"]) return @"Unknown iOS is detected. iFaith payload might be outdated or you are running a beta firmware.";
if ([stringStatus isEqualToString:@"failed-5"]) return @"No valid block devices containing flash images were found (happens when the your NAND/NOR chip malfunctions).";
if ([stringStatus isEqualToString:@"failed-6"]) return @"You have 24kpwn applied (only occurs on iPhone 3GS old bootroms/iPod Touch 2G MB models). Devices with 24kpwn applied do not have any SHSH blobs applied and never need any.";
return @"unknown error";
}
- (int)dumpiFaithPayload
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *ifaithDir = @"/private/tmp/ifaith";
if ([FM fileExistsAtPath:ifaithDir])
{
[FM removeItemAtPath:ifaithDir error:nil];
[FM createDirectoryAtPath:ifaithDir withIntermediateDirectories:YES attributes:nil error:nil];
} else {
[FM createDirectoryAtPath:ifaithDir withIntermediateDirectories:YES attributes:nil error:nil];
}
int result = 0;
char iBSSFile[255];
char iBECFile[255];
char* boardType = NULL;
char* outputStatus = NULL;
char* xmlOutput = NULL;
irecv_error_t error = IRECV_E_SUCCESS;
irecv_error_t ir_error = IRECV_E_SUCCESS;
pois0n_init();
pois0n_set_callback(&print_progress, self);
//printf("Waiting for device to enter DFU mode\n");
[self setDownloadText:NSLocalizedString(@"Waiting for device to enter DFU mode...", @"Waiting for device to enter DFU mode...")];
[self setInstructionText:NSLocalizedString(@"Connect USB then press and hold MENU and PLAY/PAUSE for 7 seconds.", @"Connect USB then press and hold MENU and PLAY/PAUSE for 7 seconds.")];
//NSImage *theImage = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"tether" ofType:@"png"]];
//NSImage *theImage = [NSImage imageNamed:@"tether"];
[instructionImage setImage:[self imageForMode:kSPATVRestoreImage]];
//[theImage release];
while(pois0n_is_ready()) {
// if (self.deviceClass == nil)
// {
// [self _fetchDeviceInfo];
// sleep(5);
// }
// if ([self isAppleTV3])
// {
// [self hideProgress];
// //pois0n_exit();
// self.poisoning = FALSE;
// [pool release];
// return -1;
// }
sleep(1);
}
[self setDownloadText:NSLocalizedString(@"Found device in DFU mode", @"Found device in DFU mode")];
[self setInstructionText:@""];
result = pois0n_is_compatible();
if (result < 0) {
[self setDownloadText:NSLocalizedString(@"Your device is not compatible with this exploit!", @"Your device is not compatible with this exploit!")];
return result;
}
result = ifaith_inject_only(); //iFaith specific payload
if (result < 0) {
[self setDownloadText:NSLocalizedString(@"Exploit injection failed!", @"Exploit injection failed!")];
return result;
}
memset(iBSSFile, '\0', 255);
snprintf(iBSSFile, 254, "/private/tmp/ifaith/%s.%s", "iBSS", device->model); //tmp iBSS file downloaded
memset(iBECFile, '\0', 255);
snprintf(iBECFile, 254, "/private/tmp/ifaith/%s.%s", "iBEC", device->model); //tmp iBEC file downloaded
printf("Checking if %s already exists\n", iBSSFile);
[self setDownloadText:NSLocalizedString(@"Fetching iBSS file...", @"Fetching iBSS file...")];
if ([self fetch_dfu_image:"iBSS" toFile:iBSSFile] < 0){
error("Unable to download DFU image\n");
return -1;
}
printf("Checking if %s already exists\n", iBECFile);
[self setDownloadText:NSLocalizedString(@"Fetching iBEC file...", @"Fetching iBSS file...")];
if ([self fetch_dfu_image:"iBEC" toFile:iBECFile] < 0){
error("Unable to download DFU image\n");
return -1;
}
//got iBSS and iBEC files, now read payload.bin into a file and append iBEC
NSString *payload = [[NSBundle mainBundle] pathForResource:@"payload" ofType:@"bin"];
NSMutableData *payloadData = [[NSMutableData alloc] initWithContentsOfMappedFile:payload];
NSData *ibecData = [NSData dataWithContentsOfFile:[NSString stringWithUTF8String:iBECFile]];
[payloadData appendData:ibecData];
NSString *outputFile = @"/private/tmp/ifaith/output.bin";
[payloadData writeToFile:outputFile atomically:YES];
[self setDownloadText:[NSString stringWithFormat:@"Uploading %@ to device...", [NSString stringWithUTF8String:iBSSFile]]];
ir_error = irecv_send_file(client, iBSSFile, 1);
if(ir_error != IRECV_E_SUCCESS) {
[self setDownloadText:NSLocalizedString(@"Unable to upload iBSS!", @"Unable to upload iBSS!")];
debug("%s\n", irecv_strerror(ir_error));
return -1;
}
[self setDownloadText:NSLocalizedString(@"iBSS upload successful! Reconnecting in 10 seconds...", @"iBSS upload successful! Reconnecting in 10 seconds...")];
client = irecv_reconnect(client, 10);
[self setDownloadText:[NSString stringWithFormat:@"Uploading %@ to device...", outputFile]];
ir_error = irecv_send_file(client, [outputFile UTF8String], 1);
if(ir_error != IRECV_E_SUCCESS) {
[self setDownloadText:NSLocalizedString(@"Unable to upload iBSS!", @"Unable to upload iBSS!")];
debug("%s\n", irecv_strerror(ir_error));
return -1;
}
[self setDownloadProgress:0];
[self setDownloadText:NSLocalizedString(@"iFaith payload upload successful! Reconnecting in 10 seconds...", @"iFaith payload upload successful! Reconnecting in 10 seconds...")];
client = irecv_reconnect(client, 10);
irecv_getenv(client, "config_board", &boardType);
//printf("boardType: %s\n", boardType);
[self setDownloadText:NSLocalizedString(@"Verifying Board Type...", @"Verifying Board Type...")];
if ([[NSString stringWithUTF8String:boardType] isEqualToString:@"k66ap"])
{
NSString *outputBlob = @"/private/tmp/ifaith/ifaith.blob"; //raw blob in hex
//NSString *ifaithOutput = @"/private/tmp/ifaith/ifaith.xml";
[self setDownloadText:NSLocalizedString(@"Creating iFaith SHSH blob...", @"Creating iFaith SHSH blob...")];
FILE* file = freopen([outputBlob fileSystemRepresentation], "a", stdout);
irecv_set_configuration(client, 1);
irecv_set_interface(client, 0, 0);
irecv_set_interface(client, 1, 1);
error = irecv_receive(client);
irecv_send_command(client, "go ready");
irecv_getenv(client, "status", &outputStatus);
NSString *stringStatus = [NSString stringWithUTF8String:outputStatus];
NSLog(@"status: %@", stringStatus);
if (![stringStatus isEqualToString:@"ready"])
{
NSString *errorDescription = [self errorDescriptionForStatus:stringStatus];
NSLog(@"failed with status: %@ and description: %@", stringStatus, errorDescription);
fclose(file);
[self setDownloadText:NSLocalizedString(@"Failed!", @"Failed!")];
poisoning = FALSE;
pois0n_exit();
[[NSNotificationCenter defaultCenter] postNotificationName:IFAITH_BLOB_DONE object:[NSDictionary dictionaryWithObject:errorDescription forKey:@"error"]];
[pool release];
return -1;
}
//printf("status: %s\n", outputStatus);
irecv_getenv_sn0w(client, "effyocouch", &xmlOutput ,1);
fclose(file);
NSString *ifaithSupport = [[tetherKitAppDelegate applicationSupportFolder] stringByAppendingPathComponent:@"iFaith"];
if (![FM fileExistsAtPath:ifaithSupport])
{
[FM createDirectoryAtPath:ifaithSupport withIntermediateDirectories:YES attributes:nil error:nil];
}
// NSString *decimalString = [[NSString stringWithContentsOfFile:outputBlob] hexToString];
NSError *encodingError = nil;
NSString *decimalString = [[NSString stringWithContentsOfFile:outputBlob encoding:NSUTF8StringEncoding error:&encodingError] hexToString];
if (encodingError != nil)
{
NSLog(@"encoding error with UTF8, try ASCII!: %@", encodingError);
decimalString = [[NSString stringWithContentsOfFile:outputBlob encoding:NSASCIIStringEncoding error:&encodingError] hexToString];
}
//decimal string is in XML format, I import the XML and then convert it to a plist / NSDictionary
// NSLog(@"decimalString: %@", decimalString);
NSDictionary *ifaithDict = [[[NSXMLDocument alloc] initWithXMLString:decimalString options:NSXMLDocumentTidyXML error:nil] iFaithDictionaryRepresentation];
NSString *ifaithXMLOutput = [ifaithSupport stringByAppendingFormat:@"/%@_%@.xml", [ifaithDict objectForKey:@"ecid"], [ifaithDict objectForKey:@"ios"]];
NSData *blob = [[NSString stringWithContentsOfFile:outputBlob encoding:NSUTF8StringEncoding error:&encodingError] stringToHexData];
if (encodingError != nil)
{
NSLog(@"encoding error with UTF8, try ASCII!: %@", encodingError);
blob = [[NSString stringWithContentsOfFile:outputBlob encoding:NSASCIIStringEncoding error:&encodingError] stringToHexData];
}
//[[NSString stringWithContentsOfFile:outputBlob] stringToHexData];
[blob writeToFile:ifaithXMLOutput atomically:YES];
//make sure if its greater than 4.3 to make sure there is an apticket there.
BOOL shouldSendBlob = YES;
NSString *comparisonVersion = @"4.4";
NSString *iosVersion = [ifaithDict objectForKey:@"ios"];
NSString *apticket = [ifaithDict objectForKey:@"apticket"];
NSString *clippedPath = [[iosVersion componentsSeparatedByString:@" "] objectAtIndex:0];
NSComparisonResult theResult = [clippedPath compare:comparisonVersion options:NSNumericSearch];
NSString *errorString = nil;
//NSLog(@"theversion: %@ installed version %@", theVersion, installedVersion);
BOOL apticketCheck = NO;
if ( theResult == NSOrderedDescending )
{
NSLog(@"%@ is greater than %@", clippedPath, comparisonVersion);
if (apticket != nil) {
shouldSendBlob = YES;
apticketCheck = YES;
} else {
NSLog(@"no apticket, invalid blob!! not submitting");
shouldSendBlob = NO;
errorString = @"The APTicket is missing!, invalid SHSH file!";
}
} else if ( theResult == NSOrderedAscending ){
NSLog(@"%@ is greater than %@", comparisonVersion, clippedPath);
NSLog(@"no apticket needed, below 4.4");
shouldSendBlob = YES;
apticketCheck = NO;
} else if ( theResult == NSOrderedSame ) {
NSLog(@"%@ is equal to %@", clippedPath, comparisonVersion);
if (apticket != nil) {
shouldSendBlob = YES;
apticketCheck = YES;
} else {
NSLog(@"no apticket, invalid blob!! not submitting");
errorString = @"The APTicket is missing!, invalid SHSH file!";
shouldSendBlob = NO;
apticketCheck = NO;
}
}
if (shouldSendBlob == YES)
{
TSSManager *tss = nil;
if (!DeviceIDEqualToDevice(currentDevice, TSSNullDevice))
{
tss = [[TSSManager alloc] initWithECID:ChipID_ device:currentDevice];
} else {
tss = [[TSSManager alloc] initWithECID:ChipID_];
}
if (apticketCheck)
{
int apticketResponse = [tss _synchronousAPTicketCheck:[ifaithDict objectForKey:@"apticket"]];
NSLog(@"apticket verify response: %i", apticketResponse);
if (apticketResponse == 0)
{
errorString = @"Invalid APTicket! invalid SHSH files.";
poisoning = FALSE;
pois0n_exit();
[[NSNotificationCenter defaultCenter] postNotificationName:IFAITH_BLOB_DONE object:[NSDictionary dictionaryWithObject:errorString forKey:@"error"]];
[pool release];
}
}
NSString *response = [tss _synchronousPushiFaithBlob:decimalString withiOSVersion:iosVersion];
NSLog(@"response: %@", response);
} else {
poisoning = FALSE;
pois0n_exit();
[[NSNotificationCenter defaultCenter] postNotificationName:IFAITH_BLOB_DONE object:[NSDictionary dictionaryWithObject:errorString forKey:@"error"]];
[pool release];
return -1;
}
//printf("output: %s", xmlOutput);
//NSLog(@"ifaithDict: %@", ifaithDict);
[self setDownloadText:NSLocalizedString(@"Finished!", @"Finished!")];
poisoning = FALSE;
pois0n_exit();
[[NSNotificationCenter defaultCenter] postNotificationName:IFAITH_BLOB_DONE object:ifaithDict];
[pool release];
return 0;
}
pois0n_exit();
[pool release];
return -1;
}
//- (NSDictionary *)ifaithBlobToDictionary:(NSXMLDocument *)rootElt
//{
//
// NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
// NSArray *val=[rootElt nodesForXPath:@"./iFaith/name" error:nil];
// if ([val count]!=0)
// {
// NSArray *children = [[val objectAtIndex:0] children];
// for (NSXMLNode *child in children)
// {
// NSLog(@"name: %@, stringVal: %@", [child name], [child stringValue]);
// // [dict setObject:[child stringValue] forKey:[child name]];
// }
// }
// //NSLog(@"dict: %@",dict);
// return [dict autorelease];
//}
+ (NSString *) stringToHex:(NSString *)str
{