Deviarev2 Hook API: Hook into existing process winapi calls? - c++

I want to use Deviare V2 API to intercept winapi calls from a test application. The problem is the hooks and the system calls are in the same process and for this reason the calls aren't intercepted.
If I open separate processes for each of them then the interception will work. Does anyone else ever had this scenario/problem ?
The thing is I'm trying to add some unit test to a peace of code and instead of modifying existing production code to wrap/mock all system calls I thought I could simply intercept all this calls and fake them as I wish.

It's actually much easier to hook APIs in your own process (actually when you want to hook in another process you need to DLL inject into that process anyway, so basically when you're hooking in your own process you can just skip that step). It might be a bug with the library you are using. Try Microsoft Detours or if you're up to it, patch the memory yourself, it's not that hard actually, a few hours work if you're new to the subject.
What you need to be wary of is that some C++ compilers will in some cases (I think debug builds) use some jump stub or something like this, which can interfere with the hooking process. In that case you must take some extra care when hooking - MS Detours probably does this properly. You can try debug/release builds if that affects your success.
What I mean is to get the proper address of the API. If the function is in a DLL like is the case with WinAPI you can be sure you are getting the right address if you use LoadLibrary and GetProcAddress.
On a side note I don't think API hooking is a proper way to avoid mocking/stubbing for testing, although it should work.
If you are interested more in how hooking works you can check out my paper on it here: http://lkm.fri.uni-lj.si/zoranb/research/berdajs-bosnic%20SPE%202011.pdf

Related

Trying to hook to MessageBeep system API

I've been asked by a client to solve the following pesky issue. They have a custom software that has a tendency of displaying message boxes "left and right" without any apparent reason. For instance, the software itself is an accounting program, and when they take a customer's payment, the message box may be displayed about 3 or 4 times in a row. Each message box plays Windows default sound. Unfortunately the way this software was programmed, the type of sounds it plays is completely wrong. For instance, it may display a warning message box and play the warning system sound when the message itself is just an information. All this is quite annoying for the staff who uses the software.
I tried to contact the vendor who distributes the software, but I hit a deadend with them. So now I am looking for ways to mitigate this issue.
My easiest solution was to suggest to mute the speakers, but unfortunately, they require sound to be present to be able to hear incoming emails, and most importantly, be able to play voice mail from them later. So my solution was to somehow mute message box sounds just for a single process.
From my experience, I know that there're two APIs that may be producing these sounds: MessageBeep and an older Beep.
I also found this article that explains how to use AppInit_DLLs to hook to system APIs. It works great, except that both of the APIs that I need to hook to come from User32.dll and not from kernel32.dll like the author suggests.
There's also this post in the questions section that kinda gives approximate steps to hooking to an API from User32.dll, but when I tried to implement them, there's not enough information (for my knowledge to do it.)
So my questions is, does anyone know how to hook to an API in the User32.dll module?
EDIT: PS. Forgot to mention. This software is installed on Windows 7 Professional, with UAC disabled -- because it is not compatible with UAC :)
As an alternative you can patch you application. Find calls to MessageBeep and overwrite them with nop.
This is the hard way of doing it: if your app is supposed to be running as Administrator on a pre-Vista Windows, you could get the address of the API via ::GetProcAddress(), give yourself privileges to write to its memory page, and overwrite the beginning of the API's code with a "jmp" assembly instruction jumping into the address of your override function. Make sure your overwrite function takes the same arguments and is declared as __cdecl.
Expanded answer follows.
The "standard" technique for API hooking involves the following steps:
1: Inject your DLL into the target process
This is usually accomplished by first allocating memory in the target process for a string containing the name/path of your DLL (e.g. "MyHook.dll"), and then creating a remote thread in the target process whose entry point is kernel32::LoadLibraryA() passing the name of your DLL as argument. This page has an implementation of this technique. You'll have to wrestle a bit with privileges, but it's guaranteed to work 100% on Windows XP and earlier OSes. I'm not sure about Vista and post-Vista, Address Space Layout Randomization might make this tricky.
2. Hook the API
Once your DLL is loaded into the target process, its DllMain() will be executed automatically, giving you a chance to run anything you want in the target process. From within your DllMain, use ::LoadLibraryA() to get the HMODULE of the library containing the API you want to hook (e.g. "user32.dll") and pass it to ::GetProcAddress() together with the name of the API you want to hook (e.g. "MessageBeep") to get the address of the API itself. Eventaully give yourself privileges to write to that address' page, and overwrite the beginning of the API with a jmp instruction jumping into your detour (i.e. into your "version" of the API to hook). Note that your detour needs to have the same signature and calling convention (usually _cdecl) as the API you want to hook, or else monsters will be awakened.
As described here, this technique is somewhat destructive: you can't call back into the original API from the detour, as the original API has been modified to jump into yours and you'll end up with a very tight and nice infinite loop. There are many different techniques that would allow you to preserve and/or call back into the original API, one of which is hooking the ...A() versions of the API and then calling into the ...W() versions (most if not all of the ...A() Windows API's convert ASCII strings into UNICODE strings and end up calling into their ...W() counterparts).
No need to spend time on a custom program to do this.
You can mute a particular application when it's running, and that setting will be remembered the next time you open the application. See https://superuser.com/questions/37281/how-to-disable-sound-of-certain-applications.
There's also the Windows Sound Sentry that will turn off most system sounds, although I'm not aware of any per-application settings for Sound Sentry.
You can use Deviare API hook and solve the hook in a couple of C# lines. Or you can use EasyHook that is a bit more difficult and less stable.

Prevent McAfee Dlls injection

I have a process that doing some inline hooks on WinSock module (Send and Receive functions).
On a machine with McAfee I can see that two dlls are being injected into my process:
hipi.dll
hipqa.dll
Both are also doing probably inline hooking on those functions and I get collisions and unwanted behaviors. Is there an option to prevent/unload those dlls so they will not interfere?
10x,
Guy
There are many scenario to achieve DLL injection(Hooking), BTW, you must learn more about how stuff works behind every method, the most common one is by using CreateRemoteThread() API function, then you must to inject your security DLL on every process and hook/redirect/deny any call to CreateRemoteThread() or any "dangerous" API call.
PS: BUT keep in your mind:
user-mode hooking can NEVER be an option to apply additional security
checks in any safe manner. If you only want
to “sandbox” a dedicated process, you know well about, and the process in fact doesn’t know about
EasyHook, this might succeed! But don’t ever attempt to write any security software based on user
mode hooking. It won’t work, I promise you…
You have 2 options.
Add an exclusion for your process so that McAfee doesn't attempt to scan it. I don't use McAfee's products, but I would assume that this would be a relatively straightforward process.
Uninstall McAfee
The easiest solution is to just unhook the affected functions. I had to do the same to work around some Dell crapware. It's not excessively hard, even though it requires some understanding of x86 assembly. You have to disable DEP, make the patched code writeable, find the original instructions, and copy them back. Finding the original instructions probably means disassembling the patch.
Another alternative is simply to hook it at a different place. For example, hook the IAT instead and then when you are done with whatever you want, forward execution back to the real function where it will then go through McAfee's hook.
I've had to deal with something similar once. Read their own hook assembly stub, so you can figure out how to hook in a way you chain to their hook after yours.
I'd imagine that McAfee are performing DLL injection from kernel-mode. They are likely finding the address of the KeServiceDescriptorTable (exported by NTOSKRNL on 32-bit systems and the address to it is leaked on 64-bit environments by KiSystemServiceRepeat -> close to KiSystemCall64 found by the IA32_LSTAR Model Specific Register) and then locating NtCreateThreadEx from the service table, or they're using KeInitializeApc and KeInsertQueueApc (both exported by NTOSKRNL) for APC injection (custom NtQueueApcThread wrapper). That would be logical considering they are a security vendor with a lot of resources, I doubt they'd be injecting from user-mode.
The likelihood is they are abusing PsSetCreateProcessNotifyRoutineEx or PsSetLoadImageNotifyRoutineEx to detect new process creation. The first one is not as good as the latter, the latter is better for filtering of NTDLL.DLL since it is the first module loaded into every single process, and signifies the process has actually started up properly and is just about ready to execute its own code (after the Windows module loads, and because McAfee will need to wait for Win32 modules like kernel32.dll to be loaded otherwise they'll crash the process if they use the Win32 API at all in their injected modules).
You can try intercepting LdrInitializeThunk or KiUserApcDispatcher, but honestly, there's not much you can do. McAfee will find a way to inject into your process no matter what you do, because they have control from kernel-mode. If you develop process protection via a variety of kernel-mode callbacks from a driver, they'll bypass it using non-exported routines located via pattern match scanning of ntoskrnl.exe, or exported routines which don't invoke the callback notification APIs. If you locally patch routines invoked for thread creation/APC locally in your own process when performed by a remote attacker, they'll find ways to prevent this and bypass it (e.g. patch the patched routines in the address space of your process back to the original, inject, then re-patch the bytes back).
You're playing with fire if you want to stop security software with the privileges McAfee has. It is similar to how Anti-Cheat cannot stop game hackers who have kernel-mode access, and go do drastic measures of even flagging Debug Mode/Test Mode enabled nowadays.

Catch Registry request C++

I known such tools
http://portableapps.com/development/projects/registry_rapper
RegRap.exe can get through param other .exe file and catch requests to registry and save it into .ini
That is good, but I need snippt code to set such hundler inside my C++ program and for given Reg KEY return my value...
RegRap.exe written with NSIS scripts that is why is not helpful for me :(
But may be somebody known other project only with c++?
Thx, and sorry for my bad english.
If you want to track registry access within YOUR program, you can #define away the registry API functions, provide your hooks instead, and track it in your hooks.
//in your stdafx.h, or some other universally included file
#define RegCreateKeyEx MyRegCreateKeyEx
//somewhere else
#undef RegCreateKeyEx
LONG WINAPI MyRegCreateKeyEx(stuff...)
{
//Track
//Call the real RegCreateKeyEx
}
That's probably the easiest way of hooking an API. Will not work if you want to track registry usage by your program but outside of your code (i. e. in libraries or DLLs). Then more advanced techniques are in order.
Also, consider Process Monitor by Mark Russinovich: http://technet.microsoft.com/en-us/sysinternals/bb896645
It's not a programmatic hook, but an awesome tool all around, and therefore worth plugging. It monitors registry access by your process(es) and then some.
This post seems to say that there are no hooks for the registry and you can only long poll. Simple way to hook registry access for specific process
If you want to use pure C++, check out the libraries EasyHook and Detours. Both are intended for this sort of function-level hooking. EasyHook works in C++ and C#, 32 and 64-bit, while Detours is somewhat outdated and only for 32-bit C++ (even running it on a 64-bit OS can crash your program).
You need to install the hook within the target process, either by loading your code as a DLL or creating the process (suspended), installing the hooks and then running it.
In EasyHook that goes something like:
LhInstallHook(&RegCreateKeyEx, &MyRegCreateKeyEx, &hookstruct);
You can also hook functions your library is not linked to using the Windows API to get the address.

OpenGL/D3D: How do I get a screen grab of a game running full screen in Windows?

Suppose I have an OpenGL game running full screen (Left 4 Dead 2). I'd like to programmatically get a screen grab of it and then write it to a video file.
I've tried GDI, D3D, and OpenGL methods (eg glReadPixels) and either receive a blank screen or flickering in the capture stream.
Any ideas?
For what it's worth, a canonical example of something similar to what I'm trying to achieve is Fraps.
There are a few approaches to this problem. Most of them are icky, and it totally depends on what kind of graphics API you want to target, and which functions the target application uses.
Most DirectX, GDI+ and OpenGL applications are double or tripple-buffered, so they all call:
void SwapBuffers(HDC hdc)
at some point. They also generate WM_PAINT messages in their message queue whenever the window should be drawn. This gives you two options.
You can install a global hook or thread-local hook into the target process and capture WM_PAINT messages. This allows you to copy the contents from the device context just before the painting happens. The process can be found by enumerating all the processes on the system and look for a known window name, or a known module handle.
You can inject code into the target process's local copy of SwapBuffers. On Linux this would be easy to do via the LD_PRELOAD environmental variable, or by calling ld-linux.so.2 explicitly, but there is no equivalient on Windows. Luckily there is a framework from Microsoft Research which can do this for you called Detours. You can find this here: link.
The demoscene group Farbrausch made a demo-capturing tool named kkapture which makes use of the Detours library. Their tool targets applications that require no user input however, so they basically run the demos at a fixed framerate by hooking into all the possible time functions, like timeGetTime(), GetTickCount() and QueryPerformanceCounter(). It's totally rad. A presentation written by ryg (I think?) regarding kkapture's internals can be found here. I think that's of interest to you.
For more information about Windows hooks, see here and here.
EDIT:
This idea intrigued me, so I used Detours to hook into OpenGL applications and mess with the graphics. Here is Quake 2 with green fog added:
Some more information about how Detours works, since I've used it first hand now:
Detours works on two levels. The actual hooking only works in the same process space as the target process. So Detours has a function for injecting a DLL into a process and force its DLLMain to run too, as well as functions that are supposed to be used in that DLL. When DLLMain is run, the DLL should call DetourAttach() to specify the functions to hook, as well as the "detour" function, which is the code you want to override with.
So it basically works like this:
You have a launcher application who's only task is to call DetourCreateProcessWithDll(). It works the same way as CreateProcessW, only with a few extra parameters. This injects a DLL into a process and calls its DllMain().
You implement a DLL that calls the Detour functions and sets up trampoline functions. That means calling DetourTransactionBegin(), DetourUpdateThread(), DetourAttach() followed by DetourTransactionEnd().
Use the launcher to inject the DLL you implemented into a process.
There are some caveats though. When DllMain is run, libraries that are imported later with LoadLibrary() aren't visible yet. So you can't necessarily set up everything during the DLL attachment event. A workaround is to keep track of all the functions that are overridden so far, and try to initialize the others inside these functions that you can already call. This way you will discover new functions as soon as LoadLibrary have mapped them into the memory space of the process. I'm not quite sure how well this would work for wglGetProcAddress though. (Perhaps someone else here has ideas regarding this?)
Some LoadLibrary() calls seem to fail. I tested with Quake 2, and DirectSound and the waveOut API failed to initalize for some reason. I'm still investigating this.
I found a sourceforge'd project called taksi:
http://taksi.sourceforge.net/
Taksi does not provide audio capture, though.
I've written screen grabbers in the past (DirectX7-9 era). I found good old DirectDraw worked remarkably well and would reliably grab bits of hardware-accelerated/video screen content which other methods (D3D, GDI, OpenGL) seemed to leave blank or scrambled. It was very fast too.

C++ hook process and show status

Ok so I am learning C++ slowly. I am familiar with all the console syntax and everything, but now I'm moving on to windows programming. Now what im trying to do, is create a DLL that I inject into a process, so it's hooked in. All I want the C++ application to do, is have text in it, that says "Hooked" if it's successfully injected, and an error if something wrong happened. Or even if I can do it without a DLL, Just open an executable, and when the certain process I'm trying to hook is opened, the status is changed to "Hooked". Also I have a safaribooksonline.com account so if there is any good reads you would recommend, just write it down. thanks
I think you might be looking at this backwards. In C/C++ an application 'pulls' a DLL in rather than having a DLL 'injected' into an application. Typically for plugins/hooks, there is some mechanism to inform an application of a DLL's availability (often just its presence in a specific directory) and a configuration file or some other logic is used to instruct the application to explicitly load the library, extract a function or two, and call them.
For Windows programming, I'd suggest doing a search for examples of the LoadLibrary() API call. You'll likely find a tutorial or two on how to do it.
If by "hooked" you mean, "have my DLL run in that processes' address space", you want CreateRemoteThread(). This is fairly advanced and difficult to debug, because your bugs make the other program crash. It's how a lot of malware works, by the way.
If you mean "have my DLL get notified of activity in the other process", you want SetWindowsHookEx().
Sounds like you want to inject as soon as the application starts? You can do that with Microsoft's Detours DetourCreateProcessWithDll(). Example here.