hacktricks/mobile-pentesting/ios-pentesting/frida-configuration-in-ios.md

17 KiB

Configuration de Frida sur iOS

☁️ HackTricks Cloud ☁️ -🐦 Twitter 🐦 - 🎙️ Twitch 🎙️ - 🎥 Youtube 🎥

Installation de Frida

Accédez à l'application Cydia/Sileo sur votre appareil Jailbreaké et ajoutez le dépôt de Frida en allant dans Gérer -> Sources -> Modifier -> Ajouter et entrez https://build.frida.re . Cela ajoutera une nouvelle source dans la liste des sources. Accédez à la source Frida, maintenant vous devriez installer le package Frida.

Si vous utilisez Corellium, vous devrez télécharger la version de Frida depuis https://github.com/frida/frida/releases (frida-gadget-[yourversion]-ios-universal.dylib.gz) et décompresser et copier à l'emplacement dylib demandé par Frida, par exemple : /Users/[youruser]/.cache/frida/gadget-ios.dylib

Une fois installé, vous pouvez utiliser la commande frida-ls-devices sur votre PC et vérifier que l'appareil apparaît (votre PC doit pouvoir y accéder).
Exécutez également frida-ps -Uia pour vérifier les processus en cours d'exécution sur le téléphone.

Frida sans appareil Jailbreaké et sans patcher l'application

Consultez cet article de blog sur la façon d'utiliser Frida sur des appareils non jailbreakés sans patcher l'application : https://mrbypass.medium.com/unlocking-potential-exploring-frida-objection-on-non-jailbroken-devices-without-application-ed0367a84f07

Installation du client Frida

Installez les outils Frida :

pip install frida-tools
pip install frida

Avec le serveur Frida installé et l'appareil en cours d'exécution et connecté, vérifiez si le client fonctionne :

frida-ls-devices  # List devices
frida-ps -Uia     # Get running processes

Frida Trace

Frida Trace is a powerful dynamic instrumentation tool that allows you to trace function calls and monitor the behavior of an iOS application in real-time. It can be used for various purposes, such as debugging, reverse engineering, and vulnerability analysis.

To configure Frida Trace in iOS, follow these steps:

  1. Jailbreak your iOS device: Frida requires a jailbroken device to work properly. If your device is not jailbroken, you can follow online tutorials to jailbreak it.

  2. Install Frida on your iOS device: Once your device is jailbroken, you need to install Frida. You can do this by adding the Frida repository to Cydia and then installing the Frida package.

  3. Install Frida on your computer: After installing Frida on your iOS device, you also need to install it on your computer. Frida supports multiple platforms, including Windows, macOS, and Linux. You can download the appropriate package from the Frida website and follow the installation instructions.

  4. Connect your iOS device to your computer: Make sure your iOS device is connected to your computer via USB.

  5. Start the Frida server on your iOS device: Open the Frida app on your iOS device and start the Frida server.

  6. Write a Frida script: Now, you need to write a Frida script to trace the function calls in the target iOS application. The script should specify the target application and the functions you want to trace. You can write the script in JavaScript using the Frida API.

  7. Run the Frida script: Once you have written the Frida script, you can run it using the Frida command-line tool on your computer. The script will be injected into the target application, and you will be able to see the function calls and their arguments in real-time.

Frida Trace is a versatile tool that can greatly enhance your iOS pentesting capabilities. By using it, you can gain valuable insights into the inner workings of an iOS application and identify potential vulnerabilities or security weaknesses.

# Functions
## Trace all functions with the word "log" in their name
frida-trace -U <program> -i "*log*"
frida-trace -U <program> -i "*log*" | swift demangle # Demangle names

# Objective-C
## Trace all methods of all classes
frida-trace -U <program> -m "*[* *]"

## Trace all methods with the word "authentication" from classes that start with "NE"
frida-trace -U <program> -m "*[NE* *authentication*]"

# Plug-In
## To hook a plugin that is momentarely executed prepare Frida indicating the ID of the Plugin binary
frida-trace -U -W <if-plugin-bin> -m '*[* *]'

Obtenir toutes les classes et méthodes

  • Auto-complétion : Exécutez simplement frida -U <programme>
  • Obtenir toutes les classes disponibles (filtrer par chaîne)

{% code title="/tmp/script.js" %}

// frida -U <program> -l /tmp/script.js

var filterClass = "filterstring";

if (ObjC.available) {
for (var className in ObjC.classes) {
if (ObjC.classes.hasOwnProperty(className)) {
if (!filterClass || className.includes(filterClass)) {
console.log(className);
}
}
}
} else {
console.log("Objective-C runtime is not available.");
}

{% endcode %}

  • Obtenir toutes les méthodes d'une classe (filtrer par chaîne de caractères)

{% code title="/tmp/script.js" %}

// frida -U <program> -l /tmp/script.js

var specificClass = "YourClassName";
var filterMethod = "filtermethod";

if (ObjC.available) {
if (ObjC.classes.hasOwnProperty(specificClass)) {
var methods = ObjC.classes[specificClass].$ownMethods;
for (var i = 0; i < methods.length; i++) {
if (!filterMethod || methods[i].includes(filterClass)) {
console.log(specificClass + ': ' + methods[i]);
}
}
} else {
console.log("Class not found.");
}
} else {
console.log("Objective-C runtime is not available.");
}

{% endcode %}

  • Appeler une fonction
// Find the address of the function to call
const func_addr = Module.findExportByName("<Prog Name>", "<Func Name>");
// Declare the function to call
const func = new NativeFunction(
func_addr,
"void", ["pointer", "pointer", "pointer"], {
});

var arg0 = null;

// In this case to call this function we need to intercept a call to it to copy arg0
Interceptor.attach(wg_log_addr, {
onEnter: function(args) {
arg0 = new NativePointer(args[0]);
}
});

// Wait untill a call to the func occurs
while (! arg0) {
Thread.sleep(1);
console.log("waiting for ptr");
}


var arg1 = Memory.allocUtf8String('arg1');
var txt = Memory.allocUtf8String('Some text for arg2');
wg_log(arg0, arg1, txt);

console.log("loaded");

Frida Fuzzing

Frida Stalker

Stalker est le moteur de traçage de code de Frida. Il permet de suivre les threads, capturant chaque fonction, chaque bloc, voire chaque instruction exécutée.

Vous trouverez un exemple d'implémentation de Frida Stalker à l'adresse suivante : https://github.com/poxyran/misc/blob/master/frida-stalker-example.py

Voici un autre exemple pour attacher Frida Stalker à chaque appel de fonction :

console.log("loading");
const wg_log_addr = Module.findExportByName("<Program>", "<function_name>");
const wg_log = new NativeFunction(
wg_log_addr,
"void", ["pointer", "pointer", "pointer"], {
});

Interceptor.attach(wg_log_addr, {
onEnter: function(args) {
console.log(`logging the following message: ${args[2].readCString()}`);

Stalker.follow({
events: {
// only collect coverage for newly encountered blocks
compile: true,
},
onReceive: function (events) {
const bbs = Stalker.parse(events, {
stringify: false,
annotate: false
});
console.log("Stalker trace of write_msg_to_log: \n" + bbs.flat().map(DebugSymbol.fromAddress).join('\n'));
}
});
},
onLeave: function(retval) {
Stalker.unfollow();
Stalker.flush();  // this is important to get all events
}
});

{% hint style="danger" %} C'est intéressant à des fins de débogage, mais pour le fuzzing, suivre constamment .follow() et .unfollow() est très inefficace. {% endhint %}

Fpicker

fpicker est une suite de fuzzing basée sur Frida qui offre une variété de modes de fuzzing pour le fuzzing en cours d'exécution, tels qu'un mode AFL++ ou un mode de traçage passif. Il devrait fonctionner sur toutes les plates-formes prises en charge par Frida.

# Get fpicker
git clone https://github.com/ttdennis/fpicker
cd fpicker

# Get Frida core devkit and prepare fpicker
wget https://github.com/frida/frida/releases/download/16.1.4/frida-core-devkit-16.1.4-[yourOS]-[yourarchitecture].tar.xz
# e.g. https://github.com/frida/frida/releases/download/16.1.4/frida-core-devkit-16.1.4-macos-arm64.tar.xz
tar -xf ./*tar.xz
cp libfrida-core.a libfrida-core-[yourOS].a #libfrida-core-macos.a

# Install fpicker
make fpicker-[yourOS] # fpicker-macos
# This generates ./fpicker

# Install radamsa (fuzzer generator)
brew install radamsa
  • Préparer le système de fichiers :
# From inside fpicker clone
mkdir -p examples/wg-log # Where the fuzzing script will be
mkdir -p examples/wg-log/out # For code coverage and crashes
mkdir -p examples/wg-log/in # For starting inputs

# Create at least 1 input for the fuzzer
echo Hello World > examples/wg-log/in/0
  • Script de Fuzzer (examples/wg-log/myfuzzer.js):

{% code title="examples/wg-log/myfuzzer.js" %}

// Import the fuzzer base class
import { Fuzzer } from "../../harness/fuzzer.js";

class WGLogFuzzer extends Fuzzer {

constructor() {
console.log("WGLogFuzzer constructor called")

// Get and declare the function we are going to fuzz
var wg_log_addr = Module.findExportByName("<Program name>", "<func name to fuzz>");
var wg_log_func = new NativeFunction(
wg_log_addr,
"void", ["pointer", "pointer", "pointer"], {
});

// Initialize the object
super("<Program nane>", wg_log_addr, wg_log_func);
this.wg_log_addr = wg_log_addr; // We cannot use "this" before calling "super"

console.log("WGLogFuzzer in the middle");

// Prepare the second argument to pass to the fuzz function
this.tag = Memory.allocUtf8String("arg2");

// Get the first argument we need to pass from a call to the functino we want to fuzz
var wg_log_global_ptr = null;
console.log(this.wg_log_addr);
Interceptor.attach(this.wg_log_addr, {
onEnter: function(args) {
console.log("Entering in the function to get the first argument");
wg_log_global_ptr = new NativePointer(args[0]);
}
});

while (! wg_log_global_ptr) {
Thread.sleep(1)
}
this.wg_log_global_ptr = wg_log_global_ptr;
console.log("WGLogFuzzer prepare ended")
}


// This function is called by the fuzzer with the first argument being a pointer into memory
// where the payload is stored and the second the length of the input.
fuzz(payload, len) {
// Get a pointer to payload being a valid C string (with a null byte at the end)
var payload_cstring = payload.readCString(len);
this.payload = Memory.allocUtf8String(payload_cstring);

// Debug and fuzz
this.debug_log(this.payload, len);
// Pass the 2 first arguments we know the function needs and finally the payload to fuzz
this.target_function(this.wg_log_global_ptr, this.tag, this.payload);
}
}

const f = new WGLogFuzzer();
rpc.exports.fuzzer = f;

{% endcode %}

  • Compiler le fuzzer :
# From inside fpicker clone
## Compile from "myfuzzer.js" to "harness.js"
frida-compile examples/wg-log/myfuzzer.js -o harness.js
  • Appelez le fuzzer fpicker en utilisant radamsa:

{% code overflow="wrap" %}

# Indicate fpicker to fuzz a program with the harness.js script and which folders to use
fpicker -v --fuzzer-mode active -e attach -p <Program to fuzz> -D usb -o examples/wg-log/out/ -i examples/wg-log/in/ -f harness.js --standalone-mutator cmd --mutator-command "radamsa"
# You can find code coverage and crashes in examples/wg-log/out/

{% endcode %}

{% hint style="danger" %} Dans ce cas, nous ne redémarrons pas l'application ou ne restaurons pas l'état après chaque charge utile. Ainsi, si Frida trouve un plantage, les prochaines entrées après cette charge utile pourraient également faire planter l'application (car l'application est dans un état instable), même si l'entrée ne devrait pas faire planter l'application.

De plus, Frida se connectera aux signaux d'exception d'iOS, donc lorsque Frida trouve un plantage, il est probable qu'aucun rapport de plantage iOS ne soit généré.

Pour éviter cela, par exemple, nous pourrions redémarrer l'application après chaque plantage de Frida. {% endhint %}

Journaux et plantages

Vous pouvez vérifier la console macOS ou le cli log pour vérifier les journaux macOS.
Vous pouvez également vérifier les journaux d'iOS en utilisant idevicesyslog.
Certains journaux omettront des informations en ajoutant <private>. Pour afficher toutes les informations, vous devez installer un profil à partir de https://developer.apple.com/bug-reporting/profiles-and-logs/ pour activer ces informations privées.

Si vous ne savez pas quoi faire :

vim /Library/Preferences/Logging/com.apple.system.logging.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Enable-Private-Data</key>
<true/>
</dict>
</plist>

killall -9 logd

Vous pouvez vérifier les plantages dans:

  • iOS
  • Paramètres → Confidentialité → Analyse et améliorations → Données d'analyse
  • /private/var/mobile/Library/Logs/CrashReporter/
  • macOS:
  • /Library/Logs/DiagnosticReports/
  • ~/Library/Logs/DiagnosticReports

{% hint style="warning" %} iOS ne stocke que 25 plantages de la même application, vous devez donc les nettoyer sinon iOS cessera de créer des plantages. {% endhint %}

Tutoriels Frida Android

{% content-ref url="../android-app-pentesting/frida-tutorial/" %} frida-tutorial {% endcontent-ref %}

☁️ HackTricks Cloud ☁️ -🐦 Twitter 🐦 - 🎙️ Twitch 🎙️ - 🎥 Youtube 🎥