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

unsigned char buf[] = 

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

  • 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

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.

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

  • 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.