Hooking windows functions - windows

I am interested in hooking the function which return the content of a directory in Windows.
I have came across a tool called EasyHook, however I saw this in their page
Unlike what some (commercial) hooking libraries out there are advertising to boost sales, 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… This is also why EasyHook does not support a so called “System wide” injection, which in fact is just an illusion, because as I said, with user-mode hooks, this will always be impossible.
http://www.codeproject.com/Articles/27637/EasyHook-The-reinvention-of-Windows-API-hooking
I have asked in the forum there but it seems that no one knows there.
Why is this kind of hooking is not suitable for security analysis?
Basically, I would like to change the output of the function so it will return extra non existing files, such that every calling process will see this changes.
(This is done for security analysis).
Thanks,
Or.

Related

Windows: How to intercept Win32 disk I/O API

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!

Click Tracking Windows Applications

I'm interesting in gathering usage metrics for an application that I did not write and have no control over. This is a applicaiton running on Windows.
My plan for this is to register a global windows hook for mouse and keyboards events, and record those events for windows that have pre-determined titles or other identifable attributes.
Using this data, I hope to be able to determine how a user uses the application in question. What buttons they click and when, as well as common workflows. Etc.
Any thoughts on this idea? Are there 3rd party products or libraries that would facilitate this solutions that do not require modification of the existing application?
I assume (hope) this is for something like usability experimentation and not nefarious purposes.
The approach you outlined seems reasonable. The drawbacks of global hooking are:
It's a burden on every process, since your hook code will be injected into every process.
It can run into security barriers. For example, if you're hooking from a medium integrity level app, I don't think you'll be able to hook a high integrity level app. Also, you're essentially creating a keylogger, so don't be surprised if some anti-malware app flags you as possibly spyware.
You may need a 64-bit version and a 32-bit version.
One way to mitigate the impact you have on the machine is to use a more targeted hook: find the particular process you care about, enumerate its threads, and hook only those.
Spy++, a developer tool for tracking Windows messages, does much of what you want, but I'm not sure if you could leverage it for your purpose. I'm not aware of any other tools or frameworks for doing this kind of instrumentation.

minifilter vs. API Hooking for file system operations monitoring \ filtering

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.

Intercept BIG application execution after DLL injection

I must intercept execution in very big application in many places.
What programs I can use to do this? What techniques exists for this problems?
Manually reverse engineering and adding hooks is maybe not optimal solution for this problem, because application is very big and some part of application can be updated in some time, i think with some tools or good practices for this problem i can do this faster, anyone know how to do?
Anybody help me?
seeing as the tools part has been covered, here is something for the techniques.
Depending what it is you need to hook and whether or not there is protection invloved, there are a few methods:
Relative call/jmp patching in the virtualized binary: this is the simplest, but also a lot of work if you can't automatically find all references to a function, this probably won't work in this cause due to your criteria.
IAT/EAT hooking: this is use for imports(IAT) and exports(EAT), great if your targeting a known importted/exported set of API functions. a good example of this can be found here or here
Hot-Patching: Windows XP SP2 introduced something called "hot-patching" (used for realtime system function updates), where all its (the WinAPI) functions start with a 'mov edi,edi', allowing a relative jump to be patched into the free space created above every hot-patchable function(one can do it too). this is generally used for programs that checksum there IAT's or have other funny forms of protection, more info can be found here and here
Code-Caving: capturing execution flow by placing redirections in arbitrary code space. see here, here or here
VFT/COM Redirection: basically overwriting entries in a objects virtual function table, useful for OOP/COM based applications. see this
There are a lot of 3rd party libraries, most famous would probably be MS Detours, one can also look at APIHijack or a mini-hook engine.
Ofcourse nothing can substitute for the initial poking you'll need to do with a debugger like ollydbg, but knowing the method your gonna use can drastically short them amount time time spent poking around
Some details on what exactly you need to do (e.g. how do you determine where to break) would be nice. Depending on your situation, something like Pin might work.
I suggest using Deviare API Hook. It's the easiest way you can do what you need. It has some COM objects that you can use to hook an application from a different process. In your process you get full parameter information and you can use it in any programming language (I'm using C# and it works like a charm).
If you need to intercept registry API I suggest using Deviare to debug what you need to intercept but then you will have to make your own hooks, otherwise, you'll find performance issues.
You can do API Hooking if you are interested in intercepting method calls.
Or use some disassembler like softice or ollydbg or win32dasm.

How to consistently organize code for debugging?

When working in a big project that requires debugging (like every project) you realize how much people love "printf" before the IDE's built-in debugger. By this I mean
Sometimes you need to render variable values to screen (specially for interactive debugging).
Sometimes to log them in a file
Sometimes you have to change the visibility (make them public) just to another class to access it (a logger or a renderer for example).
Some other times you need to save the previous value in a member just to contrast it with the new during debugging
...
When a project gets huge with a lot of people working on it, all this debugging-specific code can get messy and hard to differentiate from normal code. This can be crazy for those who have to update/change someone else's code or to prepare it for a release.
How do you solve this?
It is always good to have naming standards and I guess that debug-coding standards should be quite useful (like marking every debug-variable with a _DBG sufix). But I also guess naming is just not enough. Maybe centralizing it into a friendly tracker class, or creating a robust base of macros in order to erase it all for the release. I don't know.
What design techniques, patterns and standards would you embrace if you are asked to write a debug-coding document for all others in the project to follow?
I am not talking about tools, libraries or IDE-specific commands, but for OO design decisions.
Thanks.
Don't commit debugging code, just debuggin tools.
Loggin OTOH has a natural place in execption handling routines and such. Also a few well placed logging statments in a few commonly used APIs can be good for debugging.
Like one log statment to log all SQL executed from the system.
My vote would be with what you described as a friendly tracker class. This class would keep all of that centralized, and potentially even allow you to change debug/logging strategies dynamically.
I would avoid things like Macros simply because that's a compiler trick, and not true OO. By abstracting the concept of debug/logging, you have the opportunity to do lots of things with it including making it a no-op if needed.
Logging or debugging? I believe that well-designed and properly unit-tested application should not need to be permanently instrumented for debugging. Logging on the other hand can be very useful, both in finding bugs and auditing program actions. Rather than cover a lot of information that you can get elsewhere, I would point you at logging.apache.org for either concrete implementations that you can use or a template for a reasonable design of a logging infrastructure.
I think it's particularly important to avoid using System.outs / printfs directly and instead use (even a custom) logging class. That at least gives you a centralized kill-switch for all the loggings (minus the call costs in Java).
It is also useful to have that log class have info/warn/error/caveat, etc.
I would be careful about error levels, user ids, metadata, etc. since people don't always add them.
Also, one of the most common problems that I've seen is that people put temporary printfs in the code as they debug something, and then forget where they put them. I use a tool that tracks everything that I do so I can quickly identify all my recent edits since an abstract checkpoint and delete them. In most cases, however, you may want to pose special rules on debug code that can be checked into your source control.
In VB6 you've got
Debug.Print
which sends output to a window in the IDE. It's bearable for small projects. VB6 also has
#If <some var set in the project properties>
'debugging code
#End If
I have a logging class which I declare at the top with
Dim Trc as Std.Traces
and use in various places (often inside #If/#End If blocks)
Trc.Tracing = True
Trc.Tracefile = "c:\temp\app.log"
Trc.Trace 'with no argument stores date stamp
Trc.Trace "Var=" & var
Yes it does get messy, and yes I wish there was a better way.
We routinely are beginning to use a static class that we write trace messages to. It is very basic and still requires a call from the executing method, but it serves our purpose.
In the .NET world, there is already a fair amount of built in trace information available, so we do not need to worry about which methods are called or what the execution time is. These are more for specific events which occur in the execution of the code.
If your language does not support, through its tracing constructs, categorization of messages, it should be something that you add to your tracing code. Something to the effect that will identify different levels of importance and/or functional areas is a great start.
Just avoid instrumenting your code by modifying it. Learn to use a debugger. Make logging and error handling easy. Have a look at Aspect Oriented Programming
Debugging/Logging code can indeed be intrusive. In our C++ projects, we wrap common debug/log code in macros - very much like asserts. I often find that logging is most usefull in the lower level components so it doesn't have to go everywhere.
There is a lot in the other answers to both agree and disagree with :) Having debug/logging code can be a very valuable tool for troubleshooting problems. In Windows, there are many techniques - the two major ones are:
Extensive use of checked (DBG) build asserts and lots of testing on DBG builds.
the use of ETW in what we call 'fre' or 'retail' builds.
Checked builds (what most ohter call DEBUG builds) are very helpfull for us as well. We run all our tests on both 'fre' and 'chk' builds (on x86 and AMD64 as well, all serever stuff runs on Itanium too...). Some people even self host (dogfood) on checked builds. This does two things
Finds lots of bugs that woldn't be found otherwise.
Quickly elimintes noisy or unnessary asserts.
In Windows, we use Event Tracing for Windows (ETW) extensively. ETW is an efficient static logging mechanism. The NT kernel and many components are very well instrumented. ETW has a lot of advantages:
Any ETW event provider can be dynamically enabled/disabled at run time - no rebooting or process restarts required. Most ETW providers provide granular control over individual events, or groups of events.
Events from any provider (most importantly the kernel) can be merged into a single trace so all events can be correlated.
A merged trace can be copied off the box and fully processed - with symbols.
The NT kernel sample pofile interrupt can generate an ETW event - this yeilds a very light weight sample profiler that can be used any time
On Vista and Windows Server 2008, logging an event is lock free and fully multi-core aware - a thread on each processor can independently log events with no synchronization needed between them.
This is hugly valuable for us, and can be for your Windows code as well - ETW is usuable by any component - including user mode, drivers and other kernel components.
One thing we often do is write a streaming ETW consumer. Instead of putting printfs in the code, I just put ETW events at intersting places. When my componetn is running, I can then just run my ETW watcher at any time - the watcher receivs the events and displays them, conts them, or does other interesting things with them.
I very much respectfully disagree with tvanfosson. Even the best code can benefit from well implemented logging. Well implimented static run-time logging can make finding many problems straight forward - without it, you have zero visiblilty into what is happening in your component. You can look at inputs, outputs and guess -that's about it.
They key here is the term 'well implimented'. Instrumentation must be in the right place. Like any thing else, this requries some thought and planning. If it is not in helpfull/intersting places, then it will not help you find problems in a a development, testing, or deployed scenario. You can also have too much instrumeation causing perf problems when it is on - or even off!
Of course, different software products or componetns will have different needs. Some things may need very little instrumenation. But a widely depolyed or critical component can greatly benefit from weill egineered instrumeantion.
Here is a scenario for you (note, this very well may not apply to you...:) ). Lets say you have a line-of-business app deployed on every desktop in your company - hundreds or thousands of users. What do you do when someone has a pbolem? Do yo stop by their office and hookup a debugger? If so, how do you know what version they have? Where do you get the right symbols? How do you get the debuger on their system? What if it only happens once every few hours or days? Are you going to let the system run with the debugger connected all that time?
As you can imagine - hooking up debugger in this scenario is disruptive.
If your component is instrumented with ETW, then you could ask your user to simply turn on tracing; continue to do his/her work; then hit the "WTF" button when the problem happens. Even better: your app may have be able to self log - detecting problems at run time and turning on logging auto-magicaly. It could even send you ETW files when problems occured.
These are just simple exmples - logging can be handled many different ways. My key recomendation here is to think about how loging might be able to help you find, debug, and fix problems in your componetns at dev time, test time, and after they are deployed.
I was burnt by the same issue in about every project I've been involved with, so now I have this habit that involves extensive use of logging libraries (whatever the language/platform provides) from the start. Any Log4X port is fine for me.
Building yourself some proper debug tools can be extremely valuable. For example in a 3D environment, you might have an option to display the octree, or to render planned AI paths, or to draw waypoints that are normally invisible. You'd probably also want some on-screen display to aid with profiling too: the current framerate, count of polygons on screen, texture memory usage, and so on.
Although this takes some time and effort to do, in the long run it can save you a lot of time and frustration.

Resources