0

Once you generate an exploit in metasploit with the '-t c' tag you get an array with a bytecode like

unsigned char buf[] = 
"\xfc\xe8\x89\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b\x52\x30"
"\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26\x31\xff"
"\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d\x01\xc7\xe2"
"\xf0\x52\x57\x8b\x52\x10\x8b\x42\x3c\x01\xd0\x8b\x40\x78\x85"
...snip...

My question is how do you compile and run this bytecode in C?

1
  • Are you asking how to compile in C? Or are you asking how to compile bytecode in C? Like, do you know about gcc?
    – schroeder
    Oct 16 '16 at 16:06
2

The code is already 'compiled' machine code. Just do something like this in main():

int *ret;
ret = (int *)&ret + 2;
*ret = (int) buf;

Just make sure you disable non-executable stack with -z execstack flag while compiling.

EDIT:
Breaking down the code -

int *ret;

We are declaring an int pointer named ret as a local variable in main(). Being the first and only variable, it lies immediately below the old frame pointer in the stack.

ret = (int *)&ret + 2;

Next, we are adding 2 to the address of the ret pointer and storing it back in ret. If you look at the figure, the return address lies exactly 2 dwords above ret. So we are basically storing the address of the return address in ret.

*ret = (int) buf;

Finally, we are dereferencing ret to replace the existing return address with the address of buf (our shellcode - presumably declared globally).

main() will therefore be returning to buf instead of where it was supposed to. The bytes in buf will be interpreted as code and will be executed happily. This is what typically happens in a vanilla buffer overflow exploit. The control flow is hijacked by causing a buffer to overflow and making it overwrite the return address with something that the hacker has control over (usually injected shellcode).

Do note that modern OSes usually store additional stack canaries to detect overflows. Therefore the offset '2' might not hold true. For simplicity, use the -fno-stack-protector flag while compiling in gcc to disable stack canaries.enter image description here

2
  • is it possible to explain line by line what the code exactly does and why you put +2 on the second line? maybe give a complete example of the code anyway your code seems nice
    – AXANO
    Oct 17 '16 at 19:43
  • Sure, check the edited answer.
    – rhodeo
    Oct 18 '16 at 8:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.