0

How can I redirect execution to code on heap? OS: 64bit linux

What I tried is setting rip to my array, I can't get it to compile though. My code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int len = 0;
    char *t;
    int chr;
    printf("Input code length: ");
    scanf("%d", &len);
    t = (char*)malloc(len+1);
    for (int i = 0; i < len; ++i) {
        scanf("%x", &chr);
        t[i] = chr;
    }
    t[len] = 0;
    asm("movl %%rip, [%0]" : "=g"(t));
}
enedil
  • 1,605
  • 4
  • 18
  • 34
  • 2
    The heap pages will be marked with a no-execute bit (NX) on x86-64 linux, completely preventing such behavior even if you got the correct assembly instruction to jump to the heap. – FBergo May 05 '18 at 00:57
  • @FBergo but there's a compiler flag for it, huh? – enedil May 05 '18 at 01:02
  • 3
    Also `movl %%rip` is invalid. You don't `mov` into `rip`, you use a `jmp`. And at&t syntax uses src, dst operand order so that makes no sense because it would move **from** rip not to. And at&t doesn't use `[]`. – Jester May 05 '18 at 01:04
  • There are compiler flags for making the *stack* executable (`-z execstsck` will get passed to the linker), but I’m not sure about the heap. Instead, it might be a better idea to use [`mmap`](http://man7.org/linux/man-pages/man2/mmap.2.html) to get just the one variable executable and not the whole heap. – Daniel H May 05 '18 at 03:02

0 Answers0