Detecting Windows NT/2 k Process Execution

Source: Internet
Author: User
ArticleDirectory
    • Control Application (consctl)
    • Download source files-33 KB

Abstract

Intercepting and tracing process execution is a very useful mechanic for implementing nt Task Manager-like applications and systems that require manipulations of external processes. policying interested parties upon starting of a new processes is a classic problem of developing process monitoring systems and system-wide hooks. win32 API provides set of Great Libraries (psapi and toolhelp [1]) that allow you to enumerate processes currently running in the system. although these APIs are extremely powerful they don't permit you to get notifications when a new process starts or ends up. this article provides an efficient and robust technique based on a pair ented interface for achieving this goal.

Solution

Luckily, NT/2 k provides a set of APIS, known as "process structure routines" [2] exported by ntoskrnl. One of these ApisPssetcreateprocesspolicyroutine ()Offers the ability to register system-wide callback function which is called by OS each time when a new process starts, exits or is terminated. the mentioned API can be employed as an easy to implement method for tracking down processes simply by implementing a NT kernel-mode driver and a user mode Win32 control application. the role of the driver is to detect process execution and notifiy the control program about these events.

Requirements
    • Provide a simple, efficient, reliable and thread-safe mechanic for monitoring process execution
    • Resolve synchronization issues between the driver and the user mode Application
    • Build an easy to use and extend OOP user-mode framework
    • Allow registering and un-registering of the callback as well as ability to dynamically load and unload the kernel driver
How it works

The control application register the Kernel Mode Driver Under HKLM \ System \ CurrentControlSet \ Services and dynamically loads it. the kernel driver then creates a named event object that is used to signal the user-mode application when new event has been fired (I. e. process starts or ends up ). the control application opens the same event object and creates a listening thread that waits on this event. next, the user mode application sends a request to the driver to start monitoring. the driver invokesPssetcreateprocesspolicyroutine () , Which accepts two parameters. one of them specifies the entry point of a caller-supplied callback routine, responsible for processing all notifications from windows. upon a notification, that takes place in the callback, the driver signals that event in order to inform the user-mode application that something has happened. the control application then gets the data for that participant event from the driver and stores it in a special queue container for further processing. if there is no need for detecting process execution anymore the user mode application sends a request to the driver to stop monitoring. the driver then deactivates the observing mechanic. later the control mode application can unload the driver and un-register it.

Design and Implementation

NT kernel mode driver (procobsrv)

The entry pointDriverEntry ()(Procobsrv. c) performs the driver's initialization only. The I/O manager CILS this function when the driver is loaded. SincePssetcreateprocesspolicyroutine ()Allows to un-register the callback I implemented the actual process of registration and un-registration in the driver's dispatch routine. this allows me dynamically to start and stop the monitoring activities by using a single IOCTL (control codeIoctl_procobsrv_activate_monitoring). Once the callback is registered each time when a process starts or terminates the OS calluser suppliedProcesscallback (). This function populates a buffer that will be picked up by the user mode application. next the driver signals the named event object, thus the user-mode application that waits on it will be informed that there is available information to be retrieved.

Control Application (consctl)

for the sake of simplicity I decided to provide a simple console application, leaving the implementation of the fancy GUI stuff to you. designing of an application to be multithreaded allows that application to scale and be more responsive. on the other hand, it is very important to take into account several considerations related to synchronizing the access to information provided by the publisher (I. e. kernel Driver) and retrieved by the subscriber (I. e. control Application ). the other important key point is that a detecting system must be reliable, and makes sure that no events are missed out. to simplify the design process, first I needed to assign the responsibilities between different entities in the user mode application, responsible for handling the driver. however it isn' t difficult to do it by answering these questions [5]:

    1. What are the processes in the system
    2. What are the roles in the framework
    3. Who does what and how do they collaborate

Follows UML class dises, that has strates the relations between classes:

CapplicationscopeImplements a singleton and wraps up the main interface to the Framework. It exposes two public methods that start and stop the monitoring process.

