Home > other >  mach_vm_protect unable to make memory executable
mach_vm_protect unable to make memory executable

Time:02-23

I'm trying to allocate memory dynamically and have it be executable through mach_vm_protect; however any time I try to execute the code the application crashes. But mach_vm_protect succeeds which is what I don't understand.

#include <stdio.h>
#include <unistd.h>
#include <mach/mach_init.h>
#include <mach/vm_map.h>
#include <mach/mach_vm.h>

int test(int x, int y){
    return x y;
}
typedef int (*test_mach_copy)(int,int);
#define CODE_SIZE 0x17
int main()
{

    
    mach_vm_address_t remoteCode64 = (vm_address_t) NULL;
    mach_vm_address_t testvmaddr = (vm_address_t)&test;
    task_t remotetask;
    task_for_pid(mach_task_self(), getpid(), &remotetask);
    if (mach_vm_protect(remotetask, testvmaddr, CODE_SIZE, 1, VM_PROT_READ|VM_PROT_EXECUTE)!=KERN_SUCCESS) {
      return 1;
    }
      
    if(mach_vm_allocate(remotetask,&remoteCode64,CODE_SIZE,VM_FLAGS_ANYWHERE)!=KERN_SUCCESS){
        return 1;
    }
    if (mach_vm_protect(remotetask, remoteCode64, CODE_SIZE, 1, VM_PROT_READ|VM_PROT_EXECUTE|VM_PROT_WRITE|VM_PROT_COPY)!=KERN_SUCCESS) {
      return 1;
    }
    mach_vm_copy(remotetask, testvmaddr, CODE_SIZE, remoteCode64);
    test_mach_copy tmc = (test_mach_copy)remoteCode64;
    int x = tmc(10,20);
    printf("%d\n",x);

    return 0;
}

x017 Is size the correct sizeof(test())

CodePudding user response:

The issue is probably your use of VM_PROT_READ|VM_PROT_EXECUTE|VM_PROT_WRITE|VM_PROT_COPY. Modern operating systems, and architectures, try to enforce W^X permissions. That is, either a memory range is executable or writeable, but never both.

There might be a bug in the kernel since your call to mach_vm_protect is returning KERN_SUCCESS.

I was able to get your code working by simply making 2 calls to mach_vm_protect in succession:

int main()
{
    mach_vm_address_t remoteCode64 = (vm_address_t) NULL;
    mach_vm_address_t testvmaddr = (vm_address_t)&test;
    task_t remotetask;
    task_for_pid(mach_task_self(), getpid(), &remotetask);
    if (mach_vm_protect(remotetask, testvmaddr, CODE_SIZE, 1, VM_PROT_READ|VM_PROT_EXECUTE)!=KERN_SUCCESS) {
      return 1;
    }

    if(mach_vm_allocate(remotetask,&remoteCode64,CODE_SIZE,VM_FLAGS_ANYWHERE)!=KERN_SUCCESS){
      return 1;
    }

    if (mach_vm_protect(remotetask, remoteCode64, CODE_SIZE, 0, VM_PROT_READ|VM_PROT_WRITE|VM_PROT_COPY)!=KERN_SUCCESS) {
      return 1;
    }
    if (mach_vm_copy(remotetask, testvmaddr, CODE_SIZE, remoteCode64) != KERN_SUCCESS) {
      return 1;
    }
    if (mach_vm_protect(remotetask, remoteCode64, CODE_SIZE, 0, VM_PROT_READ|VM_PROT_EXECUTE)!=KERN_SUCCESS) {
      return 1;
    }
    test_mach_copy tmc = (test_mach_copy)remoteCode64;
    int x = tmc(10,20);
    printf("%d\n",x);

    return 0;
}
  • Related