I want to hook certain API calls, e.g. CreateFile (or NtCreateFile if I hook ntdll.dll), but there are some issues.
I can use several methods to achieve this goal, e.g. DLL injection, Inline hooking etc. But I think the most pragmatic way would be to use Microsoft Detours, as it handles some functions, e.g. trampolines, for me. However, the issue is that I don't know which processes I want to hook beforehand, so my custom DLL should be loaded into the virtual address space of the process, when the path of the DLL is set to Kernel32.dll or when it specifically calls for the functions CreateFile, ReadFile etc.
However, since this is in the context of ransomware detection, I don't know which processes will invoke these API calls.. so actually I want to have a system-wide hook. I read articles etc. about this topic, and one of the approaches is to change the registry entries, but then it will only work for proceses that use user32.dll, have a GUI etc.
Can I anyone advise me on this case? Thank you in advance.
EDIT: I did some additional research. I think inline hooking makes the most sense. But unfortunately I can't use Detours for that, as this paper states (page 7), which I find a little bit strange because I would think that inline hooking is by definition system-wide (as each process that wants to use the function CreateFile from Kernel32.dll invokes the real DLL).
Related
I want to hook every call to CreateProcess (and a few other related APIs), no matter the process. Can modern Detours be used to do this without enumerating all processes and performing injections?
I've read several articles on both API hooking and doing so specifically with Detours, re:
API Hooking with MS Detours
API Hooking with MS Detours (InfoSec Institute)
API Hooking Revealed
I have two problems with these articles:
They are quite old and things may have changed.
They do not thoroughly address system-wide hooking using Detours specifically.
I am aware that this can be done with a driver, but Detours is said to be a powerful tool, and is still currently supported, so I wanted to know how it could be done with Detours.
The literature I've read thus far is geared toward targeting a specific program using Detours, and although it has presented an idea of how it's possible to enumerate every process and perform a DLL injection and then try to use Detours, this seems like a very unreliable way.
NO
Detours cannot be used globally without per-process injection.
However, you only need to enumerate processes manually once, when you want to set an initial hook after the system is already running. One option (if you are careful with it) is to use the AppInit_DLLs Registry setting to have your DLL loaded into new processes (well, at least processes that use user32.dll, and that don't opt-out of letting AppInit_DLLs run, and providing that AppInit_DLLs is even enabled on the system to begin with).
Otherwise, the alternative is to write a kernel driver that implements a process creation callback that is registered via PsSetCreateProcessNotifyRoutine(). That callback will be called every time a process is created or destroyed.
On Windows, all disk I/O ultimately happens via Win32 API calls like CreateFile, SetFilePointer, etc.
Now, is it possible to intercept these disk I/O Win32 calls and hook in your own code, at run time, for all dynamically-linked Windows applications? That is, applications that get their CreateFile functionality via a Windows DLL instead of a static, C library.
Some constraints that I have are:
No source code: I won't have the source code for the processes I'd like to intercept.
Thread safety: My hook code may dynamically allocate its own memory. Further, because this memory is going to be shared with multiple intercepted processes (and their threads), I'd like to be able to serialize access to it.
Conditional delegation and overriding : In my hook code, I would like to be able to decide whether to delegate to the original Win32 API functionality, or to use my own functionality, or both. (Much like the optional invocation of the super class method in the overriding method of the subclass in C++ or Java.)
Regular user-space code: I want to be able to accomplish the above without having to write any device-driver, mainly due to the complexity involved in writing one.
If this is possible, I'd appreciate some pointers. Source code is not necessary, but is always welcome!
You may want to look into mhook if Detours isn't what you want.
Here are a couple of problems you may run into while working with hooks:
ASLR can prevent injected code from intercepting the intended calls.
If your hooks are global (using AppInit_DLLs for example), only Kernel32.dll and User32.dll are available when your DLL is loaded. If you want to target functions outside of those modules, you'll need to manually make sure they're available.
I suggest you start with Microsoft Detours. It's free edition also exists and its rather powerful stable as well. For injections you will have to find which injection method will work for your applications in target. Not sure whether you need to code those on your own or not, but a simple tool like "Extreme Injector" would serve you well for testing your approaches. And you definitely do not need any kernel-land drivers to be developed for such a simple task, in my opinion at least. In order to get the full help of me and others, I'd like to see your approach first or list more constraints to the problem at hand or where have you started so far, but had problems. This narrows down a lot chit-chats and can save your time as well.
Now, if you are not familiar with Detours from Microsoft (MSFT) please go ahead and download it from the following link: http://research.microsoft.com/en-us/projects/detours/ once you download it. You are required to compile it yourself. It's very straightforward and it comes with a compiled HTML help file and samples. So far your profiles falls under IAT (Import Address Table) and EAT (Export Address Table).
I hope this non-snippet answer helps you a little bit in your approach to the solution, and if you get stuck come back again and ask. Best of luck!
I'm trying to develop an anti-cheating system. The system will work by identifying applications which make use of the various keyboard/mouse entry APIs such as SendInput, keybd_event, mouse_event and SetKeyboardState in Windows. All applications are to be compared against a database of applications which are allowed by the system to make calls to those functions.
To do this, I need to know if there's any way I can monitor calls to certain WinAPI functions.
I would also need to monitor calls to SetWindowsHookEx.
Both keybd_event and mouse_event use SendInput under the covers. Although it is possible for you to inject a usermode DLL to all processes and hook these APIs, this is not the way that most anti-cheat systems work because it is easily subverted (e.g. through the use of a trampoline).
Typically, anti-cheat programs wishing to monitor/detour these APIs do so further down. For example, they would hook the NtSendUserInput system call. GameGuard is an example of a system that hooks both SendInput and NtSendUserInput.
The first thing you have to realise when coding your anti-cheat system is that you might as well assume that your code can easily be subverted or manipulated by an attacker. You speak of comparing against a database of applications. Perhaps you intend to do so by file path, which you get through GetProcessImageFileName. Then you need to think about how you are going to stop an attacker injecting a DLL to hook your call to that API or maybe even load a driver that hooks further down.
The back and forth game of cheating vs anti-cheating is endless and constantly changing (updating code signatures, cheaters recompile with different heuristics, you hook usermode, they trampoline, you hook kernelmode, they load driver to trampoline, etc.) and if you are asking questions like this, chances are you are better suited to purchasing a solution than attempting to roll your own.
I want to unload a DLL from another process. Is it possible?
If yes, how to do that? (I'm using Win32 API)
Thank you very much.
Yes, this is possible. It is called DLL ejection and is featured by some DLL injectors. The way a DLL is usually loaded is via LoadLibrary and it is subsequently unloaded via FreeLibrary. FreeLibrary takes only one parameter which is a handle to the module to be unloaded. If you injected the DLL in the first place, you should be able to find this very easily. Otherwise there are ways of obtaining the handle such as CreateToolHelp32Snapshot with further enumeration with Module32First/Module32Next. Suppose you have obtained the handle through some means, then the steps to eject the DLL are simple:
Get the address of FreeLibrary with GetProcAddress. This address will match the one for the same function in the target because of how Windows works.
Call CreateRemoteThread on the target process, specifying lpStartAddress as the address of FreeLibrary, and with lpParameter as the module's handle
There are several caveats to DLL ejection.
You should only ever eject a DLL which you are certain no code is going to make use of again in the future. If any dynamically linked code attempts to make a call to your code after it has been freed, it will most likely trigger some form of page access violation.
You should ensure that no threads are executing within the code of the DLL whilst ejection is being performed for similar reasons.
DLL ejection should be avoided with general. If the library wants to have the option of being freed, it should supply some interface which users can access it through which eventually calls FreeLibraryAndExitThread.
If you require a code example for this, I have written an ejector as part of an injector I wrote in the past in C. I can search it up and find it but it's from many years ago and the code quality is not likely to be good.
You don't want to do this.
"Loading" a DLL is much more than simply opening (and locking) a file. When the NT loader starts an executable, it processes all the DLLs referenced by the image (recursively) and wires up the function calls (recursively): loading the DLLs, calling the DLL initialization code, etc.
Unloading a DLL would mean that you'd need to stop all processes that loaded your DLL, load the new DLL, and perform all the operations the NT loader would. Of course, unloading and re-loading a DLL would need to restore that old DLL's state (initialized variables etc), an operation which is not specified in Win32.
For a bit of background information, see this article on MSDN and this Under the Hood article in MSJ.
Short answer: No, it is impossible.
Win32 doesn't provide an API to unload a DLL of another process. If a library is freed unexpectedly, the process will crash. This leads to a serious security hole as it breaks process protection mechanism.
If you can modify both of the processes, you can modify the application and add routines to free a library, and let the other application to send the message.
I would instead look to change the function called when the process tries to invoke the functions in that dll. I know this is possible in theory.
It would mean a bit of memory hacking and knowing where the pointers to the functions are stored, but all of that can be found easily enough (ollydbg manages to do it), it would be harder if they use ordinals, even harder if they hard code the pointers, but no one does that nowadays. You could then inject your own code that (ideally) mimics the functions they mask, but does not actually do anything. They will probably have to be injected into the process, and that way you could get it to work without the process ever knowing, and without any crashes.
I need to develop an application that monitors, and potentially filters (rejects the calls), file operations.
It appears that developing a minifilter is the "standard" solution.
another potential method is using API hooks.
are these relevant solutions? (I read in some places the an API hook may not be suitable - but no explanation was given)
are there other options?
API hooking (at least in kernel space) is essentially not supported by microsoft. On x64 (starting from Vista and up) patchguard will usually kill the machine if it detects SSDT hooking or any change whatsoever in critical components of the system. API hooking is very hard to get on a system-wide level because the synchronization primitives that windows uses are not exported so even if you manage to hook the code there is not guarantee that the machine won't crash due to a funky value of EIP at a given moment (this is especially valid when you are unloading a driver that has hooked a function).
Probably your best bet to do it - without using minifilter driver is to try and to direct memory kernel object hooking. You might want to look at OBJECT_TYPE_INITIALIZER definition structure which every object windows has (FILE, EVENT, PORT etc - google around to see them) has as its member. You are particularly interested in the *Procedure function pointers.
It all comes down to what you want/need to accomplish.
If you just need file operations (in the kernel level, file open / file close), and you need it system-wide than I would go with minifilter. It is a long, tedious and time-consuming road, but safer (check out Sysinternals procmon to see what you can get using this method).
If you need a more application-specific control, or if you would like control over the WINAPI level, go with API hooking. It is easier to develop, but there are lots of "mines" that blow up in your face during the way (check out EasyHook, its doing a pretty good job with minimum work).
good luck!
If you are preventing user access to certain resources (files) from a security perspective the correct way is a minifilter. This is because it's the only way you are sure that the user cannot access the filtered resources.
If you use API hook you can intercept calls at kernel32.dll (CreateFileW, FindFirstFile, etc., etc.) but an attacker can uses Native API (ntdll.dl). Of course, you can intercept at Native level (it's more difficult since it's undocumented) but attackers can use differents APIs at kernel switch level. At that level it's not portable to hook. It's almost impossible to prevent creative attackers to access to resources using API hook, that's why it's not recommended for security software.
In my opinion, API hooking is a good option for monitoring. If you want to see what an application is doing, it's very good to use API hook since you can intercept higher level functions than in kernel-mode.
If you can accomplish the task without the hooks - do it. Because hooking is not a supported way of developing applications. There is a lot of pitfalls and antivirus software will treat your application as more dangerous. Also you may face problems with newer/older versions of operating system.
But take into consideration that user-mode code is much easier then kernel-mode. So if user-mode hooks can satisfy your requirements then you may think about them.
I got a follow up question by mail, so i'm adding here the solution we used
The project was canceled before it wen't live, but we evaluated a product (Eldos CallbackFilter) that allows writing kernel filters using user space code.
The product has a generic kernel driver that communicates with user space code that defines the filtering logic.
I would have to contradict LordDoskias as, OBJECT_TYPE_INITIALIZER is not a documented object and this can, has and will change with OS patches and updates.
Do not approach this problem this was as it will only cause more problems and not solve anything.
Not to mention the patch guard which will BSOD the system if you modify system structures.
If you want to restrict access to files there is no way around it than simply using a minifilter. There are several Microsoft samples here that you can draw inspiration from and also learn to implement your driver the correct and supported way.
Lastly and more importantly it is illusory to think that you will be able to block everything you want by hooking techniques and I will just give you one example: mapped files.
Here is a scenario involving notepad which uses mapped files to write it's data to disk.
CreateFile -> obtains file handle -> you see this
CreateFileMapping -> obtains mapping handle -> you don't see this
CloseHandle(FileHandle) -> you see this
MapViewOfFile returning a memory buffer being page backed by the file -> you don't see this
Modify the memory buffer -> you don't see this
Unmap and close the FileMappingHandle -> you don't see this
Async the memory manager's system worker threads make paging writes to the file to keep it in sync. Even after all the handles have been closed or during the in-memory change of the buffer, depending when the OS wants. -> you don't see this
This is what you are missing with hooking. And this is just one scenario. There is a multitude of them, so please do things the right way.
How would that change if you use a minifilter ?
You would of course catch the CreateFile, CreateFileMapping as well ( check FltAcquireForSectionSynchronization callback) and then from the minifilter you will see all the PAGING_WRITE coming from the memory manager (see IoGetTopLevelIrp()) in your Write dispatch callback.
Good luck further.