# macOS Objective-C
Impara l'hacking di AWS da zero a esperto con htARTE (HackTricks AWS Red Team Expert)! Altri modi per supportare HackTricks: * Se vuoi vedere la tua **azienda pubblicizzata in HackTricks** o **scaricare HackTricks in PDF** Controlla i [**PACCHETTI DI ABBONAMENTO**](https://github.com/sponsors/carlospolop)! * Ottieni il [**merchandising ufficiale di PEASS & HackTricks**](https://peass.creator-spring.com) * Scopri [**The PEASS Family**](https://opensea.io/collection/the-peass-family), la nostra collezione di [**NFT**](https://opensea.io/collection/the-peass-family) esclusivi * **Unisciti al** 💬 [**gruppo Discord**](https://discord.gg/hRep4RUj7f) o al [**gruppo Telegram**](https://t.me/peass) o **seguici** su **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)**.** * **Condividi i tuoi trucchi di hacking inviando PR ai** [**HackTricks**](https://github.com/carlospolop/hacktricks) e [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
## Objective-C {% hint style="danger" %} Nota che i programmi scritti in Objective-C **mantengono** le loro dichiarazioni di classe **quando** **compilati** in [binari Mach-O](macos-files-folders-and-binaries/universal-binaries-and-mach-o-format.md). Tali dichiarazioni di classe **includono** il nome e il tipo di: {% endhint %} * La classe * I metodi di classe * Le variabili di istanza della classe Puoi ottenere queste informazioni utilizzando [**class-dump**](https://github.com/nygard/class-dump): ```bash class-dump Kindle.app ``` Nota che questi nomi potrebbero essere oscurati per rendere più difficile il reverse engineering del binario. ## Classi, Metodi e Oggetti ### Interfacce, Proprietà e Metodi ```objectivec // Declare the interface of the class @interface MyVehicle : NSObject // Declare the properties @property NSString *vehicleType; @property int numberOfWheels; // Declare the methods - (void)startEngine; - (void)addWheels:(int)value; @end ``` ### **Classe** ```objectivec @implementation MyVehicle : NSObject // No need to indicate the properties, only define methods - (void)startEngine { NSLog(@"Engine started"); } - (void)addWheels:(int)value { self.numberOfWheels += value; } @end ``` ### **Oggetto e Metodo di Chiamata** Per creare un'istanza di una classe viene chiamato il metodo **`alloc`** che **alloca memoria** per ogni **proprietà** e **azzera** tali allocazioni. Successivamente viene chiamato **`init`**, che **inizializza le proprietà** ai **valori richiesti**. ```objectivec // Something like this: MyVehicle *newVehicle = [[MyVehicle alloc] init]; // Which is usually expressed as: MyVehicle *newVehicle = [MyVehicle new]; // To call a method // [myClassInstance nameOfTheMethodFirstParam:param1 secondParam:param2] [newVehicle addWheels:4]; ``` ### **Metodi di classe** I metodi di classe sono definiti con il **segno più** (+) e non con il trattino (-) che viene utilizzato con i metodi di istanza. Come il metodo di classe **`stringWithString`** della classe **NSString**: ```objectivec + (id)stringWithString:(NSString *)aString; ``` ### Setter & Getter Per **impostare** e **ottenere** le proprietà, è possibile farlo con la **notazione a punto** o come se si stesse **chiamando un metodo**: ```objectivec // Set newVehicle.numberOfWheels = 2; [newVehicle setNumberOfWheels:3]; // Get NSLog(@"Number of wheels: %i", newVehicle.numberOfWheels); NSLog(@"Number of wheels: %i", [newVehicle numberOfWheels]); ``` ### **Variabili di istanza** In alternativa ai metodi setter e getter, è possibile utilizzare le variabili di istanza. Queste variabili hanno lo stesso nome delle proprietà, ma iniziano con un "\_": ```objectivec - (void)makeLongTruck { _numberOfWheels = +10000; NSLog(@"Number of wheels: %i", self.numberOfLeaves); } ``` ### Protocolli I protocolli sono insiemi di dichiarazioni di metodi (senza proprietà). Una classe che implementa un protocollo implementa i metodi dichiarati. Ci sono 2 tipi di metodi: **obbligatori** e **opzionali**. Per **default** un metodo è **obbligatorio** (ma puoi anche indicarlo con un tag **`@required`**). Per indicare che un metodo è opzionale, usa **`@optional`**. ```objectivec @protocol myNewProtocol - (void) method1; //mandatory @required - (void) method2; //mandatory @optional - (void) method3; //optional @end ``` ### Tutto insieme In questo capitolo, metteremo insieme tutte le informazioni che abbiamo appreso finora per ottenere un'immagine completa della sicurezza e dell'escalation dei privilegi su macOS. Discuteremo delle basi di Objective-C e di come utilizzare questa conoscenza per individuare vulnerabilità e sfruttarle. Esploreremo anche alcune tecniche di hardening per proteggere un sistema macOS da attacchi e privilegi di escalation. Infine, forniremo una panoramica delle tecniche di post-exploitation che possono essere utilizzate per mantenere l'accesso a un sistema compromesso. ```objectivec // gcc -framework Foundation test_obj.m -o test_obj #import @protocol myVehicleProtocol - (void) startEngine; //mandatory @required - (void) addWheels:(int)value; //mandatory @optional - (void) makeLongTruck; //optional @end @interface MyVehicle : NSObject @property int numberOfWheels; - (void)startEngine; - (void)addWheels:(int)value; - (void)makeLongTruck; @end @implementation MyVehicle : NSObject - (void)startEngine { NSLog(@"Engine started"); } - (void)addWheels:(int)value { self.numberOfWheels += value; } - (void)makeLongTruck { _numberOfWheels = +10000; NSLog(@"Number of wheels: %i", self.numberOfWheels); } @end int main() { MyVehicle* mySuperCar = [MyVehicle new]; [mySuperCar startEngine]; mySuperCar.numberOfWheels = 4; NSLog(@"Number of wheels: %i", mySuperCar.numberOfWheels); [mySuperCar setNumberOfWheels:3]; NSLog(@"Number of wheels: %i", mySuperCar.numberOfWheels); [mySuperCar makeLongTruck]; } ``` ### Classi di base #### Stringa {% code overflow="wrap" %} ```objectivec // NSString NSString *bookTitle = @"The Catcher in the Rye"; NSString *bookAuthor = [[NSString alloc] initWithCString:"J.D. Salinger" encoding:NSUTF8StringEncoding]; NSString *bookPublicationYear = [NSString stringWithCString:"1951" encoding:NSUTF8StringEncoding]; ``` Le classi di base sono **immutevoli**, quindi per aggiungere una stringa a una già esistente è necessario creare una **nuova NSString**. ```objectivec NSString *bookDescription = [NSString stringWithFormat:@"%@ by %@ was published in %@", bookTitle, bookAuthor, bookPublicationYear]; ``` {% endcode %} Oppure potresti utilizzare anche una classe di stringhe **mutabile**: {% code overflow="wrap" %} ```objectivec NSMutableString *mutableString = [NSMutableString stringWithString:@"The book "]; [mutableString appendString:bookTitle]; [mutableString appendString:@" was written by "]; [mutableString appendString:bookAuthor]; [mutableString appendString:@" and published in "]; [mutableString appendString:bookPublicationYear]; ``` Il seguente contenuto è tratto da un libro di hacking sulle tecniche di hacking. Il seguente contenuto è tratto dal file /hive/hacktricks/macos-hardening/macos-security-and-privilege-escalation/macos-basic-objective-c.md. Traduci il testo inglese pertinente in italiano e restituisci la traduzione mantenendo esattamente la stessa sintassi markdown e html. Non tradurre cose come codice, nomi di tecniche di hacking, parole di hacking, nomi di piattaforme cloud/SaaS (come Workspace, aws, gcp...), la parola 'leak', pentesting e tag markdown. Inoltre, non aggiungere nulla di extra oltre alla traduzione e alla sintassi markdown. ```objectivec // character literals. NSNumber *theLetterZ = @'Z'; // equivalent to [NSNumber numberWithChar:'Z'] // integral literals. NSNumber *fortyTwo = @42; // equivalent to [NSNumber numberWithInt:42] NSNumber *fortyTwoUnsigned = @42U; // equivalent to [NSNumber numberWithUnsignedInt:42U] NSNumber *fortyTwoLong = @42L; // equivalent to [NSNumber numberWithLong:42L] NSNumber *fortyTwoLongLong = @42LL; // equivalent to [NSNumber numberWithLongLong:42LL] // floating point literals. NSNumber *piFloat = @3.141592654F; // equivalent to [NSNumber numberWithFloat:3.141592654F] NSNumber *piDouble = @3.1415926535; // equivalent to [NSNumber numberWithDouble:3.1415926535] // BOOL literals. NSNumber *yesNumber = @YES; // equivalent to [NSNumber numberWithBool:YES] NSNumber *noNumber = @NO; // equivalent to [NSNumber numberWithBool:NO] ``` #### Array, Set e Dizionario {% code overflow="wrap" %} ```objectivec // Inmutable arrays NSArray *colorsArray1 = [NSArray arrayWithObjects:@"red", @"green", @"blue", nil]; NSArray *colorsArray2 = @[@"yellow", @"cyan", @"magenta"]; NSArray *colorsArray3 = @[firstColor, secondColor, thirdColor]; // Mutable arrays NSMutableArray *mutColorsArray = [NSMutableArray array]; [mutColorsArray addObject:@"red"]; [mutColorsArray addObject:@"green"]; [mutColorsArray addObject:@"blue"]; [mutColorsArray addObject:@"yellow"]; [mutColorsArray replaceObjectAtIndex:0 withObject:@"purple"]; // Inmutable Sets NSSet *fruitsSet1 = [NSSet setWithObjects:@"apple", @"banana", @"orange", nil]; NSSet *fruitsSet2 = [NSSet setWithArray:@[@"apple", @"banana", @"orange"]]; // Mutable sets NSMutableSet *mutFruitsSet = [NSMutableSet setWithObjects:@"apple", @"banana", @"orange", nil]; [mutFruitsSet addObject:@"grape"]; [mutFruitsSet removeObject:@"apple"]; // Dictionary NSDictionary *fruitColorsDictionary = @{ @"apple" : @"red", @"banana" : @"yellow", @"orange" : @"orange", @"grape" : @"purple" }; // In dictionaryWithObjectsAndKeys you specify the value and then the key: NSDictionary *fruitColorsDictionary2 = [NSDictionary dictionaryWithObjectsAndKeys: @"red", @"apple", @"yellow", @"banana", @"orange", @"orange", @"purple", @"grape", nil]; // Mutable dictionary NSMutableDictionary *mutFruitColorsDictionary = [NSMutableDictionary dictionaryWithDictionary:fruitColorsDictionary]; [mutFruitColorsDictionary setObject:@"green" forKey:@"apple"]; [mutFruitColorsDictionary removeObjectForKey:@"grape"]; ``` ### Blocchi I blocchi sono **funzioni che si comportano come oggetti**, quindi possono essere passati a funzioni o **memorizzati** in **array** o **dizionari**. Inoltre, possono **rappresentare un valore se vengono forniti dei valori**, quindi sono simili alle lambda. ```objectivec returnType (^blockName)(argumentType1, argumentType2, ...) = ^(argumentType1 param1, argumentType2 param2, ...){ //Perform operations here }; // For example int (^suma)(int, int) = ^(int a, int b){ return a+b; }; NSLog(@"3+4 = %d", suma(3,4)); ``` {% endcode %} È anche possibile **definire un tipo di blocco da utilizzare come parametro** nelle funzioni: ```objectivec // Define the block type typedef void (^callbackLogger)(void); // Create a bloack with the block type callbackLogger myLogger = ^{ NSLog(@"%@", @"This is my block"); }; // Use it inside a function as a param void genericLogger(callbackLogger blockParam) { NSLog(@"%@", @"This is my function"); blockParam(); } genericLogger(myLogger); // Call it inline genericLogger(^{ NSLog(@"%@", @"This is my second block"); }); ``` ### File {% code overflow="wrap" %} ```objectivec // Manager to manage files NSFileManager *fileManager = [NSFileManager defaultManager]; // Check if file exists: if ([fileManager fileExistsAtPath:@"/path/to/file.txt" ] == YES) { NSLog (@"File exists"); } // copy files if ([fileManager copyItemAtPath: @"/path/to/file1.txt" toPath: @"/path/to/file2.txt" error:nil] == YES) { NSLog (@"Copy successful"); } // Check if the content of 2 files match if ([fileManager contentsEqualAtPath:@"/path/to/file1.txt" andPath:@"/path/to/file2.txt"] == YES) { NSLog (@"File contents match"); } // Delete file if ([fileManager removeItemAtPath:@"/path/to/file1.txt" error:nil]) { NSLog(@"Removed successfully"); } ``` {% endcode %} È anche possibile gestire i file **utilizzando gli oggetti `NSURL` invece degli oggetti `NSString`**. I nomi dei metodi sono simili, ma **con `URL` invece di `Path`**. ```objectivec NSURL *fileSrc = [NSURL fileURLWithPath:@"/path/to/file1.txt"]; NSURL *fileDst = [NSURL fileURLWithPath:@"/path/to/file2.txt"]; [fileManager moveItemAtURL:fileSrc toURL:fileDst error: nil]; ``` La maggior parte delle classi di base ha un metodo `writeToFile: atomically: encoding: error:nil` definito che consente di scriverle direttamente su un file: {% code overflow="wrap" %} ```objectivec NSString* tmp = @"something temporary"; [tmp writeToFile:@"/tmp/tmp1.txt" atomically:YES encoding:NSASCIIStringEncoding error:nil]; ``` {% endcode %}
Impara l'hacking di AWS da zero a esperto con htARTE (HackTricks AWS Red Team Expert)! Altri modi per supportare HackTricks: * Se vuoi vedere la tua **azienda pubblicizzata su HackTricks** o **scaricare HackTricks in PDF** Controlla i [**PIANI DI ABBONAMENTO**](https://github.com/sponsors/carlospolop)! * Ottieni il [**merchandising ufficiale di PEASS & HackTricks**](https://peass.creator-spring.com) * Scopri [**The PEASS Family**](https://opensea.io/collection/the-peass-family), la nostra collezione di esclusive [**NFT**](https://opensea.io/collection/the-peass-family) * **Unisciti al** 💬 [**gruppo Discord**](https://discord.gg/hRep4RUj7f) o al [**gruppo Telegram**](https://t.me/peass) o **seguici** su **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)**.** * **Condividi i tuoi trucchi di hacking inviando PR ai repository github di** [**HackTricks**](https://github.com/carlospolop/hacktricks) e [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud).