C++ Code Cave Function Template

#define _CRT_SECURE_NO_WARNINGS 

#include
#include
#include

typedef int(__stdcall *__MessageBoxA)(HWND, LPCSTR, LPCSTR, UINT);

class cavedata {
public:
char chMessage[256];
char chTitle[256];
DWORD paMessageBoxA;
};

DWORD GetProcId(char* procname)
{
PROCESSENTRY32 pe;
HANDLE hSnap;

pe.dwSize = sizeof(PROCESSENTRY32);
hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(hSnap, &pe)) {
do {
if (strcmp(pe.szExeFile, procname) == 0)
break;
} while (Process32Next(hSnap, &pe));
}
return pe.th32ProcessID;
}

DWORD __stdcall RemoteThread(cavedata *cData)
{
__MessageBoxA MsgBox = (__MessageBoxA)cData->paMessageBoxA;
MsgBox(NULL, cData->chMessage, cData->chTitle, MB_ICONINFORMATION); //call it
return EXIT_SUCCESS;
}


int main()
{
cavedata CaveData;
ZeroMemory(&CaveData, sizeof(cavedata));
strcpy_s(CaveData.chMessage, "function called from remote process");
strcpy_s(CaveData.chTitle, "title from codecave");
HINSTANCE hUserModule = LoadLibrary("user32.dll");
CaveData.paMessageBoxA = (DWORD)GetProcAddress(hUserModule, "MessageBoxA");
FreeLibrary(hUserModule);

HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetProcId((char*)"coreshredder.exe"));
LPVOID pRemoteThread = VirtualAllocEx(hProcess, NULL, sizeof(cavedata), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
WriteProcessMemory(hProcess, pRemoteThread, (LPVOID)RemoteThread, sizeof(cavedata), 0);
cavedata *pData = (cavedata*)VirtualAllocEx(hProcess, NULL, sizeof(cavedata), MEM_COMMIT, PAGE_READWRITE);
WriteProcessMemory(hProcess, pData, &CaveData, sizeof(cavedata), NULL);
HANDLE hThread = CreateRemoteThread(hProcess, 0, 0, (LPTHREAD_START_ROUTINE)pRemoteThread, pData, 0, 0);
CloseHandle(hThread);
VirtualFreeEx(hProcess, pRemoteThread, sizeof(cavedata), MEM_RELEASE);
CloseHandle(hProcess);
getchar();
return 0;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s