Hooking OpenProcess() or ReadVirtualMemory() in win32 userland code - c++

Is there anyway to hook/detour either of OpenProcess() or ReadProcessMemory() function calls to my own custom functions?
Without:
kernel driver on Zw/NtOpenProcess, requires rootkit exploit or
driver signing for deployment
injecting .dll's in every process, spammy waste of resources and
alerts many antivirus
I am trying to prevent other processes from getting a HANDLE or reading the memory of a vector of PIDs.

If you do not hook the calls globaly on kernelmode, you have to get into every targetprocess. A dll would be the easiest solution, but you could do more hacky and tedious stuff.
Use OpenProcess and ReadProcessMemory (what a coincidence!) and WriteProcessMemory to modify every target process. Hook the desired functions and patch in your desired functionality with a filter function.
Note that if somebody gets to know what you are doing and wants to prevent it there is nothing you can do. He could re-patch your code or use some direct asm calls to call the APIs (SYSCALL).

Related

detour hooking usermode functions from the kernel

I have a kernel mode driver and I'm trying to implement a way so that I can make usermode hooks from it. I need to hook usermode functions via detour/jmp from the kernel.
To perform an external detour from kernel you do the same thing you do in usermode except instead of WriteProcessMemory you would use NtWriteVirtualMemory.
The problem this idea presents is: where are you jumping to? You can't jump into the kernel, so you are still left with the problem of getting your code into the target process. You can write shellcode, inject a DLL etc...
But the whole purpose of using the driver is to bypass protection and detection mechanisms. A mature anti-debug detection solution will detect you writing your jump and writing your shellcode via memory integrity checks.
The solution isn't as simple as "go kernel", you need to nullify the protection and detection mechanism from kernel first.
If you've nullified the detection/protection mechanism then you might as well inject a DLL and just perform a normal usermode detour at that point.

Hook a specific function in a dll

Is it possible to hook all the processes, or find out when a specific function in a dll is called? I want to be able to catch this call and inject my own code / deny access to this function. How can I do this without looping through all the processes and hook each one of them?
Is it possible to do so without altering system files? (I'm planning on doing this on an android device and I don't want to require a root)
Simply write a dll with the same ABI.
The idea is to make you dll call the equivalent functions from the original dll, eventually adding a special process, or do nothing or report an unauthorized call if necessary.

Prevent Dll injection from an Dll C++

I have some doubts about anti dll injection in C++.
I have a game C++ based, Im having problems with hackers with dll injection.
Then i need to prevent it.
I find notify hook there from there:
MSDN - Notification Hooks
But i dont have idea how to use it.
Its is possible notify hook to prevent dll injection?
How its possible? (With and example better).
Can be from dll? (With example better).
Thanks for read that post.
PS: sorry for my english.
Forget it, unless you do very sophisticated things, it's not going to work. By sophisticated I mean something like the code obfuscation, anti-debugging technology used in Skype. Just look at this talk.
You can spend a ton of time on trying to prevent DLL injection, in the end somebody will spend less time than you and circumvent your protection. I think the time would be better invested in an architecture that's more secure and tamperproof (ie calculating scores on the server, etc).
It's a cat and mouse game you can't win.
This question is old but I will briefly answer it in better form for anyone who does happen to stumble upon it magically after a proper response.
You cannot fully prevent code injection from within your own process, but you can try to do some tricks without interception of other processes. It is not recommended because you need to have experience and knowledge with lower-level tasks, especially to get it working properly and not prevent functionality of your own software, however...
Asynchronous Procedure Calls (APC) is an implementation from the Windows Kernel. It is primarily used for code injection into other running processes, Windows uses it a lot itself for a variety of things such as notifications being sent to specific processes. When a user-mode process calls QueueUserApc (KERNEL32), NtQueueApcThread (NTDLL) will be invoked. NtQueueApcThread (NTDLL) will perform a system call which will cause NtQueueApcThread (NTOSKRNL) to be invoked, which is not exported by NTOSKRNL - for anyone wondering, NTOSKRNL is the Windows Kernel, and a system-call is nothing more than a transition from user-mode to kernel-mode since the Native API System Routines exist in kernel-mode memory, NTDLL routines for NTAPI are system call stubs which direct control up to the Windows Kernel. When NtQueueApcThread (NTOSKRNL) is called, it'll use KeInitializeApc and KeInsertQueueApc (both do happen to be exported by NTOSKNL). When the APC is actually issued to the targeted process, KiUserApcDispatcher (NTDLL) will be locally called within the process, unless the APC is performed in a more extensive manner to bypass this activity (99% of the time it will not be prevented). This means that you have an oppertunity to intercept this behavior and prevent APC injection into your own process with one single local hook in your own process, via byte-patching (also known as "inline hooking") KiUserApcDispatcher, exported by NTDLL. The only problem which you will face is that it is undocumented and this is not officially supported by Microsoft; you'll need to figure out how the parameters work and how to prevent the callback routine from blocking off genuine requests which are needed to provide functionality for your own software. This will however include prevention of kernel-mode APC injection, not just user-mode attacks.
There are many ways to inject code into a process, and APC is simply one of them. Another common method would be through remote thread creation. When a user-mode process attacks another process via remote thread creation, it'll typically call CreateRemoteThread (KERNEL32). This will lead down to RtlCreateUserThread (NTDLL), and RtlCreateUserThread will call NtCreateThreadEx (NTDLL). NTDLL will perform a system call and then NtCreateThreadEx (non-exported routine from the Windows Kernel) will be invoked in kernel-mode memory. In the end, the targeted process will have LdrInitializeThunk locally invoked, and RtlUserThreadStart will also be invoked locally. Both of these routines are exported by NTDLL. This is a same scenario as with APC... You can patch LdrInitializeThunk locally, however you must do it properly to prevent genuine functionality within your own software.
These two techniques are not full-proof, there is no "full-proof" solution. There are many ways to inject code into a process, and there are very sophisticated methods to bypass said solutions from myself. Anti-Virus software has been battling anti-RCE/self-protection for as long as I can remember, as has Anti-Cheat systems. You should look into kernel-mode device driver development as well, it'll allow you to register kernel-mode callbacks which can help you out.
The first callback you should look into is ObRegisterCallbacks. It allows you to receive a Pre-operation callback notification whenever NtOpenProcess is called from the Windows Kernel. This means that user-mode processes will also trigger it, since NtOpenProcess ends up being called in kernel-mode after NTDLL makes the system-call. I cannot remember specifically if the callback APIs are triggered in the NtOpenProcess stub itself or if it goes deeper into Ob* kernel-mode only routines, but you can check at ease with WinDbg with remote kernel debugging, or Interactive Disassembler (target ntoskrnl.exe and use the symbolic links provided by Microsoft). ObRegisterCallbacks supports notifications for both handle creation & duplication for the process and the processes' threads, you can strip access rights you don't want permitted for the requested handle.
The second callback you should look into would be PsSetCreateThreadNotifyRoutineEx. This callback routine will allow you to receive a notification whenever a new thread creation occurs on the system; you can filter it out for your own process and if a rogue thread is created, terminate the thread.
The third callback you should look into would be PsSetLoadImageNotifyRoutineEx. This callback will provide a notification whenever a new module is loaded into a process; once again, you can filter for your own process. If you detect a rogue module, you can attempt to have your process call LdrUnloadDll (NTDLL) targeting the base address of the newly loaded image, however the reference count for the module needs to be 0 for it to be unloaded. In that case, you can try "hacky" methods like calling NtUnmapViewOfSection/NtFreeVirtualMemory. Bear in mind, if you mess up the rogue loaded module and it has set memory byte patches to redirect execution flow to its own routines, unless you restore them, your process will crash when they are referenced.
These are some ideas, commonly the ones typically used. Kernel-Mode callbacks are very popular among security software and anti-cheat software. As for thread creation, you'll be interested in mitigating this as much as possible -> if you only look for rogue DLL loads then you'll miss out on reflective DLL loading. Also remember of the other code injection methods, like thread hijacking, shared window memory exploitation with ROP chain call exploitation, DLL patching on-disk, etc.

is it possible to inject multiple Dlls with MS detours?

In c++ ,I want to hook more than one dll to a process. Right now I use CreateProcesswithdll() which can hook only one api at a time. What can I do to inject multiple dlls?
I came across this problem because MS detours requires us to name our custom dll the same as original dll in order to properly detour the api calls. So even though i could have different api calls handled in the same detour dll I created I need to have different names to hook calls from different apis, which means I need different detour Dlls. This also means I need to inject different DLLs. Am I right?
If I am unclear about something I will try to present it more clearly :D
Thanks!
P.S: Just to make my problem more lucid. I need to inject more than 1 dll onto the same process. CreateProcesswithdll() creates a new process with its thread in sleep state. It is woken up after the detours has finished injecting the dll and setting up the hooks. If I want to inject more than one dll I obviously cant repeatedly call CreateProcesswithdll()
so what do i do?? or Is my understanding about some aspect of this wrong?
Calling LoadLibrary() and FreeLibrary() is NOT SAFE from DLLMain(). From TFA:
"The entry-point function should
perform only simple initialization or
termination tasks. It must not call
the LoadLibrary or LoadLibraryEx
function (or a function that calls
these functions), because this may
create dependency loops in the DLL
load order. This can result in a DLL
being used before the system has
executed its initialization code.
Similarly, the entry-point function
must not call the FreeLibrary function
(or a function that calls FreeLibrary)
during process termination, because
this can result in a DLL being used
after the system has executed its
termination code."
EDIT: Apologies - this was meant as a comment for Serge's answer above.
Seems like detourattach and detourdetach will do the trick for me. Thanks everyone!
I found this blog useful!
Obviously you can load any number of DLLs from the first DLL you inject with detours.
EDIT.
When DLL is loaded system runs DllMain of your DLL (with fdwReason==DLL_PROCESS_ATTACH) and then within that function you can do whatever you like, e.g. you can call LoadLibrary to load other DLLs.
ADD:
I totally agree with comments that calling LoadLibrary from DllMain is unsafe. So you can call LoadLibrary (and all the other tricky things) from thread created in DllMain.

C++ thread to separate process

Is there any way I can have a thread branch off into its own independent process? I know there's the CreateProcess function but as far as I can tell, you can only run external applications with it. Is what I'm asking for at all possible?
It is possible.
You could call CreateProcess with a dummy application and with the CREATE_SUSPENDED flag so it doesn't run immediately. Then you can use VirtualAllocEx to allocate memory space in the created process and WriteProcessMemory to write code and data into it. And then unsuspend the process to run it.
You can also use CreateRemoteThread to create a process running within the context of another existing process.
So what you want to do is possible, but it's really not a simple thing to do in a windows environment so you'd have to have a really good reason to want to do it.
That's not possible under Windows. On Posix platforms the desired effect could be achieved by fork()ing.