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

402 lines
16 KiB
Markdown

# Configuración de Frida en iOS
<details>
<summary><strong>Aprende a hackear AWS desde cero hasta convertirte en un experto con</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
Otras formas de apoyar a HackTricks:
* Si deseas ver tu **empresa anunciada en HackTricks** o **descargar HackTricks en PDF** Consulta los [**PLANES DE SUSCRIPCIÓN**](https://github.com/sponsors/carlospolop)!
* Obtén [**artículos oficiales de PEASS & HackTricks**](https://peass.creator-spring.com)
* Descubre [**The PEASS Family**](https://opensea.io/collection/the-peass-family), nuestra colección exclusiva de [**NFTs**](https://opensea.io/collection/the-peass-family)
* **Únete al** 💬 [**grupo de Discord**](https://discord.gg/hRep4RUj7f) o al [**grupo de telegram**](https://t.me/peass) o **síguenos** en **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks\_live)**.**
* **Comparte tus trucos de hacking enviando PRs a los repositorios de** [**HackTricks**](https://github.com/carlospolop/hacktricks) y [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) en GitHub.
</details>
### [WhiteIntel](https://whiteintel.io)
<figure><img src="/.gitbook/assets/image (1224).png" alt=""><figcaption></figcaption></figure>
[**WhiteIntel**](https://whiteintel.io) es un motor de búsqueda alimentado por la **dark web** que ofrece funcionalidades **gratuitas** para verificar si una empresa o sus clientes han sido **comprometidos** por **malwares de robo**.
El objetivo principal de WhiteIntel es combatir los secuestros de cuentas y los ataques de ransomware resultantes de malwares que roban información.
Puedes visitar su sitio web y probar su motor de forma **gratuita** en:
{% embed url="https://whiteintel.io" %}
---
## Instalación de Frida
**Pasos para instalar Frida en un dispositivo con Jailbreak:**
1. Abrir la aplicación Cydia/Sileo.
2. Navegar a Manage -> Sources -> Edit -> Add.
3. Ingresar "https://build.frida.re" como URL.
4. Ir a la nueva fuente de Frida añadida.
5. Instalar el paquete de Frida.
Si estás utilizando **Corellium**, necesitarás descargar la versión de Frida desde [https://github.com/frida/frida/releases](https://github.com/frida/frida/releases) (`frida-gadget-[tuversión]-ios-universal.dylib.gz`) y descomprimir y copiar en la ubicación dylib que Frida solicita, por ejemplo: `/Users/[tusuario]/.cache/frida/gadget-ios.dylib`
Una vez instalado, puedes usar en tu PC el comando **`frida-ls-devices`** y verificar que el dispositivo aparezca (tu PC debe poder acceder a él).\
Ejecuta también **`frida-ps -Uia`** para verificar los procesos en ejecución del teléfono.
## Frida sin dispositivo con Jailbreak y sin parchear la aplicación
Consulta esta publicación en el blog sobre cómo utilizar Frida en dispositivos sin Jailbreak sin parchear la aplicación: [https://mrbypass.medium.com/unlocking-potential-exploring-frida-objection-on-non-jailbroken-devices-without-application-ed0367a84f07](https://mrbypass.medium.com/unlocking-potential-exploring-frida-objection-on-non-jailbroken-devices-without-application-ed0367a84f07)
## Instalación del Cliente de Frida
Instalar **herramientas de frida**:
```bash
pip install frida-tools
pip install frida
```
Con el servidor de Frida instalado y el dispositivo en funcionamiento y conectado, **verifica** si el cliente está **funcionando**:
```bash
frida-ls-devices # List devices
frida-ps -Uia # Get running processes
```
## Rastreo con Frida
```bash
# 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 '*[* *]'
```
### Obtener todas las clases y métodos
* Autocompletar: Simplemente ejecuta `frida -U <programa>`
<figure><img src="../../.gitbook/assets/image (1156).png" alt=""><figcaption></figcaption></figure>
* Obtener **todas** las **clases** disponibles (filtrar por cadena)
{% code title="/tmp/script.js" %}
```javascript
// 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 %}
* Obtener **todos** los **métodos** de una **clase** (filtrar por cadena)
{% code title="/tmp/script.js" %}
```javascript
// 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 %}
* **Llamar a una función**
```javascript
// 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");
```
## Fuzzing con Frida
### Frida Stalker
[Desde la documentación](https://frida.re/docs/stalker/): Stalker es el motor de **trazado** de código de Frida. Permite **seguir** hilos, **capturando** cada función, **cada bloque**, e incluso cada instrucción que se ejecuta.
Tienes un ejemplo implementando Frida Stalker en [https://github.com/poxyran/misc/blob/master/frida-stalker-example.py](https://github.com/poxyran/misc/blob/master/frida-stalker-example.py)
Este es otro ejemplo para adjuntar Frida Stalker cada vez que se llama a una función:
```javascript
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" %}
Esto es interesante para propósitos de depuración, pero para el fuzzing, estar constantemente **`.follow()`** y **`.unfollow()`** es muy ineficiente.
{% endhint %}
## [Fpicker](https://github.com/ttdennis/fpicker)
[**fpicker**](https://github.com/ttdennis/fpicker) es un **conjunto de herramientas de fuzzing basado en Frida** que ofrece una variedad de modos de fuzzing para fuzzing en el proceso, como un modo AFL++ o un modo de trazado pasivo. Debería funcionar en todas las plataformas compatibles con Frida.
* [**Instalar fpicker**](https://github.com/ttdennis/fpicker#requirements-and-installation) **& radamsa**
```bash
# 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
```
* **Preparar el sistema de archivos:**
```bash
# 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" %}
```javascript
// 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 %}
* **Compilar** el fuzzer:
```bash
# From inside fpicker clone
## Compile from "myfuzzer.js" to "harness.js"
frida-compile examples/wg-log/myfuzzer.js -o harness.js
```
* Llama al fuzzer **`fpicker`** usando **`radamsa`**:
{% code overflow="wrap" %}
```bash
# 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" %}
En este caso **no estamos reiniciando la aplicación ni restaurando el estado** después de cada carga útil. Por lo tanto, si Frida encuentra una **falla**, las **siguientes entradas** después de esa carga útil también podrían **hacer que la aplicación falle** (porque la aplicación está en un estado inestable), incluso si la **entrada no debería hacer que la aplicación falle**.
Además, Frida se enganchará en las señales de excepción de iOS, por lo que cuando **Frida encuentra una falla**, probablemente no se generen **informes de fallas de iOS**.
Para prevenir esto, por ejemplo, podríamos reiniciar la aplicación después de cada falla de Frida.
{% endhint %}
### Registros y Fallas
Puedes verificar la **consola de macOS** o el **cli `log`** para revisar los registros de macOS.\
También puedes verificar los registros de iOS usando **`idevicesyslog`**.\
Algunos registros omitirán información agregando **`<private>`**. Para mostrar toda la información, necesitas instalar algún perfil desde [https://developer.apple.com/bug-reporting/profiles-and-logs/](https://developer.apple.com/bug-reporting/profiles-and-logs/) para habilitar esa información privada.
Si no sabes qué hacer:
```sh
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
```
Puedes verificar los fallos en:
* **iOS**
* Ajustes → Privacidad → Análisis y mejora → Datos de análisis
* `/private/var/mobile/Library/Logs/CrashReporter/`
* **macOS**:
* `/Library/Logs/DiagnosticReports/`
* `~/Library/Logs/DiagnosticReports`
{% hint style="warning" %}
iOS solo almacena 25 fallos de la misma aplicación, así que necesitas limpiar eso o iOS dejará de crear fallos.
{% endhint %}
## Tutoriales de Frida para Android
{% content-ref url="../android-app-pentesting/frida-tutorial/" %}
[frida-tutorial](../android-app-pentesting/frida-tutorial/)
{% endcontent-ref %}
## Referencias
* [https://www.briskinfosec.com/blogs/blogsdetail/Getting-Started-with-Frida](https://www.briskinfosec.com/blogs/blogsdetail/Getting-Started-with-Frida)
### [WhiteIntel](https://whiteintel.io)
<figure><img src="/.gitbook/assets/image (1224).png" alt=""><figcaption></figcaption></figure>
[**WhiteIntel**](https://whiteintel.io) es un motor de búsqueda alimentado por la **dark web** que ofrece funcionalidades **gratuitas** para verificar si una empresa o sus clientes han sido **comprometidos** por **malwares de robo**.
El objetivo principal de WhiteIntel es combatir los secuestros de cuentas y los ataques de ransomware resultantes de malwares que roban información.
Puedes visitar su sitio web y probar su motor de forma **gratuita** en:
{% embed url="https://whiteintel.io" %}
<details>
<summary><strong>Aprende hacking en AWS desde cero hasta experto con</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
Otras formas de apoyar a HackTricks:
* Si deseas ver tu **empresa anunciada en HackTricks** o **descargar HackTricks en PDF** ¡Consulta los [**PLANES DE SUSCRIPCIÓN**](https://github.com/sponsors/carlospolop)!
* Obtén la [**merchandising oficial de PEASS & HackTricks**](https://peass.creator-spring.com)
* Descubre [**The PEASS Family**](https://opensea.io/collection/the-peass-family), nuestra colección exclusiva de [**NFTs**](https://opensea.io/collection/the-peass-family)
* **Únete al** 💬 [**grupo de Discord**](https://discord.gg/hRep4RUj7f) o al [**grupo de telegram**](https://t.me/peass) o **síguenos** en **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks\_live)**.**
* **Comparte tus trucos de hacking enviando PRs a los repositorios de** [**HackTricks**](https://github.com/carlospolop/hacktricks) y [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud).
</details>