Search code examples
cassemblyx86x86-64shellcode

How to get c code to execute hex machine code?


I want a simple C method to be able to run hex bytecode on a Linux 64 bit machine. Here's the C program that I have:

char code[] = "\x48\x31\xc0";
#include <stdio.h>
int main(int argc, char **argv)
{
        int (*func) ();
        func = (int (*)()) code;
        (int)(*func)();
        printf("%s\n","DONE");
}

The code that I am trying to run ("\x48\x31\xc0") I obtained by writting this simple assembly program (it's not supposed to really do anything)

.text
.globl _start
_start:
        xorq %rax, %rax

and then compiling and objdump-ing it to obtain the bytecode.

However, when I run my C program I get a segmentation fault. Any ideas?


Solution

  • Machine code has to be in an executable page. Your char code[] is in the read+write data section, without exec permission, so the code cannot be executed from there.

    Here is a simple example of allocating an executable page with mmap:

    #include <stdio.h>
    #include <string.h>
    #include <sys/mman.h>
    
    int main ()
    {
      char code[] = {
        0x8D, 0x04, 0x37,           //  lea eax,[rdi+rsi]
        0xC3                        //  ret
      };
    
      int (*sum) (int, int) = NULL;
    
      // allocate executable buffer                                             
      sum = mmap (0, sizeof(code), PROT_READ|PROT_WRITE|PROT_EXEC,
                  MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
    
      // copy code to buffer
      memcpy (sum, code, sizeof(code));
      // doesn't actually flush cache on x86, but ensure memcpy isn't
      // optimized away as a dead store.
      __builtin___clear_cache (sum, sum + sizeof(sum));  // GNU C
    
      // run code
      int a = 2;
      int b = 3;
      int c = sum (a, b);
    
      printf ("%d + %d = %d\n", a, b, c);
    }
    

    See another answer on this question for details about __builtin___clear_cache.