"Undocumented windows 2000 secrets" translation --- Chapter 3 (1)

xiaoxiao2021-03-06  24

Chapter III Writing Kernel Mode Drivers

Translation: kendiv (fcczj@263.net)

Update:

Monday, February 07, 2005

Disclaimer: Please indicate the source and guarantee the integrity of the article, and all rights to the translation.

In the next chapter, we often access system resources that are only valid only in kernel mode. A large number of sample code is designed as kernel-mode driver routine. Therefore, it is necessary to develop basic knowledge of such software. Because I can't assume that all readers have this experience, I will briefly introduce the kernel mode driver programming, but this is only intended to use the Drive Development Wizard (on this book CD).

This chapter will also discuss the basic knowledge of WINDOWS 2000 Service Control Manager (SCM), including SCM how to load, control, and unload drivers at runtime, Resulting In Wonderfully Short Change-Build-Test Turnaround Cycles. The topic of this chapter may make people a little misunderstood, drive the word usually associated with the underlying software for control hardware. In fact, many kernel rules are doing these things every day. However, Windows 2000 driver hierarchy mode allows for more things than this. The kernel driver can complete any complex task. If they do not consider they run on a higher CPU privilege level and use different development interfaces, they are very like DLLs in user mode. Here, we will use this powerful development technology to detect the internal secrets of Windows 2000, using the kernel driver just like the spaceship from a small user mode to the Windows 2000 kernel.

Create a driver's skeleton

Even if you develop Win32 applications and library developers, you will feel like an absolute beginner when you write a kernel driver for the first time. This is because the code in kernel mode runs in a completely different operating system environment. WIN32 developers are only limited to several system components belonging to the Windows 2000 WIN32 subsystem. Other developers may write POSI or OS / 2 applications, and the surcharge of Windows 2000 is supported. Thanserviate Systems, Windows 2000 is like a chameleon - it can export different application development interfaces through these subsystems (previously mentioned) to simulate different operating systems. In contrast, the code of the kernel mode can see "real" Windows 2000 operating system. The interfaces they use can be called "final boundary." Of course, this is not to say that the kernel mode is completely getting rid of the subsystem. In the second chapter, we see that Win32k.sys is the branch of Win32 GUI and Window Manager in kernel mode, which places them in the kernel is for performance consideration. However, only a small portion of the API function collection exported by Win32k.sys appears in GDI32.DLL and user32.dll, which means that only this small part of the function can be used as a Win32 API function, so Win32K will never Just Win32 stepped into the foot of the kernel world, in fact, it should be seen as a high-performance core mode graphics engine.

Windows 2000 DDK (Device Driver Kit)

Since programming in kernel mode uses different system interfaces, the header files and libraries that are often used in Win32 programming will not be used in kernel mode. For Win32 development, Microsoft provides Platform Software Development Kit (SDK). The driving development of kernel mode is related to Windows 2000 Device Driver Kit (DDK). Together with the document, DDK provides special header files and import libraries, which are both interfaces that Windows 2000 kernel modules must be. After installed DDK, you should open Visual C / C , add DDK's path to the compiler and linker list of directories. Select ToolsàOptions in the main menu, and then click Directories. Select Include Files in the Directory Select drop-down list, then add the appropriate path to the DDK, as shown in Figure 3-1. By default, DDK will be installed into the / NTDDK directory, and the include file is in the / ntddk / inc subdirectory. It should be noted that the newly added path is placed above the original path, which will use the new header file or library. Figure 3-1 Add DDK header file path

Figure 3-2 Add DDK import library path

After adding the DDK header file, add the path to the warehouse with the same method. DDK contains two group import libraries, a group called Free (Release) Builds, another group is called Checked (Debug) Builds. The corresponding directory is: / NTDDK / LIBFRE / I386 and / NTDDK / LIBCHK / I386, see Figure 3-2.

DDK development environment is different from Win32 mode, and there are some obvious differences between the two:

l For Win32 programmers, the main header file is Windows.h. For kernel mode code, NTDDK.H should be used instead.

l The main entry point function is called Dirverentry (), and no longer WinMain () or main (). Listing 3-1 gives their prototypes.

l Cannot use some common Win32 types such as Byte, Word and DWord. DDK uses uchar, ushort, ulong, etc. However, it is easy to define the type you like, and a list 3-2 gives this example.

NTSTATUS DRIVERENTRY (PDRIVER_OBJECT PDRIVEROBJECT,

Punicode_String PusregistryPath);

Listing 3-1 Prototype of DriveRentry functions

TYPEDEF UCHAR BYTE, * PBYTE

Typedef ushort word, * pword;

Typedef Ulong DWORD, * PDWORD;

Listing 3-2 Define common Win32 data types

In addition, it is necessary to pay attention to the difference between the DDK used by Windows NT 4.0 and Windows 2000, there are three points to pay attention, as follows:

l By default, the main directory of Windows NT 4.0 DDK is called / DDK, and Windows 2000 DDK is called / NTDDK

l In Windows NT 4.0 DDK, the main header file NTDDK.H is under the main directory. In Windows 2000 DDK, this file is moved to the / NTDDK / DDK subdirectory.

l The path to the introduction library has also changed: lib / i386 / free becomes libfre / i386, lib / i386 / checked becomes libchk / i386. I don't know what the actual significance of this change in Microsoft, but for life, we still need to understand its change J.

Customizable driver wizard

The main difficulties in developing kernel drivers are that Visual C / C does not provide this type of engineering guide. Fortunately, MSDN has a series of good articles about Windows NT kernel-driven development, is Ruediger R.asche. Written in 1994-1995. The two articles (Asche 1995a, 1995B) details how to join the custom driver wizard in Visual C / C , these articles have given me a lot of help, although the output file of the original wizard cannot meet all my Demand, but this is a good start. The kernel drive wizard I provide will be based on the output file generated by the original wizard of RUEDiger ASCHE.

All source code I provide the drive wizard is located in the / src / w2k_wiz directory of the disc. By reading these codes, you will find it actually heading "SBS Windows 2000 Code Wizard". In fact, this is a general Windows 2000 program skeleton generator that produces a variety of programs, including Win32 DLL and applications. However, the profile in the CD has made certain modifications for kernel driver development. Basically, the wizard I provide is a file converter that reads a set of files, and then converts them according to some simple rules, and finally writes the result in another set of files. The input file is a template, and the output file is a C engineering file. By modifying the template file, the wizard can become a DLL wizard, and the like. 7 template files must be provided (if a one is lost, an error will occur):

l The file that extension is .tw is a Workspace template that will be saved as a project file for Visual Studio.dsw.

l The file extension is .tp is an engineering template, which will be saved as a .dsp file. Project files Because of the associated Workspace file reference, the project file also contains all configuration options for generating projects.

l Extended .TC, .th, .tr and .td files are C code files, which will eventually become corresponding .c, .h, .rc and .def files.

l The extension is the icon file, which will be saved directly as a .ico file.

These seven files are required for a new project. The .def file exports the API function from the DLL in an older style, but I prefer __declspec (dllexport) mode. Since the driver usually does not export functions, I omitted the .td template, resulting in the result, report an error at the beginning, the guide reports an error. I also omitted the resource script and Icon file, but the experience tells me that it is best to provide them. The conversion rules used are also very simple, only a short string replacement list. When scanning template files, the converter looks up the escape character starting with the% number. When it is found, it will determine what kind of action on the execution according to the original characters. Table 3-1 lists the validated escape characters.

There are several reference profiles in Table 3-1 --- W2k_wiz.ini. Example 3-1 gives its default settings. Before using the wizard, you should copy the w2k_wiz.exe, w2k_wiz.ini and all W2K_WIZ.T * template files in the disc / src / w2k_wiz / release directory to your hard drive, then edit the configuration file, will change the corresponding content For your own settings. You also need to modify include, Free, and Checked to match your DDK installation. If you use Visual C / C 6.0, you may not change the value of the root. If not, set it to your root directory of the project file. If the end ends with a reverse slope, it will be used as the default. In Example 3-1, its key value is: HKEY_CURRENT_USER / SOFTWARE / Microsofto / DevStudio / 6.0 / Directories, and WorkspaceDIR is used to store basic working directories. Type W2K_WIZ MyDriver to execute the wizard, which will create an engineering directory called MyDriver in the current directory, which stores the wizard MYDRIVER.DSW, MyDriver.d, MyDriver.c, MyDriver.h, MyDriver.rc and MyDriver. ICO file. If you specify a specific path, you will create this directory under the path you specified. Another legal command option is an asterisk, such as: w2k_wiz * mydriver. In this case, the wizard does not create an engineering directory in the current directory, but look for the default engineering root directory of Visual C / C maintenance, that is, where the root in W2K_WIZ.INI is poor.