ClassCapplicationscope {.. other details ignoredForThe sake of simplicity ....Public://Initiates process of monitoring processBool startmonitoring (pvoid pvparam );//Ends up the whole process of monitoringVoidStopmonitoring ();};

CprocessthreadmonitorIs the thread that waits on the created by the driver event to be signaled. As soon as a process has been created or ended up, the driver signals this event object andCprocessthreadmonitor'S thread wakes up. Then the user mode application retrieves the data from the driver. Next, the data is appended to queue container (Cqueuecontainer) Using its MethodAppend ().

CqueuecontainerIs a thread-safe queue controller that offers an implementation of the Monitor/condition variable pattern. the main purpose of this class is to provide a thread-safe semaphore realization of a queue container. this is how the MethodAppend ()Works:

    1. Lock access to the aggregated STL deque object
    2. Add the data item
    3. SignalM_evtelementavailableEvent object
    4. Unlock the deque

 

And here is its actual implementation:

  //   insert data into the queue  bool cqueuecontainer:: append ( const  queued_item & element) {bool bresult = false; dword dw =: waitforsingleobject (m_mtxmonitor, infinite ); bresult = (wait_object_0 = DW);  If  (bresult) { //   Add it to the STL queue  m_queue.push_back (Element );  //   define y the waiting thread that there is  ///   available element in the queue for processing :: setevent (m_evtelementavailable);} ///    :: releasemutex (m_mtxmonitor);  return  bresult ;}

Since it is designed to your Y when there is an element available in the queue, it aggregates an instanceCretreivalthread, Which waits until an element becomes available in the local storage. This is its pseudo implementation:

    1. Wait onM_evtelementavailableEvent object
    2. Lock access to the STL deque object
    3. Extract the data item
    4. Unlock the deque
    5. Process the data that has been retrieved from the queue

Here is the method invoked when something has been added to the queue:

Collapse
 //  Implement specific behavior when Kernel Mode Driver notifies  //  The user-mode app void Cqueuecontainer: doonprocesscreatedterminated () {queued_item element; //  Initially we have at least one element for processing Bool bremovefromqueue = true; While (Bremovefromqueue) {DWORD dwresult =: waitforsingleobject (m_mtxmonitor, infinite ); If (Wait_object_0 = dwresult ){ //  Is there anything in the queue Bremovefromqueue = (m_queue.size () >   0 ); If (Bremovefromqueue ){ // Get the element from the queue Element = m_queue.front (); m_queue.pop_front ();} //  If              Else  //  Let's make sure that the event hasn't been                  //  Left in signaled state if there are no items                  //  In the queue : Resetevent (m_evtelementavailable );} //  If: releasemutex (m_mtxmonitor );              // Process it only if there is an element that has              //  Been picked up              If (Bremovefromqueue) m_phandler- > Onprocessevent (& element, m_pvparam ); Else  Break ;} //  While }

ccustomthread -to help manage the complexity of maintaining raw threads I encapsulated all thread's related activities in an abstract class. it provides a pure virtual method Run () , that must be implemented by any specific Thread class (e.g. cretrievalthread and cprocessthreadmonitor ). ccustomthread is designed to ensure that thread function returns when you want the thread to terminate as the only way to make sure that all thread's resources are cleaned up properly. it offers a means to shut any of its instances down by signaling a named event m_hshutdownevent .

ccallbackhandler is an abstract class that has been designed to provide interface for login Ming user-supplied actions when process is created or terminated. it exposes a pure virtual method onprocessevent () , which must be implemented according to the specific requirements of the system. in the sample code you will see a class cmycallbackhandler , that inherits from ccallbackhandler and implements onprocessevent () method. one of the parameters pvparam of onprocessevent () method allows you to pass any kind of data, that's why it is declared as pvoid . in the sample code a pointer to an instance of cwhatheveryouwanttohold is passed to the onprocessevent () . you might want to use this parameter to pass just a handle to a window, that cocould be used for sending a message to it within onprocessevent () implementation.

ClassCcallbackhandler {Public: Ccallbackhandler ();Virtual~ Ccallbackhandler ();//Define an abstract interface for Processing notificationsVirtual VoidOnprocessevent (pqueued_item pqueueditem, pvoid pvparam) =0;};
Compiling the sample code

You need to have installed MS Platform SDK on your machine. provided sample code of the User-mode application can be compiled for ANSI or Unicode. in case you wowould like to compile the driver you have to install Windows DDK as well.

Running the sample

However, it is not a problem if you don't have Windows DDK installed, since the sample code contains a compiled debug version of procobsrv. sys kernel driver as well as IT source code. just place control program along with the driver in single directory and let it run.

For demonstration purposes, the user mode application dynamically INSTALLThe driver and initiates process of monitoring. next, you will see 10 instances of notepad.exe launched and later on closed. meanwhile you can peek at the console window and see how the process monitor works. if you want you can start some program and see how the console will display its process ID along with its name.

Conclusion

This article demonstrated how you can employ a specified ented interface for detecting NT/2 K process execution. however it is by far not the only one solution to this issue and certainly might miss some details, but I hope you wocould find it helpful for some real scenarios.

References:
    1. Single interface for enumerating processes and modules under NT and Win9x/2 K, Ivo Ivanov
    2. Windows DDK documentation, process structure routines
    3. Nerditorium, Jim Finnegan, MSJ January 1999
    4. Windows NT device driver development, Peter G. viscarola and W. Anthony Mason
    5. Applying UML and patterns, Craig larman
    6. Using predicate waits with Win32 threads, D. Howard, C/C ++ users Journal, May 2000


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.