Skip to content

Evading ASLR

macOS's Address Space Layout Randomization (ASLR) randomizes the memory addresses of key components like dylibs, making exploitation of memory corruption vulnerabilities more challenging. However, dylib injection techniques can be leveraged to bypass ASLR by exploiting predictable memory patterns or forcing known load addresses. This section explores strategies to evade ASLR using dylib manipulation.


Bypassing ASLR via Dylib Injection

1. Fixed Load Address Dylibs

Some dylibs (e.g., system libraries) may be loaded at predictable addresses if their paths are hardcoded or if the attacker controls the RPATH/RUNPATH environment variables. For example:

install_name_tool -rpath @loader_path/../lib libexample.dylib
This forces the dylib to load from a known relative path, potentially reducing ASLR entropy. However, macOS's ASLR typically randomizes dylib base addresses, so this method is less reliable than on Windows.

2. Injecting a Custom Dylib

An attacker can inject a custom dylib into a target process using dlopen or memory-mapped files. If the dylib is loaded at a predictable address (e.g., via dlopen with a fixed path), its base address becomes a known pivot point. For example:

// Malicious dylib (malicious.dylib)
#include <dlfcn.h>
void malicious_func() {
    void* base = dlopen(0, RTLD_NOW);
    // Calculate offsets to other memory regions
}
The attacker can then use the dylib's base address to compute the location of other memory regions (e.g., stack, heap) by analyzing the mach-o header.

3. Exploiting ASLR Weaknesses

If the target process is not fully ASLR-protected (e.g., due to misconfiguration), the attacker can use a dylib injection to determine the base address of the process's memory. For example:

# Inject dylib into a process using ptrace
sudo taskset -c 0 taskset -c 0 gdb -ex 'attach <pid>' -ex 'call dlopen("/path/to/malicious.dylib", 0x00000000)' -ex 'detach' -ex 'quit'
Once injected, the dylib's base address can be used to calculate offsets for other memory regions.


Practical Considerations

  • ASLR Mitigations: macOS randomizes dylib base addresses, but certain libraries (e.g., /usr/lib/libSystem.dylib) may have reduced entropy. Attackers should verify the target environment's ASLR configuration.
  • Dynamic Analysis: Use tools like lldb or gdb to inspect the memory layout of a process after dylib injection. For example:
    lldb -p <pid>
    (lldb) memory read -f x <address>
    
  • Code Signing: macOS enforces code signing for dylibs. Attackers may need to bypass this using techniques like kernel exploits or privilege escalation.

Key takeaways

  • Dylib injection can create known memory addresses by leveraging predictable load paths or custom dylibs.
  • ASLR evasion requires identifying entropy-reduced components or exploiting process-specific memory patterns.
  • Tools like dlopen, lldb, and install_name_tool are critical for crafting and analyzing dylib-based exploits on macOS.