Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Shellcode execution in C++

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading