Execute shellcode by clicking on a function pointer in Visual C ++

On gcc, this works fine. The code looks something like this:

unsigned char b[50] = "\xda\xd1 ... \x0"; //some shellcode with terminating \x0 ( (void(*)())b )(); //cast b to function pointer from void to void, then run it 

But when it fits in Visual C ++, it spits out this error message:

 1>..\test.cpp(132): error C2440: 'type cast' : cannot convert from 'unsigned char [50]' to 'void (__cdecl *)(void)' 1> There is no context in which this conversion is possible 

Does anyone know why this is so?

+6
source share
2 answers

A proper debugger will tell you what is going wrong. I can only guess that your code is causing an access violation because the buffer you want to go to is not executable.

You are probably the default DEP system, such as Vista or 7, so you need to make sure your shellcode is executable. To do this, first use VirtualAlloc to select a new, executable buffer and copy your shellcode to it, then execute it :

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

By the way, you do not need to null-terminate the shellcode (C ++ automatically terminates the string literal, but this is optional). You also do not need to specify the size:

 unsigned char b[] = "\xcc"; 
+11
source

A typical way to re-interpret data as another type is to copy the binary representation:

 void (*fp)(); unsigned char buf[50]; char const * p = reinterpret_cast<char const *>(&buf); std::copy(p, p + sizeof(char const *), reinterpret_cast<char*>(&fp)); // now fp contains the same value as &buf fp(); // call 

This avoids undefined behavior caused by aliasing and alignment violations.

0
source

Source: https://habr.com/ru/post/910126/


All Articles