W2K_WIZ.INI

;

08-27-2000

Sven B. Schreiber

SBS@orgon.com

[Settings]

Text =

Company =

Author =

Email =

Prefix =

INCLUDE = E: / NTDDK / INC

Free = E: / NTDDK / LIBFRE / I386

Checked = E: / NTDDK / LIBCHK / I386

Root = HKEY_CURRENT_UOT = HKEY_CURRENT_USER / SOFTWARE / Microsoft / DevStudio / 6.0 / Directories / Workspacedir

Example 3-1. Guided custom options

Running the drive wizard

Now, try this drive wizard. Example 3-2 gives the output after the W2K_WIZ * TestDRV under Windows 2000 console. This will create an engineering directory called TestDRV in the Visual C / C default engineering root directory.

Obviously, in addition to the.TD template converted to .def, the remaining conversion is successful. Because the guide generated driver skeleton does not need the .def file, it is not necessary to provide a .td template file. Now, open a new Workspace with Visual C / C , then you will find a new directory called TestDRV, which contains a Workspace file called TestDrv.dsw. This file can be opened correctly. Next, you can generate the configuration information of the project selection activity. The drive wizard is generated. DSP file provides the following two available configurations:

1. Win2k kernel-mode driver (debug)

2. Win2k kernel-mode driver (Release) By default, the debug configuration will be used to generate items, but you can choose from Visual C / C menu Build / Set Active Configuration at any time. Finally, you have to copy /src/common/include/drvinfo.h in the CD to your own header file directory. When you open TestDRV.RC, you should use text mode to open (as shown in Figure 3-3), because the file uses a complex macro definition from drvinfo.h, which leads to resource editing abnormal exit. . This error starts from Visual C / C 5.0 and has not been corrected in my impression. Unlike the editor, the resource compiler can properly process these macros.

Figure 3-3. Open TestDrv.c, TestDrv.h and TestDrv.rc in text mode

Now, all preparations have been made for the first time. In Example 3-3, I build DRIVER's release version by choosing a build / rebuild menu, which looks normally. By the way, the omitted number at the end of the first two lines means that I cut off the output of the build command.

The linker creates an executable named TestDrv.sys in the debug or release directory, depending on your generation configuration. Test Driver's release version is 5.5KB, its Debug version is 8KB. You can use the MFVDasm or Peview in this book CD to verify that TestDrv.sys contains valid code and data.

In-depth driver skeleton

Listing 3-3 shows the TestDrv.c of the wizard. TestDrv.h associated with it in Listing 3-4. In Listing 3-3, please note the and flags at the title. If the author and company name in W2K_WIZ.INI is correct, your own name and the corresponding company name will replace them.

// TestDrv.c

//

08-07-2000

// Copyright @ 2005

#define_testdrv_sys_

#include

#include "testdrv.h"

/ / =========================================================================================================================================================================================== ==================

// disclaimer

/ / =========================================================================================================================================================================================== ================= / *

This Software Is Provided "As IS" and Any Express or Implied

Warranties, Including, But Not Limited to, The Implied Warranties of

Merchantability and Fitness for a particular purpose are disclaimed.

In no Event shall the author Be Liable for Any

Direct, Indirect, Incidental, Special, Exemplary, or Consequential

DAMAGES (INCLUDING, But Not Limited to, Procurement of Substute

Goods or Services; Loss of Use, Data, or Business; Or Business

Interruption) However Caused and On Any THEORY OF LIABILITY,

WHETHER in Contract, Strict Liability, Or Tort (Including Negligence

Or OtherWise) Arising in Any Way Out of The Use of this Software,

Even if advised of the Possibility of Such Damage.

* /

/ / =========================================================================================================================================================================================== ==================

// Revision History

/ / =========================================================================================================================================================================================== ==================

/ *

08-07-2000v1.00 Original Version.

* /

/ / =========================================================================================================================================================================================== ==================

// Global Data

/ / =========================================================================================================================================================================================== ==================

PRESET_UNICODE_STRING (USDeviceName, CSTRING (DRV_DEVICE));

PRESET_UNICODE_STRING (ussymboliclinkname, cstring (drv_link));

PDEvice_Object GpDeviceObject = NULL;

PDEvice_CONText GPDeviceContext = NULL;

/ / =========================================================================================================================================================================================== ==================

// discardable functions

/ / =========================================================================================================================================================================================== ==================

NTSTATUS Driverinitialize (PDRIVER_OBJECT PDRIVEROBJECT,

Punicode_String PusregistryPath);

NTSTATUS DRIVERENTRY (PDRIVER_Object PDRIVEROBJECT, PUNICODE_STRING PUSREGISTRYPATH);

/ / -------------------------------------------------------------------------------------------- -----------------

#ifdef alloc_pragma

#pragma alloc_text (Init, DriverInitialize)

#pragma alloc_text (init, driverentry)

#ENDIF

/ / =========================================================================================================================================================================================== ==================

// Device Request Handler

/ / =========================================================================================================================================================================================== ==================

NTSTATUS DeviceDispatcher (PDevice_Context PDeviceContext,

PIRP PIRP)

{

PIO_STACK_LOCATION PISL;

DWORD DINFO = 0;

NTSTATUS NS = status_not_implement;

PISL = IOGETCURRENTIRPSTACKLOCATION (PIRP);

Switch (PISL-> Majorfunction)

{

Case IRP_MJ_CREATE:

Case IRP_MJ_CLEANUP:

Case IRP_MJ_CLOSE:

{

NS = status_success;

Break;

}

}

PIRP-> iostatus.status = ns;

PIRP-> iostatus.information = dinfo;

IOCOMPLETEREQUEST (PIRP, IO_NO_INCREMENT);

Return ns;

}

/ / =========================================================================================================================================================================================== ================= // Driver Request Handler

/ / =========================================================================================================================================================================================== ==================

NTSTATUS DRIVERDISPATCHER (PDEvice_Object PDeviceObject,

PIRP PIRP)

{

Return (pdeviceObject == gpDeviceObject

DEVICEDISPATCHER (GPDeviceContext, PIRP)

: Status_invalid_parameter_1);

}

/ / -------------------------------------------------------------------------------------------- -----------------

Void Driverunload (PDRIVER_Object PDRIVEROBJECT)

{

IdeleteSymbolicLink (& USSymbolicLinkName);

IodeleteDevice (GPDeviceObject);

Return;

}

/ / =========================================================================================================================================================================================== ==================

// Driver Initialization

/ / =========================================================================================================================================================================================== ================= NTSTATUS Driverinitialize (PDRIVER_Object PDRIVEROBJECT,

Punicode_String PusregistryPath)

{

PDEvice_Object PDeviceObject = NULL;

NTSTATUS NS = status_device_configuration_error;

IF ((ns = IocreateDevice) (PDRIVEROBJECT, DEVICE_CONTEXT_,

& USDeviceName, File_Device_custom,

0, False, & PDeviceObject))

== STATUS_SUCCESS)

{

IF ((NS = IOCREATESYMBOLICLICLICLINK (& USSymbolicLinkName,

& usDeviceName))

== STATUS_SUCCESS)

{

gpDeviceObject = pdeviceObject;

GPDeviceContext = PDEviceObject-> DeviceExtension;

GPDeviceContext-> PDRIVEROBJECT = PDRIVEROBJECT;

GPDeviceContext-> pdeviceObject = pDeviceObject;

}

Else

{

IodeleteDevice (PDEviceObject);

}

}

Return ns;

}

/ / -------------------------------------------------------------------------------------------- -----------------

NTSTATUS DRIVERENTRY (PDRIVER_OBJECT PDRIVEROBJECT,

Punicode_String PusregistryPath)

