forked from wdmchaft/iSpy
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathiSpy.class.xm
1211 lines (1000 loc) · 38.4 KB
/
iSpy.class.xm
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
/*
* iSpy - Bishop Fox iOS hacking/hooking/sandboxing framework.
*/
#include <stack>
#include <fcntl.h>
#include <stdio.h>
#include <dlfcn.h>
#include <stdarg.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
#include <stdbool.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <sys/mount.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <sys/mman.h>
#include <sys/uio.h>
#include <objc/objc.h>
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <mach-o/dyld.h>
#include <netinet/in.h>
#import <Security/Security.h>
#import <Security/SecCertificate.h>
#include <CFNetwork/CFNetwork.h>
#include <CFNetwork/CFProxySupport.h>
#include <CoreFoundation/CFString.h>
#include <CoreFoundation/CFStream.h>
#import <Foundation/NSJSONSerialization.h>
#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonHMAC.h>
#include "iSpy.common.h"
#include "iSpy.instance.h"
#include "iSpy.class.h"
#include "hooks_C_system_calls.h"
#include "hooks_CoreFoundation.h"
#include <dlfcn.h>
#include <mach-o/nlist.h>
#include <semaphore.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <QuartzCore/QuartzCore.h>
#import "typestring.h"
#import "iSpy.rpc.h"
#include <execinfo.h>
static NSString *changeDateToDateString(NSDate *date);
static char *bf_get_friendly_method_return_type(Method method);
static char *bf_get_attrs_from_signature(char *attributeCString);
static pthread_mutex_t mutex_methodsForClass = PTHREAD_MUTEX_INITIALIZER;
id *appClassWhiteList = NULL;
/*************************************************************************************************
This is the "iSpy" class implementation. It does cool stuff. We use it quite a lot inside
the iSpy .dylib. It's used as a singleton. For example, consider the following code:
%hook myTargetAppCoolClass
-(void) someInterestingMethod {
// get access to the iSpy singleton
mySpy *mySpy = [iSpy sharedInstance];
// turn on the strace logger
[mySpy strace_enableLogging];
// perform the original interesting method
%orig;
// turn off the strace logger
[mySpy strace_disableLogging];
// do analysis of the data or whatever.
return;
}
%end
This class is also exposed to Cycript, which makes it possible to interact with iSpy at runtime:
cycript -p <PID>
mySpy = [iSpy sharedInstance]
[mySpy instance_enableTracking]
...
[mySpy instance_dumpAppInstancesWithPointers];
The method names are kinda weird (often beginning with instance_, or msgSend_, or strace_, etc.)
This is to make Cycript's tab-completion a joy to use by grouping methods together in an
intuitive manner inside the Cycript REPL. For example, let's say you're using cycript and want
to do something with iSpy's instance tracking support:
cy# x = [iSpy sharedInstance ]
"<iSpy: 0x1cd74cd0>"
cy# [x instance_<<press tab twice>>
instance_disableTracking instance_dumpAppInstancesWithPointers instance_enableTracking instance_searchInstances:
instance_dumpAllInstancesWithPointers instance_dumpAppInstancesWithPointersArray instance_numberOfTrackedInstances
Voila! All the instance support functions appear. Same for msgSend, strace, etc.
**************************************************************************************************/
@implementation iSpy
// Returns the singleton
+(iSpy *)sharedInstance {
static iSpy *sharedInstance;
static dispatch_once_t once;
dispatch_once(&once, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
-(void)initializeAllTheThings {
static dispatch_once_t once;
dispatch_once(&once, ^{
NSLog(@"[iSpy] Initializing singleton ...");
NSLog(@"[iSpy] Alloc the iSpyServer ...");
[self setWebServer:[[iSpyServer alloc] init]];
[self setGlobalStatusStr:@""];
NSLog(@"[iSpy] Setting the bundleIdentifier");
[self setBundleId:[[[NSBundle mainBundle] bundleIdentifier] copy]];
[self setIsInstanceTrackingEnabled: NO];
NSLog(@"[iSpy] Setting up RPCHandler ...");
[[self webServer] setRpcHandler:[[RPCHandler alloc] init]];
self->_trackedInstances = [[NSMutableDictionary alloc] init];
NSLog(@"[iSpy] Configuring web server ...");
[[self webServer] configureWebServer];
NSLog(@"[iSpy] Initialization complete.");
});
}
// Given the name of a class, this returns true if the class is declared in the target app, false if not.
// It's waaaaaay faster than checking bundleForClass shit from the Apple runtime.
+(BOOL)isClassFromApp:(NSString *)className {
char *appName = (char *) [[[NSProcessInfo processInfo] arguments][0] UTF8String];
char *imageName = (char *)class_getImageName(objc_getClass([className UTF8String]));
char *p = NULL;
char *imageNamePtr = imageName;
if(!imageName) {
return false;
}
if(!(p = strrchr(imageName, '/'))) {
return false;
}
// Support iOS 8
if(strncmp(imageName, "/private", 8) == 0 && strncmp(appName, "/private", 8) != 0)
imageNamePtr += 8;
if(strncmp(imageNamePtr, appName, p-imageName-1) == 0) {
return true;
}
return false;
}
/*
*
* Methods for working with objc_msgSend logging.
*
*/
// A lot of methods are just wrappers around pure C calls, which has the effect of exposing core iSpy features
// to Cycript for advanced use.
// Turn on objc_msgSend logging
-(void) msgSend_enableLogging {
bf_enable_msgSend_logging();
}
// Turn off objc_msgSend logging
-(void) msgSend_disableLogging {
bf_disable_msgSend_logging();
}
-(NSString *) msgSend_setBreakpointOnMethod:(NSString *)methodName inClass:(NSString *)className {
struct interestingCall *call = (struct interestingCall *)malloc(sizeof(struct interestingCall));
call->classification = strdup("Breakpoint");
call->type = INTERESTING_BREAKPOINT;
call->risk = strdup("");
call->description = strdup("");
call->className = strdup([className UTF8String]);
call->methodName = strdup([methodName UTF8String]);
whitelist_add_method(&std::string([className UTF8String]), &std::string([methodName UTF8String]), (unsigned int)call);
return @"ok";
}
-(NSString *) msgSend_releaseBreakpointForMethod:(NSString *)methodName inClass:(NSString *)className {
breakpoint_release_breakpoint([className UTF8String], [methodName UTF8String]);
return @"ok";
}
-(NSString *) msgSend_addInterestingMethodToWhitelist:(NSString *)methodName
forClass:(NSString *)className
ofClassicication:(NSString *)classification
withDescription:(NSString *)description
havingRisk:(NSString *)risk {
[self _msgSend_addInterestingMethodToWhitelist:methodName
forClass:className
ofClassicication:classification
withDescription:description
havingRisk:risk
ofType:WHITELIST_PRESENT];
return @"ok";
}
-(NSString *) _msgSend_addInterestingMethodToWhitelist:(NSString *)methodName
forClass:(NSString *)className
ofClassicication:(NSString *)classification
withDescription:(NSString *)description
havingRisk:(NSString *)risk
ofType:(unsigned int)type {
struct interestingCall *call = (struct interestingCall *)malloc(sizeof(struct interestingCall));
call->risk = strdup([risk UTF8String]);
call->className = strdup([className UTF8String]);
call->methodName = strdup([methodName UTF8String]);
call->description = strdup([description UTF8String]);
call->classification = strdup([classification UTF8String]);
call->type = (int)type;
whitelist_add_method(&std::string(call->className), &std::string(call->methodName), (unsigned int)call);
return @"ok";
}
-(NSString *) msgSend_addMethodToWhitelist:(NSString *)methodName forClass:(NSString *)className {
return [self _msgSend_addMethodToWhitelist:methodName forClass:className ofType:(struct interestingCall *)WHITELIST_PRESENT];
}
-(NSString *) _msgSend_addMethodToWhitelist:(NSString *)methodName forClass:(NSString *)className ofType:(struct interestingCall *)call {
if(!methodName || !className) {
return @"Nil value for class or method name";
}
std::string *classNameString = new std::string([className UTF8String]);
std::string *methodNameString = new std::string([methodName UTF8String]);
if(!classNameString || !methodNameString) {
if(methodNameString)
delete methodNameString;
if(classNameString)
delete classNameString;
return @"Error converting NSStrings to std::strings";
}
whitelist_add_method(classNameString, methodNameString, (unsigned int)call);
delete methodNameString;
delete classNameString;
return @"ok";
}
-(NSString *)msgSend_addClassToWhitelist:(NSString *) className {
NSArray *classes = [self methodsForClass:className];
for(int i = 0; i < [classes count]; i++) {
[self msgSend_addMethodToWhitelist:[[classes objectAtIndex:i] objectForKey:@"name"] forClass:className];
}
return @"ok";
}
-(NSString *) msgSend_clearWhitelist {
whitelist_clear_whitelist();
return @"ok";
}
-(NSString *) msgSend_addAppClassesToWhitelist {
whitelist_add_app_classes();
return @"ok";
}
/*
*
* Methods for working with instaniated objects.
*
*/
-(void) instance_enableTracking {
[[InstanceTracker sharedInstance] start];
}
-(void) instance_disableTracking {
[[InstanceTracker sharedInstance] stop];
}
-(BOOL) instance_getTrackingState {
return [[InstanceTracker sharedInstance] enabled];
}
/*
*
* Methods for working with the keychain.
*
*/
-(NSDictionary *)keyChainItems {
NSMutableDictionary *genericQuery = [[NSMutableDictionary alloc] init];
NSMutableDictionary *keychainDict = [[NSMutableDictionary alloc] init];
// genp, inet, idnt, cert, keys
NSArray *items = [NSArray arrayWithObjects:(id)kSecClassGenericPassword, kSecClassInternetPassword, kSecClassIdentity, kSecClassCertificate, kSecClassKey, nil];
NSArray *descs = [NSArray arrayWithObjects:(id)@"Generic Passwords", @"Internet Passwords", @"Identities", @"Certificates", @"Keys", nil];
NSDictionary *kSecAttrs = @{
@"ak": @"kSecAttrAccessibleWhenUnlocked",
@"ck": @"kSecAttrAccessibleAfterFirstUnlock",
@"dk": @"kSecAttrAccessibleAlways",
@"aku": @"kSecAttrAccessibleWhenUnlockedThisDeviceOnly",
@"cku": @"kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly",
@"dku": @"kSecAttrAccessibleAlwaysThisDeviceOnly"
};
int i = 0, j, count;
count = [items count];
do {
NSMutableArray *keychainItems = nil;
[genericQuery setObject:(id)[items objectAtIndex:i] forKey:(id)kSecClass];
[genericQuery setObject:(id)kSecMatchLimitAll forKey:(id)kSecMatchLimit];
[genericQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnAttributes];
[genericQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnRef];
[genericQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];
if (SecItemCopyMatching((CFDictionaryRef)genericQuery, (CFTypeRef *)&keychainItems) == noErr) {
// Loop through the keychain entries, logging them.
for(j = 0; j < [keychainItems count]; j++) {
for(NSString *key in [[keychainItems objectAtIndex:j] allKeys]) {
// We don't need the v_Ref attribute; it's just an another representation of v_data that won't serialize to JSON. Pfft.
if([key isEqual:@"v_Ref"]) {
[[keychainItems objectAtIndex:j] removeObjectForKey:key];
}
// Is this some kind of NSData/__NSFSData/etc?
// NSJSONSerializer won't parse NSDate or NSData, so we convert any of those into NSString for later JSON-ification.
if([[[keychainItems objectAtIndex:j] objectForKey:key] respondsToSelector:@selector(bytes)]) {
NSString *str = [[NSString alloc] initWithData:[[keychainItems objectAtIndex:j] objectForKey:key] encoding:NSUTF8StringEncoding];
if(str == nil)
str = @"";
[[keychainItems objectAtIndex:j] setObject:str forKey:key];
}
// how about NSDate?
else if([[[keychainItems objectAtIndex:j] objectForKey:key] respondsToSelector:@selector(isEqualToDate:)]) {
[[keychainItems objectAtIndex:j] setObject:changeDateToDateString([[keychainItems objectAtIndex:j] objectForKey:key]) forKey:key];
}
// add a human-readable kSecAttr value to the "v_pdmn" key. It's only for UI purposes.
[[keychainItems objectAtIndex:j] setObject:[kSecAttrs objectForKey:[[keychainItems objectAtIndex:j] objectForKey:@"pdmn"]] forKey:@"v_pdmn"];
// Security check. Report any occurences of insecure storage.
NSString *attr = [kSecAttrs objectForKey:[[keychainItems objectAtIndex:j] objectForKey:@"pdmn"]];
if([attr isEqual:@"kSecAttrAccessibleAlways"] || [attr isEqual:@"kSecAttrAccessibleAlwaysThisDeviceOnly"]) {
NSString *strName;
if([[[keychainItems objectAtIndex:j] objectForKey:@"acct"] respondsToSelector:@selector(bytes)]) {
NSString *str = [[NSString alloc] initWithData:[[keychainItems objectAtIndex:j] objectForKey:@"acct"] encoding:NSUTF8StringEncoding];
if(str == nil)
str = @"";
strName = str;
} else {
strName = [NSString stringWithFormat:@"%@", [[keychainItems objectAtIndex:j] objectForKey:@"acct"]];
}
ispy_log_debug(LOG_REPORT, "[Insecure Keychain Storage] Key \"%s\" has attribute \"%s\" on item \"%s\"", [key UTF8String], [attr UTF8String], [strName UTF8String]);
}
}
}
} else {
keychainItems = [[NSMutableArray alloc] initWithObjects:@"", nil];
}
[keychainDict setObject:keychainItems forKey:[descs objectAtIndex:i]];
} while(++i < count);
return keychainDict;
}
-(unsigned int)ASLR {
unsigned int slide = (unsigned int)_dyld_get_image_vmaddr_slide(0);
// security check - log all instances of non-ASLR apps
if(slide == 0)
ispy_log_debug(LOG_REPORT, "[Insecure ASLR] ASLR is disabled for this app. Slide = 0.");
return slide;
}
/*
*
* Methods for working with methods
*
*/
/*
Returns a NSDictionary like this:
{
"name" = "doSomething:forString:withChars:",
"parameters" = {
// name = type
"arg1" = "id",
"arg2" = "NSString *",
"arg3" = "char *"
},
"returnType" = "void";
}
*/
-(NSDictionary *)infoForMethod:(SEL)selector inClass:(Class)cls {
return [self infoForMethod:selector inClass:cls isInstanceMethod:1];
}
-(NSDictionary *)infoForMethod:(SEL)selector inClass:(Class)cls isInstanceMethod:(BOOL)isInstance {
Method method = nil;
BOOL isInstanceMethod = true;
NSMutableArray *parameters = [[NSMutableArray alloc] init];
NSMutableDictionary *methodInfo = [[NSMutableDictionary alloc] init];
int numArgs, k;
NSString *returnType;
char *freeMethodName, *methodName, *tmp;
if(cls == nil || selector == nil)
return nil;
if([cls instancesRespondToSelector:selector] == YES) {
method = class_getInstanceMethod(cls, selector);
} else if([object_getClass(cls) respondsToSelector:selector] == YES) {
method = class_getClassMethod(object_getClass(cls), selector);
isInstanceMethod = false;
} else {
NSLog(@"Method not found");
return nil;
}
if (method == nil) {
NSLog(@"Method returned nil");
return nil;
}
numArgs = method_getNumberOfArguments(method);
// get the method's name as a (char *)
freeMethodName = methodName = (char *)strdup(sel_getName(method_getName(method)));
// cycle through the paramter list for this method.
// start at k=2 so that we omit Cls and SEL, the first 2 args of every function/method
for(k=2; k < numArgs; k++) {
char tmpBuf[256]; // safe and reasonable limit on var name length
char *type;
char *name;
NSMutableDictionary *param = [[NSMutableDictionary alloc] init];
name = strsep(&methodName, ":");
if(!name) {
ispy_log_debug(LOG_GENERAL, "um, so p=NULL in arg printer for class methods... weird.");
continue;
}
method_getArgumentType(method, k, tmpBuf, 255);
if((type = (char *)bf_get_type_from_signature(tmpBuf))==NULL) {
ispy_log_wtf(LOG_GENERAL, "Out of mem?");
break;
}
[param setObject:[NSString stringWithUTF8String:type] forKey:@"type"];
[param setObject:[NSString stringWithUTF8String:name] forKey:@"name"];
[parameters addObject:param];
free(type);
} // args
tmp = (char *)bf_get_friendly_method_return_type(method);
if (!tmp) {
returnType = @"XXX_unknown_type_XXX";
} else {
returnType = [NSString stringWithUTF8String:tmp];
free(tmp);
}
[methodInfo setObject:parameters forKey:@"parameters"];
[methodInfo setObject:returnType forKey:@"returnType"];
[methodInfo setObject:[NSString stringWithUTF8String:freeMethodName] forKey:@"name"];
[methodInfo setObject:[NSNumber numberWithInt:isInstanceMethod] forKey:@"isInstanceMethod"];
free(freeMethodName);
return [methodInfo copy];
}
/*
*
* Methods for working with classes
*
*/
-(id)iVarsForClass:(NSString *)className {
unsigned int iVarCount = 0, j;
Ivar *ivarList = class_copyIvarList(objc_getClass([className UTF8String]), &iVarCount);
NSMutableArray *iVars = [[NSMutableArray alloc] init];
if(!ivarList)
return nil; //[iVars copy];
for(j = 0; j < iVarCount; j++) {
NSMutableDictionary *iVar = [[NSMutableDictionary alloc] init];
char *name = (char *)ivar_getName(ivarList[j]);
char *type = bf_get_type_from_signature((char *)ivar_getTypeEncoding(ivarList[j]));
[iVar setObject:[NSString stringWithUTF8String:type] forKey:[NSString stringWithUTF8String:name]];
[iVars addObject:iVar];
free(type);
}
return [iVars copy];
}
-(id)propertiesForClass:(NSString *)className {
unsigned int propertyCount = 0, j;
objc_property_t *propertyList = class_copyPropertyList(objc_getClass([className UTF8String]), &propertyCount);
NSMutableArray *properties = [[NSMutableArray alloc] init];
if(!propertyList)
return nil; //[properties copy];
for(j = 0; j < propertyCount; j++) {
NSMutableDictionary *property = [[NSMutableDictionary alloc] init];
char *name = (char *)property_getName(propertyList[j]);
char *attr = bf_get_attrs_from_signature((char *)property_getAttributes(propertyList[j]));
[property setObject:[NSString stringWithUTF8String:attr] forKey:[NSString stringWithUTF8String:name]];
[properties addObject:property];
free(attr);
}
return [properties copy];
}
-(id)protocolsForClass:(NSString *)className {
unsigned int protocolCount = 0, j;
Protocol **protocols = class_copyProtocolList(objc_getClass([className UTF8String]), &protocolCount);
NSMutableArray *protocolList = [[NSMutableArray alloc] init];
if(protocolCount <= 0)
return protocolList;
// some of this code was inspired by (and a little of it is copy/pasta) https://gist.github.com/markd2/5961219
for(j = 0; j < protocolCount; j++) {
NSMutableArray *adoptees;
NSMutableDictionary *protocolInfoDict = [[NSMutableDictionary alloc] init];
const char *protocolName = protocol_getName(protocols[j]);
unsigned int adopteeCount;
Protocol **adopteesList = protocol_copyProtocolList(protocols[j], &adopteeCount);
adoptees = [[NSMutableArray alloc] init];
for(int i = 0; i < adopteeCount; i++) {
const char *adopteeName = protocol_getName(adopteesList[i]);
if(!adopteeName)
continue; // skip broken names
[adoptees addObject:[NSString stringWithUTF8String:adopteeName]];
}
free(adopteesList);
[protocolInfoDict setObject:[NSString stringWithUTF8String:protocolName] forKey:@"protocolName"];
[protocolInfoDict setObject:adoptees forKey:@"adoptees"];
[protocolInfoDict setObject:[self propertiesForProtocol:protocols[j]] forKey:@"properties"];
[protocolInfoDict setObject:[self methodsForProtocol:protocols[j]] forKey:@"methods"];
[protocolList addObject:protocolInfoDict];
}
free(protocols);
return [protocolList copy];
}
/*
* returns an NSArray of NSDictionaries, each containing metadata (name, class/instance, etc) about a method for the specified class.
*/
-(id)methodsForClass:(NSString *)className {
unsigned int numClassMethods = 0;
unsigned int numInstanceMethods = 0;
unsigned int i;
NSMutableArray *methods = [[NSMutableArray alloc] init];
Class c;
char *classNameUTF8;
Method *classMethodList = NULL;
Method *instanceMethodList = NULL;
if(!className) {
return nil; //[methods copy];
}
if((classNameUTF8 = (char *)[className UTF8String]) == NULL) {
return nil; //[methods copy];
}
ispy_log_debug(LOG_GENERAL, "methodsForClass: %s", classNameUTF8);
Class cls = objc_getClass(classNameUTF8);
if(cls == nil)
return nil; //[methods copy];
ispy_log_debug(LOG_GENERAL, "getClass: %s", classNameUTF8);
c = object_getClass(cls);
if(c) {
ispy_log_debug(LOG_GENERAL, "class_methods: %s", classNameUTF8);
pthread_mutex_lock(&mutex_methodsForClass);
classMethodList = class_copyMethodList(c, &numClassMethods);
pthread_mutex_unlock(&mutex_methodsForClass);
}
else {
classMethodList = NULL;
numClassMethods = 0;
}
ispy_log_debug(LOG_GENERAL, "instance_methods: %s", classNameUTF8);
pthread_mutex_lock(&mutex_methodsForClass);
instanceMethodList = class_copyMethodList(cls, &numInstanceMethods);
pthread_mutex_unlock(&mutex_methodsForClass);
ispy_log_debug(LOG_GENERAL, "got: %d", numInstanceMethods);
if( (classMethodList == nil && instanceMethodList == nil) ||
(numClassMethods == 0 && numInstanceMethods ==0))
return nil;
if(classMethodList != NULL) {
for(i = 0; i < numClassMethods; i++) {
ispy_log_debug(LOG_GENERAL, "class method: %d", i);
if(!classMethodList[i])
continue;
pthread_mutex_lock(&mutex_methodsForClass);
SEL sel = method_getName(classMethodList[i]);
pthread_mutex_unlock(&mutex_methodsForClass);
if(!sel)
continue;
pthread_mutex_lock(&mutex_methodsForClass);
NSDictionary *methodInfo = [[iSpy sharedInstance] infoForMethod:sel inClass:cls];
if(methodInfo != nil)
[methods addObject:methodInfo];
pthread_mutex_unlock(&mutex_methodsForClass);
}
free(classMethodList);
}
if(instanceMethodList != NULL) {
for(i = 0; i < numInstanceMethods; i++) {
ispy_log_debug(LOG_GENERAL, "instance method: %d", i);
if(!instanceMethodList[i])
continue;
pthread_mutex_lock(&mutex_methodsForClass);
ispy_log_debug(LOG_GENERAL, "sel");
SEL sel = method_getName(instanceMethodList[i]);
pthread_mutex_unlock(&mutex_methodsForClass);
if(!sel)
continue;
ispy_log_debug(LOG_GENERAL, "info");
pthread_mutex_lock(&mutex_methodsForClass);
NSDictionary *methodInfo = [[iSpy sharedInstance] infoForMethod:sel inClass:cls];
if(methodInfo != nil)
[methods addObject:methodInfo];
pthread_mutex_unlock(&mutex_methodsForClass);
}
free(instanceMethodList);
}
pthread_mutex_unlock(&mutex_methodsForClass);
if([methods count] <= 0)
return nil;
else
return [methods copy];
}
/*
* Returns an NSArray of NSString names, each of which is a method name for the specified class.
* You should release the returned NSArray.
*/
-(NSArray *)methodListForClass:(NSString *)className {
unsigned int numClassMethods = 0;
unsigned int numInstanceMethods = 0;
unsigned int i;
NSMutableArray *methods = [[NSMutableArray alloc] init];
Class c;
char *classNameUTF8;
Method *classMethodList = NULL;
Method *instanceMethodList = NULL;
if(!className)
return nil; //[methods copy];
if((classNameUTF8 = (char *)[className UTF8String]) == NULL)
return nil; //[methods copy];
Class cls = objc_getClass(classNameUTF8);
if(cls == nil)
return nil; //[methods copy];
c = object_getClass(cls);
if(c) {
classMethodList = class_copyMethodList(c, &numClassMethods);
}
else {
classMethodList = NULL;
numClassMethods = 0;
}
instanceMethodList = class_copyMethodList(cls, &numInstanceMethods);
if( (classMethodList == nil && instanceMethodList == nil) ||
(numClassMethods == 0 && numInstanceMethods ==0))
return nil;
if(classMethodList != NULL) {
for(i = 0; i < numClassMethods; i++) {
if(!classMethodList[i])
continue;
SEL sel = method_getName(classMethodList[i]);
if(sel)
[methods addObject:[NSString stringWithUTF8String:sel_getName(sel)]];
}
free(classMethodList);
}
if(instanceMethodList != NULL) {
for(i = 0; i < numInstanceMethods; i++) {
if(!instanceMethodList[i])
continue;
SEL sel = method_getName(instanceMethodList[i]);
if(sel)
[methods addObject:[NSString stringWithUTF8String:sel_getName(sel)]];
}
free(instanceMethodList);
}
if([methods count] <= 0)
return nil;
else
return (NSArray *)[methods copy];
}
-(id)classes {
Class * classes = NULL;
NSMutableArray *classArray = [[NSMutableArray alloc] init];
int numClasses;
numClasses = objc_getClassList(NULL, 0);
if(numClasses <= 0)
return nil; //[classArray copy];
if((classes = (Class *)malloc(sizeof(Class) * numClasses)) == NULL)
return [classArray copy];
objc_getClassList(classes, numClasses);
int i=0;
while(i < numClasses) {
NSString *className = [NSString stringWithUTF8String:class_getName(classes[i])];
if([iSpy isClassFromApp:className])
[classArray addObject:className];
i++;
}
return [classArray copy];
}
-(id)classesWithSuperClassAndProtocolInfo {
Class * classes = NULL;
NSMutableArray *classArray = [[NSMutableArray alloc] init];
int numClasses;
unsigned int numProtocols;
numClasses = objc_getClassList(NULL, 0);
if(numClasses <= 0) {
NSLog(@"No classes");
return nil; //[classArray copy];
} else {
NSLog(@"Got %d classes", numClasses);
}
if((classes = (Class *)malloc(sizeof(Class) * numClasses)) == NULL)
return [classArray copy];
objc_getClassList(classes, numClasses);
int i=0;
while(i < numClasses) {
NSString *className = [NSString stringWithUTF8String:class_getName(classes[i])];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
if([iSpy isClassFromApp:className]) {
Protocol **protocols = class_copyProtocolList(classes[i], &numProtocols);
Class superClass = class_getSuperclass(classes[i]);
char *superClassName = NULL;
if(superClass)
superClassName = (char *)class_getName(superClass);
[dict setObject:className forKey:@"className"];
[dict setObject:[NSString stringWithUTF8String:superClassName] forKey:@"superClass"];
NSMutableArray *pr = [[NSMutableArray alloc] init];
if(numProtocols) {
for(int i = 0; i < numProtocols; i++) {
[pr addObject:[NSString stringWithUTF8String:protocol_getName(protocols[i])]];
}
free(protocols);
}
[dict setObject:pr forKey:@"protocols"];
[classArray addObject:dict];
}
i++;
}
return [classArray copy];
}
/*
* The following function returns an NSDictionary, like so:
{
"MyClass1": {
"className": "MyClass1",
"superClass": "class name",
"methods": {
},
"ivars": {
},
"properties": {
},
"protocols": {
}
},
"MyClass2": {
"methods": {
},
"ivars": {
},
"properties": {
},
"protocols": {
}
},
...
}
*/
-(NSDictionary *)classDump {
NSMutableDictionary *classDumpDict = [[NSMutableDictionary alloc] init];
NSArray *clsList = [self classesWithSuperClassAndProtocolInfo]; // returns an array of dictionaries
NSLog(@"[iSpy] Got %d classes", [clsList count]);
for(int i = 0; i < [clsList count]; i++) {
NSMutableDictionary *cls = [[clsList objectAtIndex:i] mutableCopy];
NSString *className = [cls objectForKey:@"className"];
[cls setObject:[NSArray arrayWithArray:[self methodsForClass:className]] forKey:@"methods"];
[cls setObject:[NSArray arrayWithArray:[self iVarsForClass:className]] forKey:@"ivars"];
[cls setObject:[NSArray arrayWithArray:[self propertiesForClass:className]] forKey:@"properties"];
[cls setObject:[NSArray arrayWithArray:[self methodsForClass:className]] forKey:@"methods"];
[classDumpDict setObject:[NSDictionary dictionaryWithDictionary:cls] forKey:className];
[cls release];
}
return [classDumpDict copy];
}
// This function does the same thing, only for a single specified class name.
-(NSDictionary *)classDumpClass:(NSString *)className {
NSMutableDictionary *cls = [[NSMutableDictionary alloc] init];
Class theClass = objc_getClass([className UTF8String]);
unsigned int numProtocols;
Class superClass = class_getSuperclass(theClass);
char *superClassName = NULL;
if(superClass)
superClassName = (char *)class_getName(superClass);
Protocol **protocols = class_copyProtocolList(theClass, &numProtocols);
NSMutableArray *pr = [[NSMutableArray alloc] init];
if(numProtocols) {
for(int i = 0; i < numProtocols; i++) {
[pr addObject:[NSString stringWithUTF8String:protocol_getName(protocols[i])]];
}
free(protocols);
}
[cls setObject:pr forKey:@"protocols"];
[cls setObject:className forKey:@"className"];
[cls setObject:[NSString stringWithUTF8String:superClassName] forKey:@"superClass"];
[cls setObject:[NSArray arrayWithArray:[self methodsForClass:className]] forKey:@"methods"];
[cls setObject:[NSArray arrayWithArray:[self iVarsForClass:className]] forKey:@"ivars"];
[cls setObject:[NSArray arrayWithArray:[self propertiesForClass:className]] forKey:@"properties"];
return (NSDictionary *)[cls copy];
}
/*
*
* Methods for working with protocols.
*
*/
-(id)propertiesForProtocol:(Protocol *)protocol {
unsigned int propertyCount = 0, j;
objc_property_t *propertyList = protocol_copyPropertyList(protocol, &propertyCount);
NSMutableArray *properties = [[NSMutableArray alloc] init];
if(!propertyList)
return properties;
for(j = 0; j < propertyCount; j++) {
NSMutableDictionary *property = [[NSMutableDictionary alloc] init];
char *name = (char *)property_getName(propertyList[j]);
char *attr = bf_get_attrs_from_signature((char *)property_getAttributes(propertyList[j]));
[property setObject:[NSString stringWithUTF8String:attr] forKey:[NSString stringWithUTF8String:name]];
[properties addObject:property];
free(attr);
}
return [properties copy];
}
-(id)methodsForProtocol:(Protocol *)protocol {
BOOL isReqVals[4] = {NO, NO, YES, YES};
BOOL isInstanceVals[4] = {NO, YES, NO, YES};
unsigned int methodCount;
NSMutableArray *methods = [[NSMutableArray alloc] init];
for( int i = 0; i < 4; i++ ){
struct objc_method_description *methodDescriptionList = protocol_copyMethodDescriptionList(protocol, isReqVals[i], isInstanceVals[i], &methodCount);
if(!methodDescriptionList)
continue;
if(methodCount <= 0) {
free(methodDescriptionList);
continue;
}
NSMutableDictionary *methodInfo = [[NSMutableDictionary alloc] init];
for(int j = 0; j < methodCount; j++) {
NSArray *types = ParseTypeString([NSString stringWithUTF8String:methodDescriptionList[j].types]);
[methodInfo setObject:[NSString stringWithUTF8String:sel_getName(methodDescriptionList[j].name)] forKey:@"methodName"];
[methodInfo setObject:[types objectAtIndex:0] forKey:@"returnType"];
[methodInfo setObject:((isReqVals[i]) ? @"1" : @"0") forKey:@"required"];
[methodInfo setObject:((isInstanceVals[i]) ? @"1" : @"0") forKey:@"instance"];
NSMutableArray *params = [[NSMutableArray alloc] init];
if([types count] > 3) { // return_type, class, selector, ...
NSRange range;
range.location = 3;
range.length = [types count]-3;
[params addObject:[types subarrayWithRange:range]];
}
[methodInfo setObject:params forKey:@"parameters"];
}
[methods addObject:methodInfo];
free(methodDescriptionList);
}
return [methods copy];
}
-(NSDictionary *)protocolDump {
unsigned int protocolCount = 0, j;
Protocol **protocols = objc_copyProtocolList(&protocolCount);
NSMutableDictionary *protocolList = [[NSMutableDictionary alloc] init];
if(protocolCount <= 0)
return protocolList;
// some of this code was inspired by (and a little of it is copy/pasta) https://gist.github.com/markd2/5961219
for(j = 0; j < protocolCount; j++) {
NSMutableArray *adoptees;
NSMutableDictionary *protocolInfoDict = [[NSMutableDictionary alloc] init];
const char *protocolName = protocol_getName(protocols[j]);
unsigned int adopteeCount;
Protocol **adopteesList = protocol_copyProtocolList(protocols[j], &adopteeCount);
if(!adopteeCount) {
free(adopteesList);
continue;
}
adoptees = [[NSMutableArray alloc] init];
for(int i = 0; i < adopteeCount; i++) {
const char *adopteeName = protocol_getName(adopteesList[i]);
if(!adopteeName) {
free(adopteesList);
continue; // skip broken names or shit we don't care about