Files
Microsoft-Detours/samples/payload/payloadtarget.cpp
Charles Milette 8cbb9e2b82 Feature: Add DetourFindRemotePayload and improve other payload-related methods (#81)
Other improvements:

- Makes the pcbData parameter in DetourFindPayload and DetourFindPayloadEx optional, so that if an application only needs to search for the presence of a payload, they can ignore the size by passing nullptr.

- Makes the pvData parameter in DetourCopyPayloadToProcess const, so that a pointer to a const C++ object can be passed instead of the object needing to be const_casted or being non-const.

- Adds DetourCopyPayloadToProcessEx, which has the same interface than DetourCopyPayloadToProcess, but it returns the address of the payload in the remote module, if the program later wants to write to it.

- Add payload example and extra unit tests covering new APIs. 

Fixes #79

Co-authored-by: Charles Milette <me@charlesmilette.net>
2021-03-06 00:22:08 -08:00

60 lines
1.4 KiB
C++

#define _CRT_RAND_S
#include <stdlib.h>
#include <iostream>
#include <windows.h>
#include <detours.h>
#include "payloadguid.hpp"
HANDLE hParent = NULL;
__declspec(noreturn) void HandleApiFailure(const char* api)
{
DWORD lastErr = GetLastError();
std::cout << "payloadtarget.exe: " << api << " failed (" << lastErr << ')' << std::endl;
if (hParent)
{
CloseHandle(hParent);
}
ExitProcess(1);
}
int main()
{
DWORD payloadSize;
void* payloadAddr = DetourFindPayloadEx(PARENT_HANDLE_PAYLOAD, &payloadSize);
if (!payloadAddr || payloadSize != sizeof(HANDLE))
{
HandleApiFailure("DetourFindPayloadEx");
}
hParent = *static_cast<HANDLE*>(payloadAddr);
DWORD randomPayloadSize;
void* randomPayload = DetourFindRemotePayload(hParent, RANDOM_DATA_PAYLOAD, &randomPayloadSize);
if (!randomPayload || randomPayloadSize != sizeof(random_payload_t))
{
HandleApiFailure("DetourFindRemotePayload");
}
random_payload_t randomData;
if (rand_s(&randomData) != 0)
{
HandleApiFailure("rand_s");
}
if (!WriteProcessMemory(hParent, randomPayload, &randomData, sizeof(randomData), NULL))
{
HandleApiFailure("WriteProcessMemory");
}
CloseHandle(hParent);
hParent = NULL;
// conversion to int return type is potentially undefined
ExitProcess(randomData);
}