0

Working on some test projects, and I have this code, which works fine:

#include <windows.h>
#include <iostream>

using namespace std;

int main(int argc, char** argv) {
    char shellcode[] = "..snip..\xa0\x4e\xbc\x0b\x45\xee\xb3\x1b\xf9..snip..";
    void* exec = VirtualAlloc(0, sizeof shellcode, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
    memcpy(exec, shellcode, sizeof shellcode);
    ((void(*)())exec)();
    return 0;
}

But I am trying to pass the dynamic sized byte array with the shellcode and this doesn't execute the code:

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

    std::string(test) = "..snip..\xa0\x4e\xbc\x0b\x45\xee\xb3\x1b\xf9..snip..";

    char* shellcode = new char[test.size()];

    memcpy(shellcode, test.data(), test.size());
    //std::copy(test.begin(), test.end(), shellcode);
    //delete[] shellcode;
    //std::cout << shellcode;

    void* exec = VirtualAlloc(0, sizeof shellcode, MEM_COMMIT, PAGE_EXECUTE_READWRITE);

    memcpy(exec, shellcode, sizeof shellcode);

    ((void(*)())exec)();
    //return 0;
}

Could anyone point out where is a problem? Or how could I improve this?

P_n
  • 940
  • 2
  • 11
  • 25
  • Variable length arrays (VLAs) are not part of standard C++ - but some compilers support them as a language extension. Don't use VLAs. If you need a dynamic array, use std::vector. – Jesper Juhl Dec 30 '21 at 07:47

1 Answers1

2

In your first example, sizeof shellcode is the size of the array itself. In your second example, sizeof shellcode is the size of the pointer. It will always be either 4 or 8.
Change the VirtualAlloc and subsequent memcpy statements to this:

void* exec = VirtualAlloc(0, test.size(), MEM_COMMIT, PAGE_EXECUTE_READWRITE);

memcpy(exec, shellcode, test.size());
selbie
  • 100,020
  • 15
  • 103
  • 173