C# Hook Windows Processes to Check for Debugging Processes - c#

I was wondering if there is a way I could hook the windows processes to check if any suspicious programs are running like (Wireshark, Fiddler, OllyDBG, etc).
I want to hook the windows processes so it will close the client or pop-up a message in real time when it detects a unwanted process.
If you guys can provide me with any links to doing this that would be nice.
Thanks!

Process[] processlist = Process.GetProcesses();
Then walk the list and do as desired for your apps you do not want to run.

You can detect process creations by using WMI creation events for Win32_Process. An instance of Win32_Process is created with each process, so looking new instances will tell you about process creation in (near) real time.
To receive WMI creation events see this page: http://msdn.microsoft.com/en-us/library/system.management.eventquery.aspx (EDIT: different link, now to sample in C#).

EnumWindows enumerates all top level windows.
And you don't want to inject a C# dll into other processes. This requires the .net runtime to be loaded into that process. This wastes RAM, and if the process is a .net app using a different version of .net then there are versioning problems. Especially if your dll is injected before the process loads its own version of .net.
And what to you want to achieve by injecting into that process you can't achieve from the outside?

You might want to check out EasyHook on CodePlex (http://easyhook.codeplex.com). Here is some discussion where people reportedly have been able to hook into CreateProcess. If you manage to hook into that API function you know of the created process at creation time.

Related

interact with external application in c#

I was playing around with Microsoft Spy++ and noticed that not only does it find the open processes, but can find the individual components running in each process. For example there is this application that allows you to open a window in which there is a textbox for an IP address and textbox for a port. Spy++ can detect these components. Knowing that Spy++ can detect them, is there anyway possible to find them in a separate c# application and go on to MODIFY their contents and otherwise interact with the program? (such as firing a click event on a button)
This is feasible. Try use PInvoke (InterOp) or AutomationElement, or AutomationPeer (for WPF applications) to automate all you wish to do.
Also you might wish to try Inspect and UISpy application as well.
Automation elements/peer is a non-intrusive mechanism to control UI using accessibility framework. One of the weaknesses in windows is its lack of defence against code injection. Put simply:
As a privileged user,
- You can Open and Modify a running Process image
- Make it load your OWN DLL
- Make it run your OWN thread (that potentially listens to commands from your process) and
- allows you to read any bits of memory you want.
Look at detours (http://research.microsoft.com/en-us/projects/detours/) for how to do it with Managed Processes.. Unfortunately, Microsoft removed the inject at runtime features.
Also look at http://msdn.microsoft.com/en-us/magazine/cc163617.aspx for doing things in the managed world (Apps like Snoop utilise that)

How to check if external WPF process or other process is done launching?

I've written a WPF/C#-based "shell" which launches WPF apps or other apps.
What would be the best method for checking if the process is finally fully launched or no longer "busy"? I've noticed that the mouse cursor for the launched process stays at the busy cursor from initial launch until I can finally see the UI for the process. Could I use User32.SetCapture API to set the mouse capture to the external process, then somehow check if the mouse cursor is the busy cursor? Or perhaps there's a mechanism in the System.Diagnostics.Process class that I'm unaware of?
As some of the launched apps are pre-compiled third-party apps, I absolutely cannot implement a mechanism in the external processes to message if it is finally ready, such as: Microsoft PowerPoint 2010 Viewer, Adobe Acrobat, or Adobe Flash Player Standalone.
I can't just check if the process has been created, because then I have a blank, unresponding window and a busy cursor. I hope to hide my WPF app the moment the external process is done launching.
The WaitForInputIdle Win32 APi function will wait until given process enters the message loop (with no input pending).
Quote: "Before trying to communicate with the child process, the parent process can use the WaitForInputIdle function to determine when the child's initialization has been completed."
You can call it via P/Invoke.
Not very cear what do you mean saying "beasy", but hear are several considerations:
There is no known (clear) way, at least that I'm aware of, that can let you do something like that. The thing is that process is perfectly isolated OS kernel citizen. So you can not write something that works for all type processes, especially if they are 3rd part binaries.
What you can try to do, is get the MainWindow of the process (if there is any), get its handle, and filter OS messages untill you get for example WM_ACTIVATED.
But even if this could work in certain situations, in others can measurably fail. For example, process loaded but the program is not active, cause for some reason License window of the application appeared.
Let's see what others suggest, in my opinion, there is no generic and no single solution to cover minority of possible cases.
Good luck

preventing a program from starting when another prog is running (Windows)

I have 2 programs. I want to build an external tool, which prevents one of the programs from starting, when the other program is already running, and vice versa.
I can't touch the code of either of the two programs.
I want to do it preferably with C#, but a scripting language will also be ok.
Can anyone help me with the concept how to implement it?
Thanks in advance.
Write your tool as a windows service that keeps running in background and kills the second program if it starts. It can find out when a new process starts by listening to WMI events see .NET Events for Process executable start
There are couple of ways to do that. If you are using C# you should be getting the process name using the GetProcessesByName(). It would look something like this
Process[] processes = Process.GetProcessesByName(processName);
If you know the process name you can just kill the process
Or else use the [Semaphore Class] (http://msdn.microsoft.com/en-us/library/system.threading.semaphore.aspx).

C# Raise an event when a new process starts

Hey there, Is there a way to raise event when a new process is started without using the ManagementEventWatcher, and without using the Process.GetProcesses()?
The problem with ManagementEventWatcher is that the user needs to have high premmisions.
Thank you!!!
Unlike the extrinsic event Win32_ProcessStartTrace that you are currently using, the __InstanceCreationEvent and __InstanceDeletionEvent WMI intrinsic events do not require administrator rights.
Here's a sample query you can use to track process starts:
SELECT TargetInstance
FROM __InstanceCreationEvent WITHIN 1
WHERE TargetInstance ISA 'Win32_Process'
AND TargetInstance.Name LIKE '<your process name.exe>'
Further info: Process Information and Notifications using WMI
Because these are intrinsic events, WMI ultimately mimics event behaviour by means of polling, and will check for new events only periodically (here, every 1 second). Decreasing the WITHIN duration to fractions of seconds will give you faster response at the expense of CPU usage.
It should be possible to figure out when an application was last run by configuring audit process tracking in Windows. The following links might get you started:
Audit process tracking
How can I track what programs come and go on my machine?
The process tracking will create entries in the Windows event log which you can then access using C#.
Ref: .NET Process Monitor
Strange thing is an application does not need to create a window in windows. Create process may not belong to the window-station that you work on. You will need to find windows of that process anyway, and you will also need to detect new and closed windows of all processes.
So enumerating windows is much cleaner/easier choice.
Try EnumChildWindows function on desktop handle (retrieved by GetDesktopWindow) to find top level windows of applications. use GetWindowThreadProcessId and EnumThreadWindows on obtained handles to detect sub windows of windows.
A low priority thread will do the job.
You can probably use EnumDesktopWindows from user32.dll, you will get all the window handles, you can check the title of the window using GetWindowText, and type of window using GetClassName.
That way you can hide the hint or treasure anywhere. (because you will get handles of all the windows (and controls)).
See if this class will be useful to you
Managed Global Hook for Window Creation and Destruction
On that article, someone has created nice class with easy to attach events, You can run that code without elevating privileges.
Once you get the window (control) handle, you can add text or draw image on it for hints.

Prevent application launch in C#

Okay I've spent the afternoon researching and haven't had much luck finding the answer to this. I am trying to prevent an application from launching via some sort of dll or background application. It is to be used in monitoring application usage and licenses at my institution. I have found leads here regarding WqlEventQuery and also FileSystemWatcher. Neither of these solutions appear to work for me because:
With WqlEventQuery I was only able to handle an event after the process was created. Using notepad as a test, notepad was visible and accessible to me before my logic closed it. I attempted to Suspend/Resume the thread (I know this is unsafe but I was testing/playing) but this just hung the window until my logic finished.
With FileSystemWatcher I was not able to get any events from launching a .exe, only creating, renaming and deleting files.
The goal here is to not let the application launch at all unless my logic allows it to launch. Is this possible? The next best solution I came up with was forcing some type of modal dialog which does not allow the user to interact with anything, once the dialog is closed the application is killed. My concern here is killing the application nicely and handling applications with high overhead when they load such as Photoshop or something. This would also interfere with a feature I was hoping to have where the user could enter a queue until a license is available. Is this my best route? Any other suggestions?
Thanks
edit: To clarify this is not a virus or anything malicious. It's not about preventing access to a blacklist or allowing access through a whitelist. The idea is to check a database on a case by case basis for certain applications and see if there is a license available for use. If there is, let the app launch, if not display a dialog letting the user know. We also will use this for monitoring and keeping track if we have enough licenses to meet demand, etc. An example of one of these apps is SPSS which have very expensive licenses but a very limited pool of people using it.
Could you use
System.Diagnostics.Process.GetProcessesByName
in a loop to look for the process?
It might work if you don't use too aggressive a polling rate.
You are indeed close, take a look at the WMI Management Events. http://msdn.microsoft.com/en-us/library/ms186151%28VS.80%29.aspx
Sample code from Microsoft: http://msdn.microsoft.com/en-us/library/ms257355(VS.80).aspx
Subscribing to the appropriate event will provide your application with the appropriate information to perform what you described.
Not sure if this is a GOOD solution but you could do something like pass a key into main so that if the key is not present or valid the application shuts down. Then when you open the application in your code, just pass the key in. Someone would then have to know the key in order to start the application.
This is assuming you have access to the application in question's source code, which upon reading your question again, I'm not so sure of.
I assume you don't have source for the application you want to prevent from loading...
Have you considered using a system policy? That would be the best-supported way to prevent a user from launching a program.
You could have a service running that force-kills any app that isn't "whitelisted", but I can't say how well that would work.
I wonder if you are taking the wrong approach. Back in the day there was a Mac app that would prevent access to the desktop and had buttons to launch a set list of applications.
IDEA
What if you had a wrapper for the approved apps then only allow your wrapper to run on the computer?
I would expect there is some way of hooking an application launch, but can't help directly on that front.
You may be able to improve your current approach by detecting the application's window opening and hiding it (move it offscreen) so that the user can't attempt to interact with it while you are trying to shut it down.
However, another approach that may be possible (depending on your circumstances) would be to write an application launcher. This simply is a replacement for the shortcut to the application that checks your licencing conditions, and then does a Process.Start to launch the real .exe at that point. This would work well for any application. (I used a system like this for starting up applications with specialised environment settings and it works beautifully)
You could combine this with your current approach as a fall-back for "clever" users who manage to circumvent your launcher.
If my understanding is right you want to create an application what will prevent the computer user to start any other process except ones for a white-list.
If this is the case, monitor the process list of processes (in a while loop) using System.Diagnostics.Process (the GetProcesses method gives the list of all running ones)
Just kill the process when it starts.
Or if your machines have Windows 7 (Windows 2008??) you can use AppLocker. http://www.microsoft.com/windows/enterprise/products/windows-7/features.aspx#applocker Just let Windows prevent the startup.
You might want to look at this product: http://www.sassafras.com/licensing.html Personally I can't stand it, but that's because it does what you describe. Might save you some coding.
You could actually edit the registry so when you click a psd, your launcher gets called instead of photoshop. Your launcher then checks for licenses and if there is one starts photoshop with the path of the file.
This is a long shot but you may find it helpful.
Perceived Types and Application Registration
http://msdn.microsoft.com/en-us/library/cc144150(VS.85).aspx

Categories