Skip to content

Instantly share code, notes, and snippets.

@nullpixel
Created January 19, 2020 21:28
Show Gist options
  • Save nullpixel/4f8e0969ff5cdfe05911f285db6297bc to your computer and use it in GitHub Desktop.
Save nullpixel/4f8e0969ff5cdfe05911f285db6297bc to your computer and use it in GitHub Desktop.

write_memory.c

This is a MSHookFunction shim, which supports writing to RX memory on all modern jailbreaks.

Usage

Requires linking against CydiaSubstrate for MSFindSymbol, but dlsym should work fine, to remove this dependency.

Implementation

On unc0ver and checkra1n, write_memory directly uses MSHookMemory, the functionality provided by substrate to write to RX memory.

On Electra and Chimera, it changes virtual memory permissions to allow writing, then vm_write's your data over the address, finally setting the permissions back to RX.

The fallback method used on Electra and Chimera should work on all jailbreaks, providing CS_DEBUGGED is set.

#include <mach/mach.h> // mach_task_self, vm_protect
#include <substrate.h> // MSFindSymbol
// MARK: - Types
typedef void (*MSHookMemory_ptr_t)(void *target, const void *data, size_t size);
#define ENSURE_KERN_SUCCESS(ret) \
if (ret != KERN_SUCCESS) { \
return false; \
} \
// MARK: - Functions
bool write_memory(void *destination, const void *data, size_t size) {
MSHookMemory_ptr_t __MSHookMemory = (MSHookMemory_ptr_t)MSFindSymbol(NULL, "_MSHookMemory");
if (__MSHookMemory) {
// We can use MSHookMemory!
__MSHookMemory(destination, data, size);
return true;
}
// We can't use MSHookMemory, so try and remap the permissions
mach_port_t our_port = mach_task_self();
// Attempt to map as RWX
ENSURE_KERN_SUCCESS(vm_protect(our_port, (vm_address_t)destination, size, false, VM_PROT_ALL))
// Write to memory
ENSURE_KERN_SUCCESS(vm_write(our_port, (vm_address_t)destination, data, size))
// Map back to RX
ENSURE_KERN_SUCCESS(vm_protect(our_port, (vm_address_t)destination, size, false, VM_PROT_READ | VM_PROT_EXECUTE))
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment