Filemon learning notes for file filtering system-driven development

Source: Internet
Author: User
Windows File filtering system driver development, can be used in hard disk restoration, anti-virus, file security protection, file encryption and many other fields. Mastering the theory and practice of the core layer is indispensable for becoming an excellent developer.

Two typical examples of Windows file filtering system driver development: Filemon and sfilter. After some theoretical accumulation, beginners can use these two examples.CodeThe research and analysis will be an important step into the driving development Hall. I believe that the theoretical accumulation and analysis of these two routines will be carried out, the ability to start the development of the file filtering system driver.
For the sfilter example, the tutorial of Chu's madman is already popular, while the Filemon example may be easy to understand due to the relatively clear framework structure and no one posts the tutorial, I have accumulated some notes during the analysis of Filemon, and have successively posted hope to help beginners and improve each other through communication with everyone.

Filemon Study Notes:

The general structure of Filemon is:ProgramTwo types of device objects are created.
A type of device object is used to communicate with the EXE program corresponding to Filemon to receive user input information, such as the mounted or monitored partition, whether to hook up, whether to monitor, and what operations to monitor. Only one device object is created in the driver's entry function DriverEntry. This type of device object is generally called a control device object with a name to facilitate communication between the application layer and its operation.
The second type of device object is used to mount to the partition to be monitored, such as C:, D: Or E:, F:, to block the read performed by the application layer on the partition, write operations. For the sake of security, this type of device object is generally not named. You can create one or more devices based on the number of partitions to be monitored.

The driver entry functions are roughly as follows:

Handler (in pdriver_object driverobject, in punicode_string registrypath) {ntstatus; pdevice_object guidevice; wchar devicenamebuffer [] = l "\ device \ Filemon"; unicode_string devicenameunicodestring; wchar devicelinkbuffer [] = l "\ dosdevices \ Filemon"; unicode_string devicelinkunicodestring; ulong I; dbuplint ("Filemon. SYS: Entering DriverEntry \ n "); filemondriver = driverobject; // set Up the device name // rtlinitunicodestring (& devicenameunicodestring, devicenamebuffer ); /// create the device used for GUI communications // ntstatus = iocreatedevice (driverobject, sizeof (hook_extension), & devicenameunicodestring, file_device_filemon, 0, true, & guidevice); // If successful, make a symbolic link that allows for the device // object's access from Win32 programs // If (nt_succes S (ntstatus) {// mark this as our GUI device // (phook_extension) guidevice-> deviceextension)-> type = guiinterface; /// create a symbolic link that the GUI can specify to gain access // to this driver/device // rtlinitunicodestring (& devicelinkunicodestring, devicelinkbuffer); ntstatus = iocreatesymboliclink (& devicelinkunicodestring, & devicenameunicodestring); If (! Nt_success (ntstatus) {dbuplint ("Filemon. SYS: iocreatesymboliclink failed \ n "); iodeletedevice (guidevice); Return ntstatus ;}/// create dispatch points for all routines that must be handled. // all entry points are registered since we might filter a // file system that processes all of them. // for (I = 0; I <= irp_mj_maximum_function; I ++) {driverobject-> majorfunction [I] = filemondispatch;} # If dbg/ /// Driver unload is only set if we are debugging Filemon. this is // because unloading a filter is not really safe-threads cocould // be in our fastio routines (or about to enter them), for example, // and there is no way to tell. when debugging, we can risk the // occasional unload crash as a trade-off for not having to // reboot as often. /// driverobject-> driverunload = filemonunload; # endif // dbg/ /// Set up the fast I/O dispatch table // driverobject-> fastiodispatch = & fastiohook;} else {// if something went wrong, cleanup the device object and don't load // dbuplint ("Filemon: failed to create our device! \ N "); Return ntstatus;} // initialize the name hash table // for (I = 0; I <numhash; I ++) hashtable [I] = NULL; // find the process name offset // processnameoffset = filemongetprocessnameoffset (); // to get the current process name /// initialize the synchronization objects // # if needed (& countmutex); # consumed (& logmutex); exinitializeresourcelite (& filterresource); exinitializeresourcel ITE (& hashresource); // initialize a lookaside for file names // exinitializenpagedlookasidelist (& fullpathlookaside, null, null, 0, MAXPATHLEN, 'mlif ', 256 ); /// allocate the first output buffer // currentlog = exallocatepool (nonpagedpool, sizeof (* currentlog); If (! Currentlog) {// oops-we can't do anything without at least one buffer // iodeletesymboliclink (& devicelinkunicodestring); iodeletedevice (guidevice); Return status_insufficient_resources ;} /// set the buffer pointer to the start of the buffer just allocated // currentlog-> Len = 0; currentlog-> next = NULL; numlog = 1; return STATUS_SUCCESS ;}

In this driver entry point function, a new device object is generated. The device object is used to interact with the application layer information. For example, the application layer transmits the partition drive letter that needs to be mounted or monitored to the driver, or whether to mount the drive letter or monitor the operation.
The code for creating a device object above is:

 
Ntstatus = iocreatedevice (driverobject, sizeof (hook_extension), & devicenameunicodestring, file_device_filemon, 0, true, & guidevice); // If successful, make a symbolic link that allows for the device // object's access from Win32 programs // If (nt_success (ntstatus )) {// mark this as our GUI device // (phook_extension) guidevice-> deviceextension)-> type = guiinterface; // create a symbolic link that GUI can specify to gain access // to this driver/device // rtlinitunicodestring (& devicelinkunicodestring, devicelinkbuffer); ntstatus = iocreatesymboliclink (& devicelinkunicodestring, & devicenameunicodestring); If (! Nt_success (ntstatus) {dbuplint ("Filemon. SYS: iocreatesymboliclink failed \ n"); iodeletedevice (guidevice); Return ntstatus ;}

The function completed by the code above creates a control device object for interaction with the application layer. Its name is in the parameter & devicenameunicodestring. After the device object is successfully created, call iocreatesymboliclink to create a symbolic connection for interaction at the application layer. In the DriverEntry code of the entry point function, another code is: processnameoffset = filemongetprocessnameoffset (); // to get the name of the current process. This function is as follows:

 
Ulongfilemongetprocessnameoffset (void) {peprocess curproc; int I; curproc = psgetcurrentprocess (); // call psgetcurrentprocess to obtain the kpeb base address. // search for kpeb, get the offset of processname relative to kpeb // scan for 12kb, hoping the kpeb never grows that big! // For (I = 0; I <3 * page_size; I ++) {If (! Strncmp (sysname, (pchar) curproc + I, strlen (sysname) {return I ;}/// name not found-oh, well // return 0;

This function finds the kpeb (kernel process environment block) and obtains the process name. getprocessnameoffset mainly calls psgetcurrentprocess to obtain the kpeb base address, searches for kpeb, and obtains the offset of processname to kpeb, the offset is stored in the global variable processnameoffset. The offset is obtained through this offset, regardless of the current process and the offset of its name in kpeb. When the entry point function DriverEntry is executed, the current process must be a system process. Therefore, in this function, you can conveniently get this offset based on the system process name sysname (# define sysname "system.

Distribution Function Analysis:
In the entry point function, use the code:

 
For (I = 0; I <= irp_mj_maximum_function; I ++) {driverobject-> majorfunction [I] = filemondispatch ;}

Set each distribution routine to filemondispatch. Then we track its function body:

 
Ntstatusfilemondispatch (in pdevice_object deviceobject, in pirp) {// determine if its a request from the GUI to us, or one that is // directed at a file system driver that we 've hooked // If (phook_extension) deviceobject-> deviceextension)-> type = guiinterface) {return filemondeviceroutine (deviceobject, IRP) ;}else {return filemonhookroutine (deviceobject, IRP );}}

The function first determines the type of the device object that needs to process the IRP package, whether it is a control device object or a filtering device object used for mounting and monitoring file read/write operations. If it belongs to the latter, access: filemonhookroutine (deviceobject, IRP)
This function is the center for intercepting file operations. In this function, the name of the file to be operated is obtained, and according to the operation type
Switch (currentirpstack-> majorfunction ){
}
For different majorfunctions, print the relevant operation information.
So the function body is too long to be listed.
The overall framework of the function body is: get the name of the file to be operated, print the relevant operation information, and then send the IRP to the underlying driver.
Before sending an IRP to the underlying driver for processing, the driver of this layer must be responsible for setting the content of the underlying Io stack. In this way, the next driver can obtain the corresponding data when calling iogetcurrentirpstacklocation.
Set the content of the lower-layer Io stack, which is generally implemented using two functions:
Iocopycurrentirpstacklocationtonext (IRP)
This function is generally called when the driver sets the completion routine. The parameter in the IO _ stack_location of the current layer is copied to the lower layer, but the parameter information related to the completion routine is exceptional. Because the completion routine of the driver settings is only valid for the driver at this layer.
Ioskipcurrentirpstacklocationtonext (IRP)
This function is used to directly set the content of the driver Io stack at the current layer to the pointing of the driver Io Stack pointer at the lower layer. Because the content of the two-layer driver I/O stack is completely consistent, the copy process is saved.

In Filemon's processing, it uses a special method and does not call these two functions. The filemonhookroutine function body contains three codes:

 

Pio_stack_location currentirpstack = iogetcurrentirpstacklocation (IRP); pio_stack_location nextirpstack = iogetnextirpstacklocation (IRP); * nextirpstack = * currentirpstack; // In this step, io_stack_location of the underlying driver is set to set the value of the underlying driver Io stack.

In the filemonhookroutine function, a macro is used to implement complicated operations to obtain intercepted data.CompositionComponent Name:

 
If (filteron & hookext-> hooked) {getpathname (createpath );}

The getpathname (createpath) macro is available:

 
# Define getpathname (_ iscreate) \ fullpathname = Response (& fullpathlookaside); \ If (fullpathname) {\ filemongetfullpath (_ iscreate, fileobject, hookext, fullpathname ); \} else {\ fullpathname = insufficientresources ;\}

In the function: filemongetfullpath (_ iscreate, fileobject, hookext, fullpathname), the name of the file to be operated is obtained. This function has many codes, complex judgment conditions, and is difficult to understand, the following is an important explanation.
The key to understanding the filemongetfullpath function is to straighten out the structure,
This function is used to obtain the file name. Generally, the file name can be obtained in three states:
I. before opening a file.
2: In the file opening request, but after opening the file, the routine is set in the driver of this layer. Obtained in the completion routine.
Iii. Filtering read/write operations.
In this function, it contains the first and third methods. Through some cumbersome conditions, we can first determine the current status and then adopt different methods based on different states.

First, analyze the processing method of this function under the first condition, which can be refined as follows:

Using (Boolean createpath, pfile_object fileobject, jsonhookext, pchar fullpathname) {ulong pathlen, prefixlen, slashes; pchar success, PTR; Boolean gotpath; pfile_object success; ansi_string filename; ansi_string success; unicode_string fulluniname; prefixlen = 2; // "C:" If (! Fileobject) {sprintf (fullpathname, "% C:", hookext-> logicaldrive); Return ;}/// initialize variables // filename. buffer = NULL; relatedname. buffer = NULL; gotpath = false; If (! Fileobject-> filename. buffer) {sprintf (fullpathname, "% C:", hookext-> logicaldrive); return;} elsedbuplint ("fileojec-> filename: % s", fileobject-> filename ); if (! Nt_success (rtlunicodestringtoansistring (& filename, & fileobject-> filename, true) {sprintf (fullpathname, "% C: <out of memory>", hookext-> logicaldrive ); return;} pathlen = filename. length + prefixlen; relatedfileobject = fileobject-> relatedfileobject; // only look at related file object if this is a relative name // If (fileobject-> filename. buffer [0]! = L' \ '& relatedfileobject-> filename. Length) {dbuplint ("relatedfileobject filename: % s", relatedfileobject-> filename); If (! Nt_success (Response (& relatedname, & relatedfileobject-> filename, true) {sprintf (fullpathname, "% C: <out of memory>", hookext-> logicaldrive ); rtlfreeansistring (& filename); return;} pathlen + = relatedname. length + 1;} If (fileobject-> deviceobject-> devicetype! = File_device_network_file_system) {sprintf (fullpathname, "% C:", hookext-> logicaldrive);} If (pathlen> = MAXPATHLEN) {strcat (fullpathname, "<Name Too Long>");} else {// now we can build the path name // fullpathname [pathlen] = 0; pathoffset = fullpathname + pathlen-filename. length; memcpy (pathoffset, filename. buffer, filename. length + 1); If (fileobject-> filename. buffer [0]! = L' \ '& relatedfileobject-> filename. length) {// copy the component, adding a slash separator // * (pathoffset-1) = '\'; pathoffset-= relatedname. length + 1; memcpy (pathoffset, relatedname. buffer, relatedname. length ); /// if we 've got to slashes at the front zap one // If (pathlen> 3 & fullpathname [2] = '\' & fullpathname [3] = '\\') {strcpy (fullpathname + 2, fullpathname + 3 );}}}}

The simplified function code above is only considered in the first case, that is, when the file is opened but the file is not yet opened.
At this time, the file name information is stored in the file object fileobject-> filename, and fileobject-> relatedfileobject-> filename,Fileobject-> filenameYesRelatedobjectBy parsing the two, the file name is combined.

Another code in the filemongetfullpath function body:

Filemongetfullpath {..................................................................... If (! Gotpath &&! Createpath) {filenameinfo = (callback) callback (nonpagedpool, MAXPATHLEN * sizeof (wchar); If (filenameinfo & filemonqueryfile (hookext-> filesystem, fileobject, filenameinformation, filenameinfo, (MAXPATHLEN-prefixlen-1) * sizeof (wchar) {fulluniname. length = (short) filenameinfo-> filenamelength; fulluniname. buffer = filenameinfo-> filename; If (nt_success (rtlunicodestringtoansis Tring (& filename, & fulluniname, true) {fullpathname [filename. length + prefixlen] = 0; If (hookext-> type = npfs) {strcpy (fullpathname, named_pipe_prefix);} else if (hookext-> type = msfs) {strcpy (fullpathname, mail_slot_prefix);} else if (fileobject-> deviceobject-> devicetype! = File_device_network_file_system) {sprintf (fullpathname, "% C:", hookext-> logicaldrive );} else {// no prefix for network devices //} memcpy (& fullpathname [prefixlen], filename. buffer, filename. length); gotpath = true; rtlfreeansistring (& filename); filename. buffer = NULL ;}} if (filenameinfo) exfreepool (filenameinfo );}...............................................................}

The above code is to handle another situation, that is, in other read/write requests, you can build an IRP Based on the intercepted fileobject and send it to the underlying layer to query the file name information. The entire process is easy to understand.

After clarifying these two contexts and analyzing the entire function, it is easy to understand the entire function code.
In the code, majorfunction = irp_mj_create_named_pipe
Majorfunction = irp_mj_create_mailslot is determined to identify the two communication methods between intercepted processes: the processing of the named pipe and the mail slot.

The weekend is coming. Have a good weekend. I hope to share my post with you after finishing the rest.

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.