Prevent McAfee Dlls injection - c++

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.

Related

Require specific event completion before application launch

I'm working on an application (DLL) that logs specific WIN32 calls using Detours. It is injected into a target application that passes the filter. It has to absolutely log every call that the application makes, starting from the first instruction in the application's entry point.
I now am looking for a way to make my application (the one that always runs) inject the DLL as fast as possible, preferably without the target application making any other calls.
Is there any way to achieve this?
You could use the AppInit_DLLs registry key to load a dll into a process. The dll is loaded during DLL_PROCESS_ATTACH of User32.dll. For regular applications this should happen prior to running any application code.
Keep in mind though that AppInit_DLLs should be renamed Deadlock_Or_Crash_Randomly_DLLs.
As far as I know, there's no straightforward way of doing this in Windows.
Your options are:
Hooking the CreateProcess (or lower) function in all processes. When a new process is created, change the arguments to create it as suspended, inject, and resume if needed.
Using a driver.

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.

Should I write my own crash dump via separate process or rely on WER?

At the moment my info is (and let's keep the context to Windows-7, as WER doesn't work like that on Win-XP) that I have two ways of getting a full memory crash dump for my application:
I can set up WER to generate a local full memory dump of my application
The info is here: http://msdn.microsoft.com/en-us/library/bb787181%28v=vs.85%29.aspx
Add (also for 32bit apps. Do not use SysWow64 node) HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps key (possibly app specific subkey ...LocalDumps\MyApplication.exe)
Set DumpType to 2.
Tweak other settings as neccessary
Note: As our application is custom deployed, setting this registry value isn't a problem.
This seems to give me pretty reliable crash dumps with a simple demo app.
Or, I can rig up the dump writing myself - properly with watchdog process and all
I use MiniDumpWriteDump to write the dump and I do this from a watchdog process (as described here, here) to minimize risk of failure.
Question
So, which is the better approach? Given that, when doing it myself, I prudently keep the stuff I do in the crash handler to an absolute minimum, I'm wondering whether the WER approach is as reliable, or whether the WER approach does some more things in-process that
may fail. Any ideas/experiences?
As alternative to doing it yourself, you might look into Google Breakpad, wich is a library and toolset for generating and handling crashdumps.

Deviarev2 Hook API: Hook into existing process winapi calls?

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

Hiding a file from other programs

I need to make a file not appear to another program. For instance, when another program gets the list of files in a folder, I want one particular one not to show up. I am injecting a DLL from which my code will run into the process from which I want to hide the DLL file on the filesystem. I am using Microsoft Visual C++ 2010 and Windows 7.
Yes, as you've mentioned you need to intercept the file/folder enumeration APIs and filter out the specific file/folder from the enumeration result in order to "hide" that file/folder. This can be done either at user mode or kernel mode.
User mode: User mode hooking involves DLL injection. There are many places where you can hook:
IAT hooking of executables: Find out the entry FindXxx in import address table of the target process and overwrite it with the address of trampoline function present in injected DLL.
EAT hooking of DLLs loaded by executables: Find out the entry of FindXxx APIs in export address table of loaded DLL (kernel32.dll in this case) and overwrite it with the address of trampoline function present in injected DLL.
Inline hooking: Overwriting first few instructions of an API code in a loaded DLL with a JMP to your trampoline function.
Generally, user mode tend to become "ugly" (difficult to manage) as you need inject your DLL into all of the running processes if you want a system-wide hook (or at least into Explorer.exe or your target application). Many applications, like security software, have protection mechanisms to detect and deny DLL injection.
A cleaner way to implement user mode hooking is to hook APIs in NTDLL.dll (using either EAT or inline hook). All other APIs (like FindFirstFile/FindNextFile) end up calling an equivalent NtXxx APIs (like NtQueryDirectoryFile) provided by NTDLL.dll. The NtXxx API is the point where control jumps to kernel mode by executing INT 2E/SYSENTER.
Kernel mode: This involves writing a driver. Again, in kernel mode there are many places where you can install hook:
SSDT hook: Install an SSDT hook for the required ZwXxx API (ZwQueryDirectoryFile in this case) by overwriting the corresponding SSDT index with the address of trampoline function in your driver.
Kernel inline hook: Overwrite the first few instructions of NT kernel API exported by kernel (NtQueryDirectoryFile in this case) with a JMP to point to trampoline function in your driver.
File system filter driver: This is a cleaner approach and no hooks are involved. Install a file system filter driver and intercept read/write/enumerate IOCTLs and filter out the results to hide/lock a specific file/folder.
Kernel mode hook tend to be cleaner as they generally installed at one "centralized place". However, you should be very careful as a small mistake/mishandling in driver code can end up with a BSOD.
PS: There are many hooking library/frameworks available to ease the job of writing code. Some popular ones are:
http://www.madshi.net/madCodeHookDescription.htm
http://easyhook.codeplex.com/
PPS: Hiding files/folders using such techniques without user's consent might be a questionable action and can become problematic (Remember Sony DRM protection software issue? ;) ). This is what rootkits do! There are many user mode and kernel mode rootkits that use the techniques mentioned above to hide files/folders. There are various anti-rootkit software available to detect and restore all sorts of hooking described above. Many anti-virus software raise a flag when they detect such rootkit like behavior (like API hooking, hidden files, SSDT hooks etc.)
Few resources:
http://www.codeproject.com/KB/threads/APIHooking.aspx
http://www.codeproject.com/KB/DLL/funapihook.aspx
http://www.codeproject.com/KB/system/api_spying_hack.aspx
http://www.codeproject.com/KB/system/hide-driver.aspx
http://www.uc-forum.com/forum/c-and-c/59147-writing-drivers-perform-kernel-level-ssdt-hooking.html
http://www.security.org.sg/code/apihookcheck.html
Easiest way to do that would be using Microsoft Detours to override the functions you need. It can also be used to inject the DLL, but you already have that covered. If there's a specific function used by the other process that is known to you, hook on that. If not, you'll need to hook on the building blocks of all functions used to list files or open them. Hooking just CreateFile/FindFirst/FindFirstFile/etc would be enough as they just call an internal function. For example, if you hook CreateFile which actually maps to CreateFileA, the process will still be able to access the file using CreateFileW. So you want to hook NtCreateFile and friends. But I guess you know which process you're messing with, so you know exactly which functions to mess with too.