Indeed, you can populate the array with x86 machine code and try to execute it. It is called shellcode and controls that the application or library executes such code when it was not intended, called the "exploit."
Unfortunately, this is not so simple, since modern hardware and OS usually prevent the execution of code from areas that can be written, for example, non-const char arrays. This is called W ^ X (write or execute permissions, but not both). But you can request a POSIX-compatible OS to disable this protection using the mprotect() function. Here is an example that works because it allows you to allow reading, writing, and executing permissions in an array of corresponding bytes of machine code:
#include <stdio.h> #include <stdint.h> #include <sys/mman.h> typedef int(*FUNKY_POINTER)(void); char shellcode[] = { 0xb8, 0x2a, 0x00, 0x00, 0x00, //mov $0x2a,%eax 0xc3 //retq }; int main(void){ uintptr_t pageSize = 4096; uintptr_t shellcodeAddr = (uintptr_t)shellcode; uintptr_t pageAlignedAddr = shellcodeAddr & ~(pageSize-1); FUNKY_POINTER shellcodeFn = (FUNKY_POINTER)shellcode; /* Magic */ mprotect((void*)pageAlignedAddr, (shellcodeAddr - pageAlignedAddr) + sizeof(shellcode), PROT_EXEC|PROT_WRITE|PROT_READ); printf("The answer to the ultimate question of life, " "the universe and everything is %d\n", shellcodeFn()); return 0; }
source share