C++ hook process and show status - c++

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.

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.

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.

How to hook C++ in Explorer's rename event

I can't be clearer than my title. :P
I want to run my program whenever a user renames a file in Windows Explorer (and only within the Explorer). Here's a simple mock up:
A simple link to a tutorial will be very helpful. I couldn't find anything. :/
Thank you in advance.
P.S. I'm new in C++
It looks like Windows API hooking may be your best bet. You'll want to intercept all calls related to Windows file renaming (i.e. MoveFile, MoveFileEx, SHFileOperation, possibly more). There are a few commercial and open source solutions; Microsoft Detours, Madshi's madCodeHook, and the free, open source EasyHook.
This approach, when done correctly, will allow you to capture all file renaming on a system.
I would avoid hooking APIs as much as possible. It gets really ugly really fast.
There are 2 ways I see that you can approach this.
Both ways have a few common factors:
The ReadDirectoryChangesW API. For a very good implementation of that API, see this
article
You will need to minimize your dependencies, so... Use a Microsoft compiler, link to the DLL runtime, stick to C as much as possible etc. This reduces problems. Loading things into the shell memory space is already problematic enough.
Method one is to use ReadDirectoryChangesW from an Explorer shell extension that does nothing else. Keep it minimal. I'm reasonably sure I saw a "do nothing" shell extension as an example in some of Microsoft's documentation.
Method two would be to package your code as a DLL and use a system hook to get your DLL loaded into Explorer only. The system hook should only load inside Explorer to prevent spurious notifications via ReadDirectoryChangesW.
Hope this helps and that you're not using it for something Evil.

How can I update an in-use COM DLL?

One part of some software I have written is a COM dll.
Other software uses this COM dll.
My software has an update function where it will download a newer version of the dll, but the update will fail if the dll is in use because the file cannot be deleted or written to.
The question is, how can I update a COM dll that is in use?
I have considered popping up a message asking the user to close any applications that are using the DLL if it is in use, if this is the best solution how would I go about detecting if the COM dll was in use before popping up the message?
Thanks in advance.
You cannot update it in place for existing applications, but one way to do this would be to save it with a different file name or different folder and call DllRegisterServer on the DLL to register it under the new name. New applications which begin using your object should now use the new version.
If this is just a matter of detecting whether you can replace the file then it is easy. Just try to open it with a share flag that denies reading. That's going to fail if the DLL is loaded in another process. Use _fsopen() or CreateFile(). Beware of the race condition.
Detecting which processes have the file loaded is a harder problem, CreateToolhelp32Snapshot() and Process32First/Next plus Module32First/Next to enumerate processes and the DLLs they have loaded. Still tough to generate a good diagnostic for the user, the process name isn't that helpful.
When you have downloaded the update, you must launch a third program (which you write) that does not have any dependancies on your COM component, or any other piece that is to be updated. This launcher, or bootstrapper, must shut down all your pieces, uninstall them, and install the update. When the update is installed you may then re-launch your application.
If you need also to download updates to the updater itself, your main program can do that.
Here is a simple solution for you. Create a wrapper DLL, which will be used by the other processes. Inside that DLL you explicitly load/unload your DLL, which is subject to updates. Of course you will have to suspend all callers when an update process kicks in.

How to test if a DLL can be loaded without an error

I have a native C++ application (no fancy .Net stuff just C++). However it uses some optional .Net assemblies through mixed mode wrapper dll files. These dlls are loaded using delay load. Thing with mixed mode wrappers is they need to be fully trusted in order to load. So when the application try to use the dll if it is not there or if it is not trusted entire thing crashes with a nasty error message.
But i my case as long as my main application is concerned it can live without these dll files. So I need a way to check if these dlls can be loaded (files are there and trusted). In order to do this I tried to put a dummy call to one of the dll functions within a try catch block hoping the catch the exception but it still crash with 'module not found' exception.
we also tried replacing unhanded exception filter with a custom one but still no luck.
we also tried to use LoadLibrary method to first load the dll and check the return value.
But that function load the Dll even if it is not trusted but crash when we try to do a method call.
I dont think that this is an unsolved problem. How hard can it be to check if a dll can be used without actually trying to load it and end up crashing? Any ideas?
If all methods fail, try running a separate process (i.e. simple command-line app) that will try to load the library, then analyze its return code.
But, did you try structured exceptions handling - i.e. __try/__catch, not try/catch? See here.
I had the idea of using a separate process to test the dll first and see if it runs in to any errors. I don't want to use that in my app cos it was not really a clan solution. but the __try, __except approach worked with delay load dll calls. I didn't even have to use LoadLibrary. Thanks.