{

PDRIVER_DISPATCH * PPDD;

NTSTATUS NS = status_device_configuration_error;

IF ((NS = DriverInitialize))

== STATUS_SUCCESS)

{

PPDD = PDRIVEROBJECT-> Majorfunction;

PPDD [IRP_MJ_CREATE] =

PPDD [IRP_MJ_CREATE_NAMED_PIPE] =

PPDD [IRP_MJ_CLOSE] =

PPDD [IRP_MJ_READ] =

PPDD [IRP_MJ_WRITE] =

PPDD [IRP_MJ_QUERY_INFORMATION] =

PPDD [IRP_MJ_SET_INFORMATION] = PPDD [IRP_MJ_QUERY_EA] =

PPDD [IRP_MJ_SET_EA] =

PPDD [IRP_MJ_FLUSH_BUFFERS] =

PPDD [IRP_MJ_QUERY_VOLUME_INFORMATION] =

PPDD [IRP_MJ_SET_VOLUME_INFORMATION] =

PPDD [IRP_MJ_DIRECTORY_CONTROL] =

PPDD [IRP_MJ_FILE_SYSTEM_CONTROL] =

PPDD [IRP_MJ_DEVICE_CONTROL] =

PPDD [IRP_MJ_INTERNAL_DEVICE_CONTROL] =

PPDD [IRP_MJ_SHUTDOWN] =

PPDD [IRP_MJ_LOCK_CONTROL] =

PPDD [IRP_MJ_CLANUP] =

PPDD [IRP_MJ_CREATE_MAILSLOT] =

PPDD [IRP_MJ_QUERY_SECURITY] =

PPDD [IRP_MJ_SET_SECURITY] =

PPDD [IRP_MJ_POWER] =

PPDD [IRP_MJ_SYSTEM_CONTROL] =

PPDD [IRP_MJ_DEVICE_CHANGE] =

PPDD [IRP_MJ_QUERY_QUOTA] =

PPDD [IRP_MJ_SET_QUOTA] =

PPDD [IRP_MJ_PNP] = DriverDispatcher;

PDRIVEROBJECT-> Driverunload = Driverunload;

}

Return ns;

}

/ / =========================================================================================================================================================================================== ==================

// end of program

/ / =========================================================================================================================================================================================== ================== List 3-3. Source code for driver skeleton

// TestDrv.h

//

08-07-2000

// Copyright @ 2005

/ / =========================================================================================================================================================================================== ==================

// Program Identification

/ / =========================================================================================================================================================================================== ==================

#define DRV_BUILD 1

#define drv_version_high 1

#define DRV_VERSION_LOW 0

/ / -------------------------------------------------------------------------------------------- -----------------

#DEFINE DRV_DAY 07

#define DRV_MONTH 02

#define drv_year 2005

/ / -------------------------------------------------------------------------------------------- -----------------

// Customize these Settings by Editing the Configuration File

// d: /etc32/w2k_wiz.ini

#define drv_module TestDRV

#define drv_name

#define drv_company

#define DRV_AUTHOR

#define drv_email #define DRV_PREFIX

/ / =========================================================================================================================================================================================== ==================

//Header Files

/ / =========================================================================================================================================================================================== ==================

#include "drvinfo.h" // defines more drv_ * items

#ifndef _RC_pass_

/ / =========================================================================================================================================================================================== ==================

// constants

/ / =========================================================================================================================================================================================== ==================

#define file_device_custom 0x8000

/ / =========================================================================================================================================================================================== ================= // Structures

/ / =========================================================================================================================================================================================== ==================

Typedef struct _Device_context

{

PDRIVER_OBJECT PDRIVEROBJECT;

PDEvice_Object PDeviceObject;

}

Device_Context, * pdevice_context, ** ppDevice_context;

#define device_context_ sizeof (Device_Context)

#ENDIF / / #1ndef _RC_pass_

/ / =========================================================================================================================================================================================== ==================

// end of file

/ / =========================================================================================================================================================================================== ==================

Listing 3-4. Skull of the driver skeleton

........................to be continued........................ .

转载请注明原文地址:https://www.9cbs.com/read-59346.html

New Post(0)