Search code examples
c++function-pointersshellcode

Run shellcode in cpp


I am trying to run shellcode in cpp (the shellcode come from the user so the program should be dynamic) When I try to run my program I got an exception which ,I think, tells me that I can't run code from data section. after that I tried to create a new exceutable section and put there my data but it didn't work

#pragma section(".shell",read,execute)                                                                                                                        
__declspec(allocate(".shell"))
unsigned char code[] =
"\xB8\x04\x00\x00\x00";

// Function pointer points to the address of function.
int(*shell)(); //Function pointer
// Initializing a function pointer  with the address of a shellcode
shell = ((int(*)())&code);
// Execute shellcode
int a = shell();

can someone explain to me what am I doing wrong?


Solution

  • All that you have wrote is correct. Exception is raised just because your shellcode consist only mov eax, 4. The Windows allocator aligns your section to the page size and fills it with zeros, but 0x00 is opcode for add byte ptr [rax], al. Now you have not only mov eax, 4 in your shellcode, but:

    mov eax, 4
    add byte ptr [rax],al
    add byte ptr [rax],al
    ....
    

    After your mov you try to get value at eax addres 0x00000004, where Windows page guard were placed. And now you have 0xC0000005: Access violation on write "0x0000000000000004".

    Add ret to your shellcode:

    unsigned char code[] = ""\xB8\x04\x00\x00\x00\xC3"
    

    And you won't execute unused commands and exit succesfully.