forked from maciekish/iReSign
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iReSignAppDelegate.m
537 lines (414 loc) · 21.9 KB
/
iReSignAppDelegate.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
//
// iReSignAppDelegate.m
// iReSign
//
// Created by Maciej Swic on 2011-05-16.
//
#import "iReSignAppDelegate.h"
static NSString *kKeyPrefsBundleIDChange = @"keyBundleIDChange";
static NSString *kKeyBundleIDPlistApp = @"CFBundleIdentifier";
static NSString *kKeyBundleIDPlistiTunesArtwork = @"softwareVersionBundleId";
static NSString *kPayloadDirName = @"Payload";
static NSString *kInfoPlistFilename = @"Info.plist";
static NSString *kiTunesMetadataFileName = @"iTunesMetadata";
@implementation iReSignAppDelegate
@synthesize window,workingPath;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[self resizeWindow:184];
[flurry setAlphaValue:0.5];
defaults = [NSUserDefaults standardUserDefaults];
if ([defaults valueForKey:@"CERT_NAME"])
[certField setStringValue:[defaults valueForKey:@"CERT_NAME"]];
if ([defaults valueForKey:@"MOBILEPROVISION_PATH"])
[provisioningPathField setStringValue:[defaults valueForKey:@"MOBILEPROVISION_PATH"]];
if (![[NSFileManager defaultManager] fileExistsAtPath:@"/usr/bin/zip"]) {
NSRunAlertPanel(@"Error",
@"This app cannot run without the zip utility present at /usr/bin/zip",
@"OK",nil,nil);
exit(0);
}
if (![[NSFileManager defaultManager] fileExistsAtPath:@"/usr/bin/unzip"]) {
NSRunAlertPanel(@"Error",
@"This app cannot run without the unzip utility present at /usr/bin/unzip",
@"OK",nil,nil);
exit(0);
}
if (![[NSFileManager defaultManager] fileExistsAtPath:@"/usr/bin/codesign"]) {
NSRunAlertPanel(@"Error",
@"This app cannot run without the codesign utility present at /usr/bin/codesign",
@"OK",nil, nil);
exit(0);
}
}
- (IBAction)resign:(id)sender {
//Save cert name
[defaults setValue:[certField stringValue] forKey:@"CERT_NAME"];
[defaults setValue:[provisioningPathField stringValue] forKey:@"MOBILEPROVISION_PATH"];
[defaults setValue:[bundleIDField stringValue] forKey:kKeyPrefsBundleIDChange];
[defaults synchronize];
codesigningResult = nil;
verificationResult = nil;
originalIpaPath = [[pathField stringValue] retain];
workingPath = [[NSTemporaryDirectory() stringByAppendingPathComponent:@"com.appulize.iresign"] retain];
if ([[[originalIpaPath pathExtension] lowercaseString] isEqualToString:@"ipa"]) {
[self disableControls];
NSLog(@"Setting up working directory in %@",workingPath);
[statusLabel setHidden:NO];
[statusLabel setStringValue:@"Setting up working directory"];
[[NSFileManager defaultManager] removeItemAtPath:workingPath error:nil];
[[NSFileManager defaultManager] createDirectoryAtPath:workingPath withIntermediateDirectories:TRUE attributes:nil error:nil];
if (originalIpaPath && [originalIpaPath length] > 0) {
NSLog(@"Unzipping %@",originalIpaPath);
[statusLabel setStringValue:@"Extracting original app"];
}
unzipTask = [[NSTask alloc] init];
[unzipTask setLaunchPath:@"/usr/bin/unzip"];
[unzipTask setArguments:[NSArray arrayWithObjects:@"-q", originalIpaPath, @"-d", workingPath, nil]];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkUnzip:) userInfo:nil repeats:TRUE];
[unzipTask launch];
} else {
NSRunAlertPanel(@"Error",
@"You must choose an *.ipa file",
@"OK",nil,nil);
[self enableControls];
[statusLabel setStringValue:@"Please try again"];
}
}
- (void)checkUnzip:(NSTimer *)timer {
if ([unzipTask isRunning] == 0) {
[timer invalidate];
[unzipTask release];
unzipTask = nil;
if ([[NSFileManager defaultManager] fileExistsAtPath:[workingPath stringByAppendingPathComponent:@"Payload"]]) {
NSLog(@"Unzipping done");
[statusLabel setStringValue:@"Original app extracted"];
if (changeBundleIDCheckbox.state == NSOnState) {
[self doBundleIDChange:bundleIDField.stringValue];
}
if ([[provisioningPathField stringValue] isEqualTo:@""]) {
[self doCodeSigning];
} else {
[self doProvisioning];
}
} else {
NSRunAlertPanel(@"Error",
@"Unzip failed",
@"OK",nil,nil);
[self enableControls];
[statusLabel setStringValue:@"Ready"];
}
}
}
- (BOOL)doBundleIDChange:(NSString *)newBundleID {
BOOL success = YES;
success &= [self doAppBundleIDChange:newBundleID];
success &= [self doITunesMetadataBundleIDChange:newBundleID];
return success;
}
- (BOOL)doITunesMetadataBundleIDChange:(NSString *)newBundleID {
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:workingPath error:nil];
NSString *infoPlistPath = nil;
for (NSString *file in dirContents) {
if ([[[file pathExtension] lowercaseString] isEqualToString:@"plist"]) {
infoPlistPath = [workingPath stringByAppendingPathComponent:file];
break;
}
}
return [self changeBundleIDForFile:infoPlistPath bundleIDKey:kKeyBundleIDPlistiTunesArtwork newBundleID:newBundleID plistOutOptions:NSPropertyListXMLFormat_v1_0];
}
- (BOOL)doAppBundleIDChange:(NSString *)newBundleID {
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[workingPath stringByAppendingPathComponent:kPayloadDirName] error:nil];
NSString *infoPlistPath = nil;
for (NSString *file in dirContents) {
if ([[[file pathExtension] lowercaseString] isEqualToString:@"app"]) {
infoPlistPath = [[[workingPath stringByAppendingPathComponent:kPayloadDirName]
stringByAppendingPathComponent:file]
stringByAppendingPathComponent:kInfoPlistFilename];
break;
}
}
return [self changeBundleIDForFile:infoPlistPath bundleIDKey:kKeyBundleIDPlistApp newBundleID:newBundleID plistOutOptions:NSPropertyListBinaryFormat_v1_0];
}
- (BOOL)changeBundleIDForFile:(NSString *)filePath bundleIDKey:(NSString *)bundleIDKey newBundleID:(NSString *)newBundleID plistOutOptions:(NSPropertyListWriteOptions)options {
NSMutableDictionary *plist = nil;
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
plist = [[[NSMutableDictionary alloc] initWithContentsOfFile:filePath] autorelease];
[plist setObject:newBundleID forKey:bundleIDKey];
NSData *xmlData = [NSPropertyListSerialization dataWithPropertyList:plist format:options options:kCFPropertyListImmutable error:nil];
return [xmlData writeToFile:filePath atomically:YES];
}
return NO;
}
- (void)doProvisioning {
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[workingPath stringByAppendingPathComponent:@"Payload"] error:nil];
for (NSString *file in dirContents) {
if ([[[file pathExtension] lowercaseString] isEqualToString:@"app"]) {
appPath = [[workingPath stringByAppendingPathComponent:@"Payload"] stringByAppendingPathComponent:file];
if ([[NSFileManager defaultManager] fileExistsAtPath:[appPath stringByAppendingPathComponent:@"embedded.mobileprovision"]]) {
NSLog(@"Found embedded.mobileprovision, deleting.");
[[NSFileManager defaultManager] removeItemAtPath:[appPath stringByAppendingPathComponent:@"embedded.mobileprovision"] error:nil];
}
break;
}
}
NSString *targetPath = [appPath stringByAppendingPathComponent:@"embedded.mobileprovision"];
provisioningTask = [[NSTask alloc] init];
[provisioningTask setLaunchPath:@"/bin/cp"];
[provisioningTask setArguments:[NSArray arrayWithObjects:[provisioningPathField stringValue], targetPath, nil]];
[provisioningTask launch];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkProvisioning:) userInfo:nil repeats:TRUE];
}
- (void)checkProvisioning:(NSTimer *)timer {
if ([provisioningTask isRunning] == 0) {
[timer invalidate];
[provisioningTask release];
provisioningTask = nil;
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[workingPath stringByAppendingPathComponent:@"Payload"] error:nil];
for (NSString *file in dirContents) {
if ([[[file pathExtension] lowercaseString] isEqualToString:@"app"]) {
appPath = [[workingPath stringByAppendingPathComponent:@"Payload"] stringByAppendingPathComponent:file];
if ([[NSFileManager defaultManager] fileExistsAtPath:[appPath stringByAppendingPathComponent:@"embedded.mobileprovision"]]) {
BOOL identifierOK = FALSE;
NSString *identifierInProvisioning = @"";
NSString *embeddedProvisioning = [NSString stringWithContentsOfFile:[appPath stringByAppendingPathComponent:@"embedded.mobileprovision"] encoding:NSASCIIStringEncoding error:nil];
NSArray* embeddedProvisioningLines = [embeddedProvisioning componentsSeparatedByCharactersInSet:
[NSCharacterSet newlineCharacterSet]];
for (int i = 0; i <= [embeddedProvisioningLines count]; i++) {
if ([[embeddedProvisioningLines objectAtIndex:i] rangeOfString:@"application-identifier"].location != NSNotFound) {
NSInteger fromPosition = [[embeddedProvisioningLines objectAtIndex:i+1] rangeOfString:@"<string>"].location + 8;
NSInteger toPosition = [[embeddedProvisioningLines objectAtIndex:i+1] rangeOfString:@"</string>"].location;
NSRange range;
range.location = fromPosition;
range.length = toPosition-fromPosition;
NSString *fullIdentifier = [[embeddedProvisioningLines objectAtIndex:i+1] substringWithRange:range];
NSArray *identifierComponents = [fullIdentifier componentsSeparatedByString:@"."];
if ([[identifierComponents lastObject] isEqualTo:@"*"]) {
identifierOK = TRUE;
}
for (int i = 1; i < [identifierComponents count]; i++) {
identifierInProvisioning = [identifierInProvisioning stringByAppendingString:[identifierComponents objectAtIndex:i]];
if (i < [identifierComponents count]-1) {
identifierInProvisioning = [identifierInProvisioning stringByAppendingString:@"."];
}
}
break;
}
}
NSLog(@"Mobileprovision identifier: %@",identifierInProvisioning);
NSString *infoPlist = [NSString stringWithContentsOfFile:[appPath stringByAppendingPathComponent:@"Info.plist"] encoding:NSASCIIStringEncoding error:nil];
if ([infoPlist rangeOfString:identifierInProvisioning].location != NSNotFound) {
NSLog(@"Identifiers match");
identifierOK = TRUE;
}
if (identifierOK) {
NSLog(@"Provisioning completed.");
[statusLabel setStringValue:@"Provisioning completed"];
[self doCodeSigning];
} else {
NSRunAlertPanel(@"Error",
@"Product identifiers don't match",
@"OK",nil,nil);
[self enableControls];
[statusLabel setStringValue:@"Ready"];
}
} else {
NSRunAlertPanel(@"Error",
@"Provisioning failed",
@"OK",nil,nil);
[self enableControls];
[statusLabel setStringValue:@"Ready"];
}
break;
}
}
}
}
- (void)doCodeSigning {
appPath = nil;
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[workingPath stringByAppendingPathComponent:@"Payload"] error:nil];
for (NSString *file in dirContents) {
if ([[[file pathExtension] lowercaseString] isEqualToString:@"app"]) {
appPath = [[workingPath stringByAppendingPathComponent:@"Payload"] stringByAppendingPathComponent:file];
NSLog(@"Found %@",appPath);
appName = [file retain];
[statusLabel setStringValue:[NSString stringWithFormat:@"Codesigning %@",file]];
break;
}
}
if (appPath) {
NSString *resourceRulesPath = [[NSBundle mainBundle] pathForResource:@"ResourceRules" ofType:@"plist"];
NSString *resourceRulesArgument = [NSString stringWithFormat:@"--resource-rules=%@",resourceRulesPath];
codesignTask = [[NSTask alloc] init];
[codesignTask setLaunchPath:@"/usr/bin/codesign"];
[codesignTask setArguments:[NSArray arrayWithObjects:@"-fs", [certField stringValue], resourceRulesArgument, appPath, nil]];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkCodesigning:) userInfo:nil repeats:TRUE];
[appPath retain];
NSPipe *pipe=[NSPipe pipe];
[codesignTask setStandardOutput:pipe];
[codesignTask setStandardError:pipe];
NSFileHandle *handle=[pipe fileHandleForReading];
[codesignTask launch];
[NSThread detachNewThreadSelector:@selector(watchCodesigning:)
toTarget:self withObject:handle];
}
}
- (void)watchCodesigning:(NSFileHandle*)streamHandle {
NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
codesigningResult = [[NSString alloc] initWithData:[streamHandle readDataToEndOfFile] encoding:NSASCIIStringEncoding];
[pool release];
}
- (void)checkCodesigning:(NSTimer *)timer {
if ([codesignTask isRunning] == 0) {
[timer invalidate];
[codesignTask release];
codesignTask = nil;
NSLog(@"Codesigning done");
[statusLabel setStringValue:@"Codesigning completed"];
[self doVerifySignature];
}
}
- (void)doVerifySignature {
if (appPath) {
verifyTask = [[NSTask alloc] init];
[verifyTask setLaunchPath:@"/usr/bin/codesign"];
[verifyTask setArguments:[NSArray arrayWithObjects:@"-v", appPath, nil]];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkVerificationProcess:) userInfo:nil repeats:TRUE];
NSLog(@"Verifying %@",appPath);
[statusLabel setStringValue:[NSString stringWithFormat:@"Verifying %@",appName]];
NSPipe *pipe=[NSPipe pipe];
[verifyTask setStandardOutput:pipe];
[verifyTask setStandardError:pipe];
NSFileHandle *handle=[pipe fileHandleForReading];
[verifyTask launch];
[NSThread detachNewThreadSelector:@selector(watchVerificationProcess:)
toTarget:self withObject:handle];
}
}
- (void)watchVerificationProcess:(NSFileHandle*)streamHandle {
NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
verificationResult = [[NSString alloc] initWithData:[streamHandle readDataToEndOfFile] encoding:NSASCIIStringEncoding];
[pool release];
}
- (void)checkVerificationProcess:(NSTimer *)timer {
if ([verifyTask isRunning] == 0) {
[timer invalidate];
[verifyTask release];
verifyTask = nil;
if ([verificationResult length] == 0) {
NSLog(@"Verification done");
[statusLabel setStringValue:@"Verification completed"];
[self doZip];
} else {
NSString *error = [[codesigningResult stringByAppendingString:@"\n\n"] stringByAppendingString:verificationResult];
NSRunAlertPanel(@"Signing failed", error, @"OK",nil, nil);
[self enableControls];
[statusLabel setStringValue:@"Please try again"];
}
}
}
- (void)doZip {
if (appPath) {
NSArray *destinationPathComponents = [originalIpaPath pathComponents];
NSString *destinationPath = @"";
for (int i = 0; i < ([destinationPathComponents count]-1); i++) {
destinationPath = [destinationPath stringByAppendingPathComponent:[destinationPathComponents objectAtIndex:i]];
}
fileName = [originalIpaPath lastPathComponent];
fileName = [fileName substringToIndex:[fileName length]-4];
fileName = [fileName stringByAppendingString:@"-resigned"];
fileName = [fileName stringByAppendingPathExtension:@"ipa"];
destinationPath = [destinationPath stringByAppendingPathComponent:fileName];
NSLog(@"Dest: %@",destinationPath);
zipTask = [[NSTask alloc] init];
[zipTask setLaunchPath:@"/usr/bin/zip"];
[zipTask setCurrentDirectoryPath:workingPath];
[zipTask setArguments:[NSArray arrayWithObjects:@"-qr", destinationPath, @".", nil]];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkZip:) userInfo:nil repeats:TRUE];
NSLog(@"Zipping %@", destinationPath);
[statusLabel setStringValue:[NSString stringWithFormat:@"Saving %@",fileName]];
[fileName retain];
[zipTask launch];
}
}
- (void)checkZip:(NSTimer *)timer {
if ([zipTask isRunning] == 0) {
[timer invalidate];
[zipTask release];
zipTask = nil;
NSLog(@"Zipping done");
[statusLabel setStringValue:[NSString stringWithFormat:@"Saved %@",fileName]];
[[NSFileManager defaultManager] removeItemAtPath:workingPath error:nil];
[appPath release];
[workingPath release];
[self enableControls];
NSString *result = [[codesigningResult stringByAppendingString:@"\n\n"] stringByAppendingString:verificationResult];
NSLog(@"Codesigning result: %@",result);
}
}
- (IBAction)browse:(id)sender {
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setCanChooseFiles:TRUE];
[openDlg setCanChooseDirectories:FALSE];
[openDlg setAllowsMultipleSelection:FALSE];
[openDlg setAllowsOtherFileTypes:FALSE];
if ( [openDlg runModalForTypes:[NSArray arrayWithObject:@"ipa"]] == NSOKButton )
{
NSString* fileNameOpened = [[openDlg filenames] objectAtIndex:0];
[pathField setStringValue:fileNameOpened];
}
}
- (IBAction)provisioningBrowse:(id)sender {
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setCanChooseFiles:TRUE];
[openDlg setCanChooseDirectories:FALSE];
[openDlg setAllowsMultipleSelection:FALSE];
[openDlg setAllowsOtherFileTypes:FALSE];
if ( [openDlg runModalForTypes:[NSArray arrayWithObject:@"mobileprovision"]] == NSOKButton )
{
NSString* fileNameOpened = [[openDlg filenames] objectAtIndex:0];
[provisioningPathField setStringValue:fileNameOpened];
}
}
- (IBAction)showHelp:(id)sender {
NSRunAlertPanel(@"How to use iReSign",
@"iReSign allows you to re-sign any unencrypted ipa-file with any certificate for which you hold the corresponding private key.\n\n1. Drag your unsigned .ipa file to the top box, or use the browse button.\n\n2. Enter your full certificate name from Keychain Access, for example \"iPhone Developer: Firstname Lastname (XXXXXXXXXX)\" in the bottom box.\n\n3. Click ReSign! and wait. The resigned file will be saved in the same folder as the original file.",
@"OK",nil, nil);
}
- (IBAction)changeBundleIDPressed:(id)sender {
if (sender != changeBundleIDCheckbox) {
return;
}
bundleIDField.enabled = changeBundleIDCheckbox.state == NSOnState;
}
- (void)disableControls {
[pathField setEnabled:FALSE];
[certField setEnabled:FALSE];
[browseButton setEnabled:FALSE];
[resignButton setEnabled:FALSE];
[provisioningBrowseButton setEnabled:NO];
[provisioningPathField setEnabled:NO];
[changeBundleIDCheckbox setEnabled:NO];
[bundleIDField setEnabled:NO];
[flurry startAnimation:self];
[flurry setAlphaValue:1.0];
[self resizeWindow:210];
}
- (void)enableControls {
[pathField setEnabled:TRUE];
[certField setEnabled:TRUE];
[browseButton setEnabled:TRUE];
[resignButton setEnabled:TRUE];
[provisioningBrowseButton setEnabled:YES];
[provisioningPathField setEnabled:YES];
[changeBundleIDCheckbox setEnabled:YES];
[bundleIDField setEnabled:changeBundleIDCheckbox.state == NSOnState];
[flurry stopAnimation:self];
[flurry setAlphaValue:0.5];
}
- (void)resizeWindow:(int)newHeight {
NSRect r;
r = NSMakeRect([window frame].origin.x - ([window frame].size.width - (int)(NSWidth([window frame]))), [window frame].origin.y - (newHeight - (int)(NSHeight([window frame]))), [window frame].size.width, newHeight);
[window setFrame:r display:YES animate:YES];
}
@end