Trying to hook D3D EndScene - c++

So I've been playing around with C++ and injecting DLLs, fairly new to this but learning fairly quickly. I'm trying to hook EndScene and just cannot get it working. I've tried using a pattern scan to find and then hook it, I've tried creating a dummy d3d device and finding the EndScene through its VTable. Each time it fails i get an Access Violation so I can only assume I have the wrong address for the function or maybe I'm missing something completely. I have tried a lot of different ways but due to limited knowledge need a little more help.
DWORD dEndScene = 0x10066D50;
HMODULE hBaseAddress = GetModuleHandle("d3d9.dll");
BYTE* pEndFunction = (BYTE*)reinterpret_cast<uintptr_t>(hBaseAddress);
pEndFunction = pEndFunction + dEndScene;
fEndScene = (oEndScene)DetourFunction(pEndFunction, (PBYTE)EndScene);

The vtable is likely write protected. You can use VirtualProtect.
And some slightly different approaches:
Is it possible to replace Direct3DCreate9(Ex) before its created? Then you just make proxy objects for the interfaces you want, which can then just delegate normally, do stuff before/after, or do something different entirely.
Or if you can get the IDirect3DDevice9 instance pointer, by getting then editing the vtable it references (again VirtualProtect, but avoids needing to know where the function lives in advance, which might change in various cases).

Related

How to hook CopyTextureRegion with Minhook

Im trying to hook the ID3D12GraphicsCommandList::CopyTextureRegion method with MinHook but the problem is that the method is inside ID3D12GraphicsCommandList which makes it hard to hook.
Here is my current approach which unfortunatley is 0
// not working, CopyTextureRegionHook is 0
auto CopyTextureRegionHook = GetProcAddress(GetModuleHandleA("d3d12.dll"), "CopyTextureRegion");
MH_CreateHook(reinterpret_cast<void**>(CopyTextureRegionHook), &HK_CopyTextureRegion, reinterpret_cast<void**>(&oCopyTextureRegion));
MH_EnableHook(CopyTextureRegionHook);
Hooking methods like D3D12CreateDevice, D3D12CoreRegisterLayers.. work because they are not in a interface like ID3D12GraphicsCommandList
How would I properly hook CopyTextureRegion?
Because you're dealing with an interface, you won't be able to hook the function directly in memory since it's dependent on the pointer to the interface. In which case you have to utilize a technique called VMT(Virtual Method Table) hooking. In order to achieve this, you'll need to be able to retrieve the pointer to the interface in memory, then locate the virtual method table index(offset) of the function pointer. Which then you'll have to overwrite with your own function address. Your hooked function will have to comply with the calling convention of the original.

C++: Code injection to call a function

First of all, I don't want to inject a dll. I want to inject code using WriteProcessMemory() (if this is even possible). I already used ReadProcessMemory() so I think writing is not a big deal.
Well, lets say there is a function at TargetProgram.exe+D78C612
and let's say it could be called like this:
push eax
push [esp+08]
push edx
push 00
push TargetProgram.exe+AF76235
push 04
call TargetProgram.exe+D78C612
How exactly would I accomplish this with WriteProcessMemory()?
I mean where do I find a section in which I can inject my code without overwriting important stuff. And most importantly, how would I call the function?
Just put a jump to my code in the active routine, jump back and delete it afterwards? But how would I find the routine?
So many questions and I have no idea how to start... I hope you can help me. :)
And if you have the time I would really like to see an example code of a function-call-injection.
You can use VirtualAllocEx to allocate memory in the remote process and then copy your procedure into this memory.
Here are the steps to do the injection:
SuspendThread(hThread); // Suspend the remote thread
remote_address = VirtualAllocEx(hProcess, ...) // allocate memory for your code
WriteProcessMemory(hProcess, remote_address, local_address, length, NULL) // copy your code to remote process
WriteProcessMemory(hProcess, remote_fixup, ...) // insert a jump to your code
ResumeThread(hThread); // Resume the remote thread
As mentioned by Max's answer, VirtualAllocEx is one way to allocate memory pages in a remote process, assuming you have the PROCESS_VM_OPERATION access right for the process in question. You will also want to make sure the new pages are marked PAGE_EXECUTE_READWRITE for their protection level during the writing and then change it later to PAGE_EXECUTE_READ using VirtualProtectEx.
Note that branching and some call instructions in x86 are IP-relative. This means their encodings are dependent upon where they are located in memory, as they use a signed relative displacement from the end of the instruction. So if you plan on calling an existing function from your new code, make sure you take this into account when using a relative call instruction or use an indirect/immediate form instead.
However, without knowing exactly what you're trying to accomplish here, it's difficult to recommend a technique for executing your new target code. With the new code in place, you could just inject a remote thread using CreateRemoteThread to execute it without having to disrupt any existing threads. This would be the simplest solution to execute the new code, but requires that the code you're calling is thread-safe. Picking an already running thread, suspending it, modifying EIP or introducing a detour, and resuming it without side effects (properly saving context across the injected call) is very tricky to say the least.
Personal note: as the author of the code coverage tool in Visual Studio 2012 that uses a bunch of tricks to rewrite third-party x86/x86-64 code on the fly to collect coverage data, this stuff is oh-so-much fun to hack and think on :)

C++ Function Hook (memory address only)

I have a memory address, its the memory address of a function in another program (one of its dlls). I am already loaded into the program via DLL injection. I already have the bass address, and the actual location of the function each time the program loads. So, this is not an issue.
I want to just simply hook that location, and grab the variables. I know the function's pseudocode. So this is not an issue. OR another approach that would be great is doing a break point at that memory location and grab the debug registers.
I can not find any clear-cut examples of this. I also do not have the "name" of the function, I just have the memory address. Is there any way to work with just a memory address? Most, if not all the examples have you use the name of the function, which I do not have.
If anyone could point me into the right direction so I can accomplish this task, I would greatly appreciate it. It also might help a lot of other people who may have the same question.
Edit: I should also mention that Id rather not overload my program with someone else code, I really just want the barebones, much like a basic car with roll-up windows. No luxury packages for me please.
You missed the most important part, is this for 32 or 64 bit code? In any case, the code project has a good run-down and lib here that covers both.
If you want to do this "old-school", then it can be done quite simply:
firstly, you need to find the virtual address of the function you want to hook (due to ASLR, you should never rely on it being in the same place), this is generally done with RVA + module base load address for function that are not exported, for exported functions, you can use GetProcAddress.
From there, the type hook depends on what you want to accomplish, in your case, there are two methods:
patch a jump/call out to your function in the target function' prologue
patch all call sites to the function you want to hook, redirecting to your function
the first is simpler, but messy as it generally involves some inline assembly (unless you are hooking a /HOTPATCH binary or you just want to stub it), the second is much cleaner, but requires a bit of work with a debugger.
The function you'll jump out to should have the same parameters and calling convention (ABI) as the function you are hooking, this function is where you can capture the passed parameters, manipulate them, filter calls or whatever you are after.
for both, you need a way to write some assembly to do the patching, under windows, WriteProcessMemory is your first port of call (note: you require RWX permissions to do this, hence the calls to VirtualProtect), this is a little utility function that creates a 32bit relative call or jump (depending on the opcode passed as eType)
#pragma pack(1)
struct patch_t
{
BYTE nPatchType;
DWORD dwAddress;
};
#pragma pack()
BOOL ApplyPatch(BYTE eType, DWORD dwAddress, const void* pTarget)
{
DWORD dwOldValue, dwTemp;
patch_t pWrite =
{
eType,
(DWORD)pTarget - (dwAddress + sizeof(DWORD) + sizeof(BYTE))
};
VirtualProtect((LPVOID)dwAddress,sizeof(DWORD),PAGE_EXECUTE_READWRITE,&dwOldValue);
BOOL bSuccess = WriteProcessMemory(GetCurrentProcess(),(LPVOID)dwAddress,&pWrite,sizeof(pWrite),NULL);
VirtualProtect((LPVOID)dwAddress,sizeof(DWORD),dwOldValue,&dwTemp);
return bSuccess;
}
This function works great for method 2, but for method 1, you'll need to jump to an intermediary assembly trampoline to restore any code that the patch overwrote before returning to the original function, this gets very tedious, which is why its better to just use an existing and tested library.
From the sounds of it, using method 1 and patching a jump over the prologue of your target function will do what you need, as it seems you don't care about executing the function you patched.
(there is a third method using HW breakpoints, but this is very brittle, and can become problematic, as you are limited to 4 HW breakpoints).
Your "sample" is here:
http://www.codeproject.com/Articles/4610/Three-Ways-to-Inject-Your-Code-into-Another-Proces#section_1
Normally when you "hook" into the DLL, you actually put your function in front of the one in the DLL that gets called, so your function gets called instead. You then capture whatever you want, call the other function, capture its return values and whatever else, then return to the original caller.

Converting a string into a function in c++

I have been looking for a way to dynamically load functions into c++ for some time now, and I think I have finally figure it out. Here is the plan:
Pass the function as a string into C++ (via a socket connection, a file, or something).
Write the string into file.
Have the C++ program compile the file and execute it. If there are any errors, catch them and return it.
Have the newly executed program with the new function pass the memory location of the function to the currently running program.
Save the location of the function to a function pointer variable (the function will always have the same return type and arguments, so
this simplifies the declaration of the pointer).
Run the new function with the function pointer.
The issue is that after step 4, I do not want to keep the new program running since if I do this very often, many running programs will suck up threads. Is there some way to close the new program, but preserve the memory location where the new function is stored? I do not want it being overwritten or made available to other programs while it is still in use.
If you guys have any suggestions for the other steps as well, that would be appreciated as well. There might be other libraries that do things similar to this, and it is fine to recommend them, but this is the approach I want to look into — if not for the accomplishment of it, then for the knowledge of knowing how to do so.
Edit: I am aware of dynamically linked libraries. This is something I am largely looking into to gain a better understanding of how things work in C++.
I can't see how this can work. When you run the new program it'll be a separate process and so any addresses in its process space have no meaning in the original process.
And not just that, but the code you want to call doesn't even exist in the original process, so there's no way to call it in the original process.
As Nick says in his answer, you need either a DLL/shared library or you have to set up some form of interprocess communication so the original process can send data to the new process to be operated on by the function in question and then sent back to the original process.
How about a Dynamic Link Library?
These can be linked/unlinked/replaced at runtime.
Or, if you really want to communicated between processes, you could use a named pipe.
edit- you can also create named shared memory.
for the step 4. we can't directly pass the memory location(address) from one process to another process because the two process use the different virtual memory space. One process can't use memory in other process.
So you need create a shared memory through two processes. and copy your function to this memory, then you can close the newly process.
for shared memory, if in windows, looks Creating Named Shared Memory
http://msdn.microsoft.com/en-us/library/windows/desktop/aa366551(v=vs.85).aspx
after that, you still create another memory space to copy function to it again.
The idea is that the normal memory allocated only has read/write properties, if execute the programmer on it, the CPU will generate the exception.
So, if in windows, you need use VirtualAlloc to allocate the memory with the flag,PAGE_EXECUTE_READWRITE (http://msdn.microsoft.com/en-us/library/windows/desktop/aa366887(v=vs.85).aspx)
void* address = NULL;
address= VirtualAlloc(NULL,
sizeof(emitcode),
MEM_COMMIT|MEM_RESERVE,
PAGE_EXECUTE_READWRITE);
After copy the function to address, you can call the function in address, but need be very careful to keep the stack balance.
Dynamic library are best suited for your problem. Also forget about launching a different process, it's another problem by itself, but in addition to the post above, provided that you did the virtual alloc correctly, just call your function within the same "loadder", then you shouldn't have to worry since you will be running the same RAM size bound stack.
The real problems are:
1 - Compiling the function you want to load, offline from the main program.
2 - Extract the relevant code from the binary produced by the compiler.
3 - Load the string.
1 and 2 require deep understanding of the entire compiler suite, including compiler flag options, linker, etc ... not just the IDE's push buttons ...
If you are OK, with 1 and 2, you should know why using a std::string or anything but pure char *, is an harmfull.
I could continue the entire story but it definitely deserve it's book, since this is Hacker/Cracker way of doing things I strongly recommand to the normal user the use of dynamic library, this is why they exists.
Usually we call this code injection ...
Basically it is forbidden by any modern operating system to access something for exceution after the initial loading has been done for sake of security, so we must fall back to OS wide validated dynamic libraries.
That's said, one you have valid compiled code, if you realy want to achieve that effect you must load your function into memory then define it as executable ( clear the NX bit ) in a system specific way.
But let's be clear, your function must be code position independant and you have no help from the dynamic linker in order to resolve symbol ... that's the hard part of the job.

Get specific process memory space

I have a pointer (void *) to a function and I want to know which process this function belongs to. I have no idea which way to go about it, but I think it's possible by using some form of VirtualQuery trickery. Any help would be appreciated.
Thanks in advance,
CLARIFICATION: By "belong to process" I mean what process the function is in. For example:
say there was an executable (test.exe) loaded in memory. This executable contains a function named SayHello, which is located at 0xDEADBEEF in memory. In an entirely different process, how would I know 0xDEADBEEF is in test.exe's memory space.
Hope that clears things up.
CLARIFICATION 2: I'm sure you're familiar with "VTable hooking", where an external module changes a VTable pointer in a seperate process to point to a different function. Thereby whenever the hooked member is called, it is passed to the external module.
To prevent this (anti-cheat), I want to be able to check whether all methods of a VTable point to the module they reside in.
SOLUTION CODE:
template<class T>
inline void **GetVTableArray(T *pClass, int *pSize)
{
void **ppVTable = *(void ***)pClass;
if(pSize)
{
*pSize = 0;
while(!IsBadReadPtr(ppVTable[*pSize], sizeof(UINT_PTR)))
(*pSize)++;
}
return ppVTable;
}
bool AllVTableMembersPointToCurrentModule(void *pClass)
{
DWORD dwOldProtect;
HANDLE hModuleSnap = INVALID_HANDLE_VALUE;
MODULEENTRY32 moduleEntry;
// Take a snapshot of all modules in the specified process
hModuleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId());
if(hModuleSnap == INVALID_HANDLE_VALUE)
return false;
// Set the size of the structure before using it
moduleEntry.dwSize = sizeof(MODULEENTRY32);
// Retrieve information about the first module (current process)
if(!Module32First(hModuleSnap, &moduleEntry))
{
CloseHandle(hModuleSnap);
return false;
}
// Grab the base address and size of our module (the address range where
// the VTable can validly point to)
UINT_PTR ulBaseAddress = reinterpret_cast<UINT_PTR>(moduleEntry.modBaseAddr);
UINT_PTR ulBaseSize = moduleEntry.modBaseSize;
// Get the VTable array and VTable member count
int nMethods;
void **ppVTable = GetVTableArray(pClass, &nMethods);
#ifdef VTABLE_FAKING
// Allow patching
VirtualProtect(ppVTable, nMethods * sizeof(UINT_PTR), PAGE_EXECUTE_READWRITE, &dwOldProtect);
// Now take the next module and set the first VTable pointer to point to an
// invalid address, outside of the current module's address range
Module32Next(hModuleSnap, &moduleEntry);
ppVTable[0] = moduleEntry.modBaseAddr;
#endif
// Don't allow people to overwrite VTables (can easily be bypassed, so make
// sure you check the VirtualProtect status of the VTable regularly with
// VirtualQuery)
VirtualProtect(ppVTable, nMethods * sizeof(UINT_PTR), PAGE_EXECUTE, &dwOldProtect);
// Clean up the snapshot object
CloseHandle(hModuleSnap);
// Ensure all VTable pointers are in our current module's address range
for(int i = 0; i < nMethods; ++i)
{
// Get address of the method this VTable pointer points to
UINT_PTR ulFuncAddress = reinterpret_cast<UINT_PTR>(ppVTable[i]);
// Check the address is within our current module range
if(ulFuncAddress < ulBaseAddress || ulFuncAddress > ulBaseAddress + ulBaseSize)
return false;
}
return true;
}
Each process has its own address space. This means that the same address will contain different things for different processes, so there is no way to do what you're asking.
If this pointer is to a function in the current program (i.e. a function that you can currently call), then the answer is simple: it belongs to the current process.
To further clarify: A pointer by itself is meaningless unless you already know which process it belongs to. Process #1001 may have a function sayHello at address 0x12345678, while process #1002 has the function sayGoodbye at address 0x12345678, and process #1003 contains some data at the same address. There is no way to know which process the pointer came from.
The hijacked function pointer in the VTable can only be inside your process, as the other folks have already answered. The memory address only makes sense for your process. If someone is going to overwrite one of your VTable spots, then they would first have to hook something your process, which means running code inside your process. There exists plenty of win API that provides hooking.
See EnumProcessModule to go through all of the modules in your process. See this about modules info including base address of your module. You would then have to check your VTables to make sure those addressed exist inside of your module's address range.
To prevent VTable hijacking in the first place? I don't know how to do this, other than trying Microsoft's Detours library, which can in theory be used to detour any hook API call inside your process.
If you have the module handle, you can inspect the image header to ensure that the vtable pointers are in that module's virtual address space.
In any of the Windows operating systems that are descended from Windows NT (so, for all intents and purposes anything including and after XP, and before that NT 4 and NT 3.51) each process has it's own address space. Within reason, any pointer address can be different in every process in the system as they all have an 0xDEADBEEF address and it may, or may not contain the same thing as other processes. This was not the same with Windows 3.0, 3.1, 95, 98 and ME (they had one address space which all processes shared) where your question MAY have made more sense.
So, without a handle to a process to go with your pointer address the address is pretty much useless to you. With a handle to a process you can (possibly) work out what you want by walking the import tables for the DLLs that you import... If the function isn't an imported function then it's unlikely that you could work out what you want to know.
Note that if the address is to a function which is from a 'standard' system DLL then you MAY be able to work out where it lives by finding out what function it represents in the address space of your process as there is a strong chance that the DLL will be mapped to the same base address in your process as it is in every other process.
Why not tell us a little more about what it is, exactly, that you're actually trying to do?
Edit:
Well, as I described above, what you're suggesting is not possible except on very old versions of Windows. What IS possible is that you can inject code into a process to replace that code that should be executed. The address of this injected code is valid in the target process's address space and contains code that you (the hacking process) have created. You do this by a combination of allocating memory in the remote process with VirtualAllocEx() (1) and then writing your code to it with WriteProcessMemory() (2). You now have code that you wrote in the target process. You can then patch it in so that it's called instead of the code that should be called.
The common way to do this is IAT hooking (Import Address Table hooking) and this lets you replace imported functions from DLLs. To detect this you need to scan the DLL's Import Address Table from the DLL image on disk, work out where the functions are in memory and then scan the in memory IAT to check that the functions are where they should be; if they're not then they've likely been patched.
You're suggesting that someone is replacing an arbitrary C++ vTable entry. This is possible with the same technique but it's harder as there's no convenient table of names to addresses that you can use to work out where to patch. Anyway, assuming the bad guy can find the correct address to patch he can use the same technique as above to create his own function in your process.
Detecting the vTable problem is made more complex by the lack of name to address lookup, but if you're in the process that's being hacked you can simply have written code that takes the address of the function in question at start up. Store that somewhere and compare it later. However, you'd probably best take a copy of the whole function itself in memory and compare with that as you might find that the bad guys simply look for some recognisable function signature bytes and patch a jump into them somewhere to their own code or simply to skip yours.
Good luck and grab yourself a good book, such as one by Jeffrey Richter which will explain much of this far better than I can.
I don't really understand your question, so I'm going to take a stab in the dark and answer what I think you're asking.
You're asking how you can find out, from a function pointer, to which module it belongs.
The solution is rather simple in theory, scan backwards in memory to find the header, and then enjoy using this function GetModuleFileName.
Since your question isn't well worded, you don't get a well worded answer.