Detect global Keyboard Hook in C3 - c#

It's incredibly easy to write Key-loggers in many languages. It makes me a little nervous because these small, unknown viruses won't get detected by most(read: all) antivirus'.
I'm curious how to detect if some process grabbing these keys. I want to know what process is reading my input at any given point. Kind of a Key-logger-logger.

several answers available on these questions
List of installed windows hooks
Detecting Keyboard Hooks
what are the methods to find hooked functions and apis

Related

Do something before an application starts

I've been looking for a way to do some stuff before an application starts and stop the started application and execute after "the stuff" is completed.
Like an Antivirus applications, when you open an application which may be dangerous or has no certification, it executes a scanning and only after that execution allow the application to starts.
Already tried with watchers and WMI (C#) but no success, since the calling event happens before the application starts and there is no way to cancel the opening.
If there is a name for that technique or someone knows an example code in C++ or C# or even any other language.
For those who are downvoting the question at least have the F** balls to explain why is downvoting...
It's a legitimate question! Maybe i miss explain it but still a legitimate question. Ohh I forgot, in many years of your career you already had to know everything... What would happen if you lost internet connection for three days? Are you still be productive? Maybe you guys had the API and documentation injected by Tank from Matrix... That's how NEO learn to fight.
Thanks
One option (which might be used by antiviruses, but not sure) is described here:
https://www.codeproject.com/Articles/11985/Hooking-the-native-API-and-controlling-process-cre
Basically, hooking the functions NtCreateFile(), NtOpenFile() or NtCreateSection() (the last one being mentioned as the preferred).
However, the hook must be done from inside a kernel mode driver, which might be a "slight inconvenience" (especially under 64-bit Windows, where the drivers must be signed AFAIK).
Some options also mentioned here: How does a Windows antivirus hook into the file access process?

How to make system calls counter using deviare

I would like to hook all the functions calls of all running processes. I can hook certain function("ws2_32.dll!recv") of all processes using deviare by:
CreateSpyMgr(out mgr);
hook = mgr.CreateHook("ws2_32.dll!recv");
hook.Attach(mgr.get_Processes(0));
mgr.set_ReportProcessCreation(DeviareCommonLib.ReportMethod._create_process_hook_and_polling, 0);
hook.set_HookNewProcesses(0, 1);
hook.OnFunctionCalled += new DHookEvents_OnFunctionCalledEventHandler(hook_OnFunctionCalled);
hook.Hook();
How can I hook all function calls instead of just one? is it possible?
Or should I create hooks collection(of all functions which is way hard) using INktSpyMgr::CreateHooksCollection and add hooks to it, then call hook method and pass the INktHooksEnum object as the parameter. Is this the only way to do this?
My aim is to make a tool that counts all system calls for each running process. Feel free to give any suggestions.
First a word of advice: be very very careful about which APIs you hook. If anything you do within your hook method results in a call to one of the APIs you are hooking then you are creating an infinite recursion that could potentially wreck your computer. Bear that in mind. You'll probably want to filter out the API calls for your own process as well, otherwise you'll end up logging entries about the disk access caused by logging entries, and before you know it your memory is full and the hard drive is fully occupied with logging about logging.
There appears to be nothing in the Deviare API that allows you to create hooks on multiple methods - no wildcards or 'hook everything' calls - so you'll have to enumerate the APIs (see INktModule.ExportedFunctions for some ideas) and hook them. I'd suggest that you use a hook collection (see INktSpyMgr.CreateHookCollection and INktHooksEnum) so that you can setup all your hooks and then attach and detach them in one operation.
As for the logging aspect, give some thought to using a queue of some sort - ConcurrentQueue<T> by preference - to pass the actual logging operations off to another thread. That way you spend a minimum of time in the actual hook function as well as reducing the chances of your hooks causing recursion. You'll have to experiment with filtering in the logging thread vs the hook functions to find out which has the smaller performance impact on the system.
Always make sure you know how much data your program is dealing with and have a plan in place for dealing with the volume of data. You're going to have to do some serious profiling to find the pain points, then put in plenty of work on reducing the overheads so that your program doesn't mess up the system too badly.
Personally I'd start with a small subset of the APIs you ultimately want to monitor, write code that works as well as you can make it, then move up to the full set of APIs. Less chance that you'll kill your computer that way.

SetWindowsHookEx global keyboard hook not catching all keypresses

I'm writing code that is part of an automation system. I wanted to add a keyboard hook to end the test prematurely, and I did this by using SetWindowHookEx.
My code looks pretty much like this: http://support.microsoft.com/kb/318804
Here's my SetWindowsHookEx call:
hHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProcedure, GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName), 0);
Now, when I run my automation, keypresses from within the automation system (from SendKeys) trigger the keyboard hook method, but when I hit the keyboard manually it isn't triggered.
I can share more code if that helps, but it's part of a much larger system. I'm pretty sure that either:
My SetWindowsHookEx isn't correct, or
Something in the automation system is bypassing my keyboard hook (I don't really know how to tell though).
I've written a test application that uses the sample code from microsoft.com to determine that my approach has merit (i.e., it works), but I'm having trouble integrating it with the automation system.
Any thoughts on how to determine where things are going wrong would be greatly appreciated.
Edit: There are no other instances of SetWindowsHookEx in the automation harness. I'm not too clear the nuances of global keyboard hooks w.r.t. threads and the desktop. If I add a global keyboard hook, should it matter from where it was added?
George Mamaladze's article Processing Global Mouse and Keyboard Hooks in C# which works if the application is "in the background" on CodeProject has been around since 2004, been through multiple revisions, and he's still supporting it and updating it : as I understand it, he started his project because he could not implement global hooks in .NET, that worked when the app was running in the background, but later discovered you could hook certain "lower level" events : formerly Q318804 : now MSDN article revised (?) that says you can hook WH_KEYBOARD_LL.
Perhaps, since George's code has been field-tested by so many C# programmers, over so many years, and extensively revised against bugs or problems : there's some possible value in his code for you ? In his article, in the Version 1 "FAQ" he shows code that will make the hook application specific, rather than global.
The MSDN article cited above mentions ... in the context of the allowed hooking of low level events, as you are doing :
"Low-level hook procedures are called
on the thread that installed the hook.
Low-level hooks do not require that
the hook procedure be implemented in a
DLL."
Hypothesis : could threading be related to what you are observing ?
I'm assuming you've already been through and considered all the details on : MSDN : LowLevelKeyboardProc Function
Responding to your comment -
If you just need to test whether a key is down in order to exit your test, you could just poll on GetAsyncKeyState(), this will tell you if a particular key is down regardless of who currently has keyboard focus.
You user would have to hold a key or set of keys down long enough for your polling to notice, which means either they hold it down for a few seconds, or you have to poll more frequently than a second.
But that would be a lot less intrusive than a global keyboard hook.
Global hooks supposedly serialize parts of the kernel that normally would be async from each other, so they also harm system performance.

Hide a C# program from the task manager?

Is there any way to hide a C# program from the Windows Task Manager?
EDIT:
Thanks for the overwhelming response! Well I didn't intend to do something spooky. Just wanted to win a bet with my friend that I can do it without him noticing. And I'm not a geek myself to be able to write a rootkit, as someone suggested though I'd love to know how to do it.
Not that I'm aware of - and there shouldn't be. The point of the task manager is to allow users to examine processes etc.
If the user should be able to do that, they should be able to find your program. If they shouldn't be poking around in Task Manager, group policy should prevent that - not your program.
Don't mean to zombie this but i thought i could contribute some useful information
If you want to hide a application there a two methods (that i can think of atm).
They both have their ups and downs
[1] SSDT Table hooking - basically you have to set the MDL of the table to writeable, overwrite the address of NtQuerySystemInformation (iirc) with the address of your function and have it call the original function after filtering the results.
This method doesn't suit your needs very well because the hooking function would always need to be in memory and would involve writing a kernel mode driver. Its a fun thing to do but debugging is a pain because an exception means a BSOD.
[2] Direct Kernel Object Manipulation (DKOM) - the list of processes is a doubly linked list, with a kernel mode driver you can alter the pointers of the records above and below your process to point around yours. This still requires the use of a kernel mode driver but there are rootkits such as FU that can be easily downloaded that contain an exe and the service. The exe could be called from inside your application as a child process (in the released version of FU, at least the one I found, there was a bug which I had to fix where if the hidden application exited the computer would BSOD, it was a trivial fix).
This will thankfully be caught by almost any decent antivirus so if you are trying to do something sneaky you'll have to learn to get around that (hint: they use a binary signature)
I have not used method 1 ever but method 2 has worked for me from a VB.Net application.
A third possible option is to just create the application as a windows service, this will show up in task manager by default but I'm willing to bet that there is a way to tell it to not show up there since there are plenty of other services which don't show up in task manager.
Hope I helped a little, my advice is that if you are interested in this kind of stuff to learn C++.
You could make your program a service and then it would appear as "svchost". There's a little more to it than that, but that should give you a hint to go in the right direction.
I'm not aware of any way to hide it from the task manager, but you could just disguise it by making it show up as "svchost.exe". It'll get lumped in with all the others (there's usually several), and will become indistinguishable.
You shouldn't hide it, but you could prevent the user from killing the process.
See Chris Smith's answer to this question.

Please help me with a program for virus detection using detection of malicious behavior

I know how antivirus detects viruses. I read few aticles:
How do antivirus programs detect viruses?
http://www.antivirusworld.com/articles/antivirus.php
http://www.agusblog.com/wordpress/what-is-a-virus-signature-are-they-still-used-3.htm
http://hooked-on-mnemonics.blogspot.com/2011/01/intro-to-creating-anti-virus-signatures.html
During this one month vacation I'm having. I want to learn & code a simple virus detection program:
So, there are 2-3 ways (from above articles):
Virus Dictionary : Searching for virus signatures
Detecting malicious behavior
I want to take the 2nd approach. I want to start off with simple things.
As a side note, recently I encountered a software named "ThreatFire" for this purpose. It does a pretty good job.
1st thing I don't understand is how can this program inter vent an execution of another between and prompt user about its action. Isnt it something like violation?
How does it scan's memory of other programs? A program is confined to only its virtual space right?
Is C# .NET correct for doing this kind of stuff?
Please post your ideas on how to go about it? Also mention some simple things that I could do.
This happens because the software in question likely has a special driver installed to allow it low level kernel access which allows it to intercept and deny various potentially malicious behavior.
By having the rights that many drivers do, this grants it the ability to scan another processes memory space.
No. C# needs a good chunk of the operating system already loaded. Drivers need to load first.
Learn about driver and kernel level programming. . . I've not done so, so I can't be of more help here.
I think system calls are the way to go, and a lot more doable than actually trying to scan multiple processes' memory spaces. While I'm not a low-level Windows guy, it seems like this can be accomplished using Windows API hooks- tie-ins to the low-level API that can modify system-wide response to a system call. These hooks can be installed as something like a kernel module, and intercept and potentially modify system calls. I found an article on CodeProject that offers more information.
In a machine learning course I took, a group decided to try something similar to what you're describing for a semester project. They used a list of recent system calls made by a program to determine whether or not the executing program was malicious, and the results were promising (think 95% recognition on new samples). In their project, they trained using SVMs on windowed call lists, and used that to determine a good window size. After that, you can collect system call lists from different malicious programs, and either train on the entire list, or find what you consider "malicious activity" and flag it. The cool thing about this approach (aside from the fact that it's based on ML) is that the window size is small, and that many trained eager classifiers (SVM, neural nets) execute quickly.
Anyway, it seems like it could be done without the ML if it's not your style. Let me know if you'd like more info about the group- I might be able to dig it up. Good luck!
Windows provides APIs to do that (generally the involve running at least some of your code in kernel). If you have sufficient privileges, you can also inject a .dll into other process. See http://en.wikipedia.org/wiki/DLL_injection.
When you have the powers described above, you can do that. You are either in kernel space and have access to everything, or inside the target process.
At least for the low-level in-kernel stuff you'd need something more low-level than C#, like C or C++. I'm not sure, but you might be able to do some of the rest things in a C# app.
The DLL injection sounds like the simplest starting point. You're still in user space, and don't have to learn how to live in the kernel world (it's completely different world, really).
Some loose ideas on topic in general:
you can interpose system calls issued by the traced process. It is generally assumed that a process cannot do anything "dangerous" without issuing a system call.
you can intercept its network traffic and see where it connects to, what does it send, what does it receive, which files does it touch, which system calls fail
you can scan its memory and simulate its execution in a sandbox (really hard)
with the system call interposition, you can simulate some responses to the system calls, but really just sandbox the process
you can scan the process memory and extract some general characteristics from it (connects to the network, modifies registry, hooks into Windows, enumerates processes, and so on) and see if it looks malicious
just put the entire thing in a sandbox and see what happens (a nice sandbox has been made for Google Chrome, and it's open source!)

Categories

Resources