.Net Process Monitor

.NET Process Monitor

WMI provides a way to track processes starting and terminating with the Win32_ProcessTrace classes. Best shown with an example. Start a new Console application, Project + Add Reference, select System.Management. Paste this code:

using System;
using System.Management;

class Process {
public static void Main() {
ManagementEventWatcher startWatch = new ManagementEventWatcher(
new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"));
startWatch.EventArrived += new EventArrivedEventHandler(startWatch_EventArrived);
startWatch.Start();
ManagementEventWatcher stopWatch = new ManagementEventWatcher(
new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace"));
stopWatch.EventArrived += new EventArrivedEventHandler(stopWatch_EventArrived);
stopWatch.Start();
Console.WriteLine("Press any key to exit");
while (!Console.KeyAvailable) System.Threading.Thread.Sleep(50);
startWatch.Stop();
stopWatch.Stop();
}

static void stopWatch_EventArrived(object sender, EventArrivedEventArgs e) {
Console.WriteLine("Process stopped: {0}", e.NewEvent.Properties["ProcessName"].Value);
}

static void startWatch_EventArrived(object sender, EventArrivedEventArgs e) {
Console.WriteLine("Process started: {0}", e.NewEvent.Properties["ProcessName"].Value);
}
}

Edit the manifest so this program runs elevated. Then simply start some programs to see it at work. Beware that it is not especially quick.

C#.NET Monitoring for a Process

The documentation for this can be found on MSDN
https://msdn.microsoft.com/en-us/library/system.management.managementeventwatcher.eventarrived%28v=vs.110%29.aspx

OnEventArrived should look like this.

private void OnEventArrived(object sender, ManagementEventArgs args)
{
//do your work here
}

Here is a sample program that will monitor notepad. You probably want to read more on WMI to see if there is a better way. You can launch notepad via the start menu and you will see Notepad started out put to the console. On exiting it will print Notepad Exited. I do not know all the messages that can be output.

    static void Main(string[] args)
{

string pol = "2";
string appName = "Notepad.exe";

string queryString =
"SELECT *" +
" FROM __InstanceOperationEvent " +
"WITHIN " + pol +
" WHERE TargetInstance ISA 'Win32_Process' " +
" AND TargetInstance.Name = '" + appName + "'";

// You could replace the dot by a machine name to watch to that machine
string scope = @"\\.\root\CIMV2";

// create the watcher and start to listen
ManagementEventWatcher watcher = new ManagementEventWatcher(scope, queryString);
watcher.EventArrived += new EventArrivedEventHandler(OnEventArrived);
watcher.Start();
Console.Read();
}

private static void OnEventArrived(object sender, EventArrivedEventArgs e)
{
if (e.NewEvent.ClassPath.ClassName.Contains("InstanceCreationEvent"))
Console.WriteLine("Notepad started");
else if (e.NewEvent.ClassPath.ClassName.Contains("InstanceDeletionEvent"))
Console.WriteLine("Notepad Exited");
else
Console.WriteLine(e.NewEvent.ClassPath.ClassName);
}

How to detect when a file is checked for in a directory?

I thinks is pretty safe to answer this question,

I want to be able to programmatically (C#) detect when a program
attempts to load (or otherwise access) a non-existent DLL from a
directory that I control/own on Windows.

There is really only one reliable way to achieve this, and its really not for the faint-or-heart.

I can manually accomplish this using Sysinternals Process Monitor
(ProcMon).

ProcMon is a very complex application and makes use of all sorts of black magic in Kernel Mode to achieve what it does


DLL injection

In computer programming, DLL injection is a technique used for running
code within the address space of another process by forcing it to load
a dynamic-link library.1 DLL injection is often used by external
programs to influence the behavior of another program in a way its
authors did not anticipate or intend.1[2][3] For example, the
injected code could hook system function calls,[4][5] or read the
contents of password textboxes, which cannot be done the usual way.[6]
A program used to inject arbitrary code into arbitrary processes is
called a DLL injector.

The premise is exceedingly simple, and its a well used technique to do various things.

Basically, you need to inject a DLL into the program address space. The best known and most often used method is "Import Table Patching". Each win32 module (application/DLL) has a so-called "import table", which is basically a list of all APIs, which this module calls. Patching this import table is a quite easy job and works very nicely.

Another more robust method is, you can also directly manipulate the API's binary code in memory. The most often used method is to overwrite the first 5 bytes of the API code with a JMP instruction, which then jumps to your callback function.

In your case you want to Find LoadLibrary in your target application, JMP to a proxy where you can monitor the libraries loaded and also the results of the call, then pass back the results to the original caller.

This is pretty intense stuff, however it is more common that what you think. There are libraries written that Use Drivers that work in Kernel Mode Which work for 64bit and 32Bit applications that take care off all the hard work, you basically just give it a scope a dll and a signature of the apis you want to hook and write a proxy. and it will take care of the rest. At that point you can IPC the results anywhere you like.

Your first problem is setting a hook before it loads your target lib. However once again this has all be done for you. take a look at http://help.madshi.net/madCodeHook.htm

The onyl down side here, is it has to be done with a traditional DLL and not in .net

Anyway good luck

How to use Process Monitor to Resolve an UnauthorizedAccessException

When PM starts it displays a filter dialog. Just click 'Reset' to use the standard filtering. This will generate lots of messages, and you are only interested in very few of them. Under Process Name, select a line with the process you want to monitor. Richtclick it and choose include . That limits the reported events to the ones of your app. In the toolbar, the three rightmost icons let you filter the sources: Registry access, file system access and process/thread events. Unselect registry and process/threads, since you only want to monitor file access.
In the menu choose Options - Select columns. Under Process Management, check User Name.

Now try to reproduce the error. If you are still getting too many events, you can limit the path (rightclick in the Path column and choose exclude ). You can fine tune your filtering by clicking Ctrl-L, the interface should be self explanatory. (Oh, just remember to click Add before clicking OK when you want to create a new filter rule... I almost always fall for that particular trap ;-)



Related Topics



Leave a reply



Submit