Skip to content

Instantly share code, notes, and snippets.

@nullpixel
Last active October 17, 2021 16:12
Show Gist options
  • Save nullpixel/871d0c51a7ad66111f6f8f1c55831c38 to your computer and use it in GitHub Desktop.
Save nullpixel/871d0c51a7ad66111f6f8f1c55831c38 to your computer and use it in GitHub Desktop.
MSHookMemory wrapper for all modern jailbreaks.
#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;
}
@nullpixel
Copy link
Author

nullpixel commented Jan 19, 2020

write_memory.c

This is a MSHookMemory 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment