How global SetWindowsHookEx manages to inject dll into all threads? - windows

I created 2 hooks in my host application. 1st is WH_MOUSE set specifically for Taskbar's thread. 2nd is global WH_KEYBOARD_LL hook (dwThreadId is set to 0).
As you can see in Process Explorer, the "local" hook actually injected my dll into specific explorer.exe thread. However, there is no indication that my 2nd global hook got injected into any other processes, yet it still works perfectly... Moreover, it also works for all the new processes I start, even after the hook was set! How SetWindowsHookEx manages that?
I read that it only applies to processes that load user32.dll. My weak suspicion is that in a case of global hook, Windows somehow injects my custom dll code into user32.dll "hook-chain". And then, when new process that loads user32.dll is started, it automatically loads my hook with it? Is this correct or is there some other mechanism at work?

_LL (low-level) hooks are not injected anywhere, win32k (the kernel part of the window manager) calls the hook callback function directly. This is why that thread needs a message loop. Low-level hooks are always "global".
MSDN says:
Be aware that the WH_MOUSE, WH_KEYBOARD, WH_JOURNAL*, WH_SHELL, and low-level hooks can be called on the thread that installed the hook rather than the thread processing the hook.
You should think of hooks as having 3 modes:
Low-level (keyboard and mouse only)
Thread specific
All threads
The last two might require Windows to inject the .dll.

Related

How to hook any API call on windows x64, x86?

I'm working on a way to hook any API call to perform some verification on the function. (I'm creating a SandBox)
The first way that I think about, is with register key, and implement our own dll into MicrosoftNT to be able to redirect any defined syscall. https://www.apriorit.com/dev-blog/160-apihooks .
Problem? only work on 32 bit, and if the binarie is loading User32.dll, so it's abig issue.
The second way is to inject a dll into a process? Simple but impossible, most program is defended from those injection, so it's not possible.
The last way that I think was to modify the SSDT to change the function address by mine and redirect to the original by creating a driver. Or by InlineHook and just modify the first byte of each address that I want.
The Problem, only working on 32 bit, because windows add a PatchGuard on the Kernel, so we can't do that.
We can delete de PatchGuard but, anticheat will notice the technique.
For the Sandbox I think it won't be a problem to delete a PatchGuard.
The main problem is for real time analysis, I have no more idea how I can do to hook every API call that I want, on any windows OS. I mean on 32 and 62 bit.
I'm a beginner in this domain I started this week so I'm open to any suggestion.
You say you want to hook every API call for a sandbox but then reference the SSDT? Those are two very different things. Do you want to hook VirtualQuery(Ex) or do you want to hook NtQueryVirtualMemory? From kernel or user mode? Or maybe you're referring to all loaded module exports as well as kernel system services?
WinApi
Iterate all loaded modules as well as installing an event to hook all future modules loaded. For each one you will iterate all exports and apply a hook of your preference which all jump to some handler. This handler should be raw assembly that preserves the CPU state, calls some method that does the logging and filtering, restores CPU state, before finally jumping to the original.
Syscalls
Disable Patchguard and apply hooks to every method in the service table similar to the WinApi method described above. This is definitely not suitable for production for obvious reasons.
Use an instrumentation callback which uses ZwSetInformationProcess to redirect most syscalls to an arbitrary assembly block. You can extract the syscall id here as well as parameters. Universal support is an issue though as it wasn't introduced until W7 iirc and you have a lot of limitations prior to W10.
Map a wrapper module that has a hook for every syscall into each newly loaded process from kernel. These hooks will apply to ntdll and simply invoke an NtDeviceIoControlFile call with the syscall id and arguments, forwarding it to your kernel driver for processing. This is commonly employed by antivirus software to monitor user mode system calls without disrupting Patchguard.
The most approved method would probably be callbacks. You can register process and thread callbacks in kernel, stripping handle access at your leisure. This will give you full control over process and thread access from external processes, and you can add a file minfilter to similarly restrict access to the file system.

how to hook all new processes in Windows

I want to write a program to detach dll injection or vulnerability exploit by creating a monitor thread for all processes.I want to do this in user level instead of inserting a driver.
I try to use AppInit_DLLs to create a thread at DllMain,but it's not work if a program don't load user32.dll.
I try to listen a new process creation event and suspend new process for loading my monitor dll,but it's not work well.
Is there any methods to hook all new processes before they start run?
Most programs are run via double click so explorer.exe is the process which uses CreateProcess to launch them
Hook explorer.exe and make CreateProcess and ShellExecute/Ex hook the created processes also and so on
You can do some more by hooking all the running processes with the same technique once your injector opens thus you absolutely are hooking all user mode processes
Make sure to have the proper rights if you aren't running as admin you won't be able to hook processes running as admin
The functions you need to hook are usually CreateProcess NtCreateProcess ShellExecuteInfo/Ex
You will be using NtSuspendProcess and NtResumeProcess to set your hooks before the process has a chance to defend itself but tls callbacks may be already called , and in case of NtCreateProcess , CreateProcess you can use CREATE_SUSPENDED then ResumeThread with the thread handle you get from the function
if you want to go deeper you can hook NtCrateFile as any attempt to execute exe or load a dll will need to open the file to allocate the image in the memory

ExitProcess behaviour in Windows in relation to atexit handlers

I want to be able to catch any attempts of executing exit()/ExitProcess()/TerminateProcess() or any other such calls.
I thought about registering a handler with atexit(). This works fine for normal program termination (return from main()) or exit() calls (regardless of the thread that calls exit()), but ExitProcess() and TerminateProcess() bypass the handler I registered.
ExitProcess() documentation states:
Note that returning from the main function of an application results
in a call to ExitProcess.
But the observed behaviour is at least different in this regard.
Is there a method of registering a handler for process exit/termination what will always be called (except for external calls to TerminateProcess(), unhandled exceptions thrown by one of my threads or __failfast() calls, I'm guessing these are really impossible to catch).
There is the dirty option of hooking ExitProcess(), but I'd rather not do that.
EDIT: just so this is clear: I'm interested in my own process, not monitoring / controlling another process.
There is a Kernel Mode Event a device driver can subscribe to in order to get notifications of terminations of processes. This is preferred over trying to inject a DLL into processes for API hooks due to the myriad number of internal and external ways that process may end.

Hookin CreateProcessEx

i would like to systemwide hook CreateProcessEx
it is redirects all windows calls into my wrapper function
where I will log names to textfile then call oruginal CreateProcessEx
Can it be easy and safely done ?
I would like hook all systemwide calls to it but not etternaly
for some period of time only.. How to do it?
If I will find the adress of this api call in ram then overvrite
it with call to my procedure, how then I will call the oryginal
function if there it is somewhat corrupted?
Hooking CreateProcess is the wrong approach for a few reasons. There is an approved mechanism for doing this sort of thing but you need a driver to be loaded. Your driver can then simply leverage the PsSetCreateProcessNotifyRoutine function.
With that said, would your needs not be served by using the auditing functionality built into Windows? Turning on process creation auditing will cause the system to write an event log entry whenever a process is created, detailing plenty of information about the process being started, including the image path.
CreateProcessEx() is a user-mode function. You have to patch it on a per-process basis. That means creating a DLL that is injected into every running process, such as by using SetWindowsHookEx() or the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows\AppInit_DLLs Registry key, and then have that DLL patch the PE Imports table of every process it is loaded into.

creating window in child thread in vc++

I want to create a window and show some image display (like animation based on SetTimer()) on window created using CreateWindow() function. But it should be created on separate thread and should remain alive until user closes this. I tried but was unsuccessful.
EDITED
I just googled I found this link How To Create Windows in a Multithreaded Application but one thing i want to know when Window Procedure get invoked. if it is invoked by system then how i can call it from my child thread.
Windows (represented by HWNDs) in Windows have a thread affinity. Their WindowProc is always invoked in the context of the thread they are created with.
As such, they are a convenient way to serialize calls between threads as the PostMessage and SendMessage APIs can be called from any thread in the application, but the WindowProc will get executed in the context of the original creating thread.
Because WM_TIMER messages posted to message queues are the mechanism by which SetTimer works, again you need to be careful when calling SetTimer in a multithreaded app - The timer messages will be processed by the calling thread (if the hwnd parameter is NULL) or the window's thread.
You also, as a result, have to be careful to put a message loop on every thread that might create windows, or want to process timers.
Keep your user-interface on the main Windows thread. Setting a timer using the Windows API doesn't require an additional thread (as your WndProc will get the timer message WM_TIMER).
Even if you have a long running task to perform that might necessitate the use of an additional thread, keep the window on the main thread, do your work in the worker-thread and post back to the main thread with updates.

Resources