undocumented windows nt - index-of.esindex-of.es/programming/programming - undocumented... · 2019....

15
Part Undocumented Windows NT CHAPTER 6 Hooking Windows NT System Services CHAPTER 7 Adding New System Services to the Windows NT Kernel CHAPTER 8 Local Procedure Call CHAPTER 9 Hooking Software Interrupts CHAPTER 10 Adding New Software Interrupts CHAPTER 11 Portable Executable File Format

Upload: others

Post on 28-Sep-2020

39 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Undocumented Windows NT - index-of.esindex-of.es/Programming/Programming - Undocumented... · 2019. 3. 3. · 112 Part 11: Undocumented Windows NT something easily doable when you

PartUndocumented Windows NT

CHAPTER 6Hooking Windows NT System Services

CHAPTER 7Adding New System Services to the

Windows NT KernelCHAPTER 8

Local Procedure CallCHAPTER 9

Hooking Software InterruptsCHAPTER 10

Adding New Software InterruptsCHAPTER 11

Portable Executable File Format

Page 2: Undocumented Windows NT - index-of.esindex-of.es/Programming/Programming - Undocumented... · 2019. 3. 3. · 112 Part 11: Undocumented Windows NT something easily doable when you

Chapter 6

Hooking Windows NTSystem Services

IN THIS CHAPTER

+ Looking at system services under various operating systems

+ Examining the need for hooking system services

+ Implementing types of hooks

THIS CHAPTER DISCUSSES hooking Windows NT system services. Before we begin,let's first review what we mean by a system service. A system service refers to a setof functions (primitive or elaborate) provided by the operating system. Applicationprogramming interfaces (APIs) enable developers to call several system services, di-rectly or indirectly. The operating system provides APIs in the form of a dynamiclink library (DLL) or a static compiler library. These APIs are often based on systemservices provided by the operating system. Some of the API calls are directly basedon a corresponding system service, and some jlepend on making multiple systemservice calls. Also, some of the API calls may not make any calls to system services.In short, you do not need a one-to-one mapping between API functions and systemservices. Figure 6-1 demonstrates this in context of Windows NT.

System Services: The Long ViewSystem services and the APIs calling these system services have come a long wayfrom DOS to Windows NT.

System Services under DOSUnder DOS, system services comprise part of the MS-DOS kernel (includingMSDOS.SYS and IO.SYS). These system services are available to users in the form ofInterrupt Service Routines (ISRs). ISRs can be invoked by calling the appropriateinterrupt handlers using the INT instruction. API functions, provided by compilerlibraries, call the interrupt handler for system services (the INT 21h interrupt). Forexample, to open a file, MS-DOS provides a system service for which you have to 109

Page 3: Undocumented Windows NT - index-of.esindex-of.es/Programming/Programming - Undocumented... · 2019. 3. 3. · 112 Part 11: Undocumented Windows NT something easily doable when you

110 Part 11: Undocumented Windows NT

specify the function number Ox3D in the AH register, attribute mask in the CL reg-ister, filename in the DS:DX register, as well as issue the INT 21h instruction.Compilers typically provide wrappers around this and provide a nice API functionfor this purpose.

System Services under Windows 3.x andWindows 95/98Under Windows 3.x or Windows 95/98, the core system services take the form ofVXDs and DLLs and some real-mode DOS code. The APIs are provided in the formof dynamic link libraries. These dynamic link libraries call the system services toimplement the APIs. For example, to open a file, applications call an API functionfrom KERNEL32.DLL such as OpenFileQ or CreateFilefJ. These APIs, in turn, cal1 asystem service.

System Services under Windows NTUnder Windows NT, the NT executive (part of NTOSKRNL.EXE) provides core sys-tem services. These services are rather generic and primitive. Various APIs such asWin32, OS/2, and POSIX are provided in the form of DLLs. These APIs, in turn, callservices provided by the NT executive. The name of the API function to call differsfor users calling from different subsystems even though the same system service isinvoked. For example, to open a file from the Win32 API, applications callCreateFileO and to open a file from the POSIX API, applications call the open()function. Both of these applications ultimately call the NtCreateFileQ system servicefrom the NT executive.

Page 4: Undocumented Windows NT - index-of.esindex-of.es/Programming/Programming - Undocumented... · 2019. 3. 3. · 112 Part 11: Undocumented Windows NT something easily doable when you

Chapter 6: Hooking Windows NT System Services 111

Under Windows NT 3.51, the system services are provided by a kernel-modecomponent called NTOSKRNL.EXE. Most of the KERNEL32.DLL calls —such asthose related to memory management and kernel objects management —are handled by these system services.The USER32 and GDI32 calls are han-dled by a separate subsystem process called CSRSS. Starting with WindowsNT 4.0, Microsoft moved most of the functionality of CSRSS into a kernel-mode driver called WIN32K.SYS.The functionality moved into WIN32K.SYS ismade available to the applications in the form of system services.These sys-tem services are not truly part of native system services since they are spe-cific to the user interface and not used by all subsystems.This chapter and thenext chapter focus only on the system services provided by NTOSKRNL.EXE.

Need for Hooking System ServicesHooking represents a very common mechanism oTfntercepting a particular sectionof executing code. Hooking provides a useful way of modifying the behavior of theoperating system. Hooking can help the developer in several ways. Often develop-ers are concerned more with how to hook a system service or an API call ratherthan why to hook. Nevertheless, we examine the various possible situations inwhich the need to hook a system service arises. How hooking can help the devel-oper is explained in the following sections.

Trapping Events at OccurrenceDevelopers trap events such as the creation of a file (CreateFileO), creation of a mu-tex (CreateMutex()), or Registry accesses (RegCreateKeyO) for specific purposes.Hooking a particular event-related API or system service call, synchronously, canhelp trap those events. Applications doing system monitoring will find these kindsof hooking invaluable. These hooks could act as interrupts triggered by the occur-rence of these events. A developer could write a routine to handle the occurrence ofthese events and take appropriate action.

Modifying System Behavior to Suit User NeedsDiverting the normal flow of control by introducing the hooks can modify operat-ing system behavior. This enables the developer to change data structures and con-text at the time of hooking - enough to induce new behavior. For example, you canprotect the opening of a sensitive file by hooking the NtCreateFileQ system service.Although NTFS provides user-level security for files, this security is not availableon FAT partitions. You should ensure that hooking does not have any undesirableside effects on the operating system. Protecting modifications to Registry keys is

Page 5: Undocumented Windows NT - index-of.esindex-of.es/Programming/Programming - Undocumented... · 2019. 3. 3. · 112 Part 11: Undocumented Windows NT something easily doable when you

112 Part 11: Undocumented Windows NT

something easily doable when you hook the Registry system services. This has sev-eral applications, since little protection is provided for Registry settings created byapplications. •- '

Studying the Behavior of the SystemIn order to get a better idea of the internal workings of the operating system, study-ing the behavior of the system is something most debuggers or system hackers willrelate to. Understanding of undocumented operating system functionality requiresa lot of hacking, which goes hand in hand with hooking.

DebuggingComplex programs could make use of system-service hooking to debug the sticki-est problems. For example, a few days back, we had a problem with the installationof a piece of software. We had difficulty creating folders and shortcuts for this ap-plication. Using a systemwide hook, we quickly figured that the installation pro-gram was looking for a Registry value that indicated where to install the folders(which happened to be the Start menu). We hooked the NtQueryValueKeyQ call,then obtained the value the installation program was looking for. We created thatvalue and solved our problem.

Getting Performance Data for Specific Tasks andGenerating StatisticsThese tasks can prove very useful to those writing benchmarks and applications tocritically measure system performance under specific conditions. Even measuringthe frequency of certain system services becomes very easy with this type of hook-ing. Measuring file system performance by hooking the file system-related systemservices exemplify this procedure.

Life without hooking is unthinkable for most Windows developers in today'sMicrosoft-dominated world of operating systems. Windows NT system services lieat the center of the NT universe, and having the ability to hook these can prove ex-tremely handy.

Types of HooksThe following sections explore two types of hooking.

Kern el-Level HookingYou can achieve kernel-level hooking by writing a VXD or device driver. In thismethod, essential functions provided by the kernel are hooked. The advantage of

Page 6: Undocumented Windows NT - index-of.esindex-of.es/Programming/Programming - Undocumented... · 2019. 3. 3. · 112 Part 11: Undocumented Windows NT something easily doable when you

______________Chapter 6: Hooking Windows NT System Services____113

this type of hooking is that you get one central place from which you can monitorthe events occurring as a result of a user-mode call or a kernel-mode call. The dis-advantage of this method is that you need to decipher the parameters of the callpassed from kernel mode, since many times these services are undocumented. Also,the data passed to the kernel-mode call might differ from the data passed in a user-mode call. Also, a user-level API call might be implemented using multiple calls tothe kernel. In this case, hooking becomes far more difficult. In general, this type ofhooking is more difficult to achieve, but it can produce more rewarding results.

User-Level HookingYou can perform this type of hooking with some help from a VXD or device driver.In this method, the functions provided by the user-mode DLLs are hooked. The ad-vantage of this method is that these functions are usually well documented.Therefore, you know the parameters to expect. This makes it easy to write the hookfunction. This type of hooking limits your field of vision to user mode only anddoes not extend to kernel mode.

Implementations of HooksThe following sections detail the implementation of hooks under various Microsoftplatforms.

DOSIn the DOS world, system services are implemented as an interrupt handler routine(INT 2In). The compiler library routines typically call this interrupt handler to pro-vide an API function to the programmer. It is trivial to hook this handler using theGetVect (INT 21h, AX=25h) and SetVect (Int 21h, AX=35h) services. Hence, hookingsystem services are fairly straightforward. DOS does not contain separate user andkernel modes.

Windows 3.xIn the Windows 3.x world, system services are implemented in DLLs. The compilerlibrary routines represent stubs that jump to the DLL code (this is called dynamiclinking of DLLs). Also, because the address space is common to all applications,hooking amounts to getting the address of that particular system service andchanging a few bytes at that address. Changing of these bytes sometimes requiresthe simple aliasing of selectors. -

Page 7: Undocumented Windows NT - index-of.esindex-of.es/Programming/Programming - Undocumented... · 2019. 3. 3. · 112 Part 11: Undocumented Windows NT something easily doable when you

114 Part 11: Undocumented Windows NT

Refer to the MSDN article in Microsoft Systems Journal (Vol. 9, No. 1) entitled,"Hook and Monitor Any 16-bit Windows(tm) Function With Our ProcHookDLL," by James Finnegan.

Windows 95 and 98In the Windows 95/98 world, system services are implemented in a DLL as inWindows 3.1. However, under Windows 95/98, all 32-bit applications run in sepa-rate address spaces. Because of this, you cannot easily hook any unshared DLL. It isfairly easy to hook a shared DLL such as KERNEL32.DLL. You simply modify a fewcode bytes at the start of the system service you want to hook and write your hookfunction in a DLL that is loaded in shared memory. Modifying the code bytes mayinvolve writing a VXD, because KERNEL32.DLL is loaded in the upper 2GB of theaddress space and protected by the operating system.

r

Windows NTIn the Windows NT world, system services are implemented in the kernel compo-nent of NT (NTOSKRNL.EXE). The APIs supported by various subsystems (Win32,OS/2, and POSIX) are implemented by using these system services. There is no doc-umented way of hooking these system services from kernel mode. There are severaldocumented ways for hooking user-level API calls.

Refer to the MSDN articles in Microsoft Systems Journal entitled, "LearnSystem-Level Win32(r) Coding Techniques by Writing and API Spy Program,"by Matt Pietrek (Vol.9, No.12), and "Load Your 32-bit DLL into AnotherProcess's Address Space Using INJLIB,"by Jeffrey Richter (Vol.9, No.5). $

Refer to CyberSensor on http://www.cybermedia.co.in

We will present one way of achieving hooking of NT system services in kernelmode in this chapter. We also provide the code for this on the CD-ROM accompa-nying this book.

Windows NT System ServicesWindows NT has been designed with several design goals in mind. Support formultiple (popular) APIs, extensibility, isolation of various APIs from each other,and security are some of the most important ones. The present design incorporates

Page 8: Undocumented Windows NT - index-of.esindex-of.es/Programming/Programming - Undocumented... · 2019. 3. 3. · 112 Part 11: Undocumented Windows NT something easily doable when you

Chapter 6: Hooking Windows NT System Services 115

several protected subsystems (for example, the Win32 subsystem, the POSIX sub-system, and others) that reside in the user space isolated from each other. The NTexecutive runs in the kernel mode and provides native support to all the subsys-tems. All subsystems use the NT system services provided by the NT executive toimplement most of their core functionality.

Windows programmers, when they link with the KERNEL32, USER32, and GDI32DLLs, are completely unaware of the existence of the NT system services supportingthe various Win32 calls they make. Similarly, POSIX clients using the POSIX APIend up using more or less the same set of NT system services to get what they wantfrom the kernel. Thus, NT system services represent the fundamental interface forany user-mode application or subsystem to the kernel.

For example, when a Win32 application calls CreateProcessQ or when a POSIXapplication calls the fork() call, both ultimately call the NtCreateProcessQ systemservice from the NT executive.

NT system services represent routines, which run entirely in the kernel mode. Forthose familiar with the Unix world, NT system services can be considered theequivalent of system calls in Unix.

Figure 6-2: A caller program invoking an NT system service

Currently, Windows NT system services are not completely documented. Theonly place where you can find some documentation regarding the NT system ser-vices is on Windows NT DDK CD-ROMs from Microsoft. The DDK discusses about25 different system services and covers the parameters passed to them in some de-tail. You'll see from Appendix A that this is only the tip of the iceberg. In Windows

Page 9: Undocumented Windows NT - index-of.esindex-of.es/Programming/Programming - Undocumented... · 2019. 3. 3. · 112 Part 11: Undocumented Windows NT something easily doable when you

116 Part 11: Undocumented Windows NT

NT 3.51, OxC4 different system services exist, in Windows NT 4.0, OxD3 differentsystem services exist, and in Windows 2000 Beta-2, OxF4 different system servicesexist.

We deciphered the parameters of 90°/o of the system services. Prototypes for allthese system services can be found in UNDOCNT.H on the CD-ROM included withthis book. We also provide detailed documentation of some of the system servicesin Appendix A.

In the following section, you will learn how to hook these system services.

Hooking NT System ServicesLet's first look at how NT System Services are implemented in the Windows NT op-erating system. We also will discuss the exact mechanics of hooking an NT systemservice. In addition, we'll explore the kernel data structures involved and providesample code to aid hooking of system services.

ON THE <D Check out hookdrv.c on the accompanying CD-ROM.

Implementation of a System Service inWindows NTThe user mode interface to the system services of NTOSKRNL is provided in theform of wrapper functions. These wrapper functions are present in a DLL called NT-DLL.DLL. These wrappers use the INT 2E instruction to switch to the kernel modeand execute the requested system service. The Win32 API functions (mainly inKERNEL32.DLL and ADVAPI32.DLL) use these wrappers for calling a system ser-vice. The Win32 API functions performs validations on the parameters passed tothe API functions, and translates everything to Unicode. After this, the Win32 APIfunction calls an appropriate wrapper function in NTDLL corresponding to the re-quired service. Each system service in NTOSKRNL is identified by the Service ID.The wrapper function in NTDLL fills in the service id of the requested system ser-vice in the EAX register, fills in the pointer to stack frame of the parameters in EDXregister, and issues the INT 2E instruction. This instruction changes the processor tothe kernel mode, and the processor starts executing the handler specified for theINT 2E in the Interrupt Descriptor Table (TDT). The Windows NT executive sets upthis handler. The INT 2E handler copies the parameters from user-mode stack tokernel-mode stack. The base of the stack frame is identified by the contents of the

Page 10: Undocumented Windows NT - index-of.esindex-of.es/Programming/Programming - Undocumented... · 2019. 3. 3. · 112 Part 11: Undocumented Windows NT something easily doable when you

Chapter 6: Hooking Windows NT System Services 117

EDX register. The INT 2E handler provided by NT Executive is internally called asKiSystemServiceQ.

During the initialization of NTOSKRNL, it creates a function table, hereafter re-ferred to as the System Service Dispatch Table (SSDT), for different services pro-vided by NTOSKRNL (see Figure 6-3). Each entry in the table contains the addressof the function to be executed for a given service ID. The INT 2Eh handler looks upthis table based on the service ID passed in EAX register and calls the correspond-ing system service. The code for each function resides in the kernel. Similarly, an-other table called the ParamTable (hereafter referred to as System Service ParameterTable [SSPT]) provides the handler with the number of parameter bytes to expectfrom a particular service.

Figure 6-3: System Service Dispatch Table and Parameter Table

Hooking NT System ServicesThe easiest way to put a hook into the system services is to locate the SystemService Dispatch Table used by the operating system and change the functionpointers to point to some other function inserted by the developer. You can do thisonly from a kernel-mode device driver because this table is protected by the oper-ating system at the page table level. The page attribute for these pages is set so thatonly kernel-mode components can read from and write to this table. User-level ap-plications cannot read or write these memory locations.

Page 11: Undocumented Windows NT - index-of.esindex-of.es/Programming/Programming - Undocumented... · 2019. 3. 3. · 112 Part 11: Undocumented Windows NT something easily doable when you

118 Part 11: Undocumented Windows NT

LOCATING THE SYSTEM SERVICE DISPATCH TABLE IN THENTOSKR1MLThere is one undocumented entry in the export list of NTOSKRNL calledKeServiceDescriptorTable(). This entry is the key to accessing the System ServiceDispatch Table. The structure of this entry looks like this:

typedef struct ServiceDescriptorTable {PVOID S e r v i c e T a b l e B a s e ;P V O I D S e r v i c e C o u n t e r T a b l e ( O ) ; • j •unsigned int N u m b e r O f S e r v i c e s ;PVOID P a r a m T a b l e B a s e ;

}

ServiceTableBase and ParamTableBase contain NumberOfServices entries. Eachentry represents a pointer to a function implementing the corresponding systemservice.

The following program provides an example of hooking system services, underWindows NT. The system service NtCreateFileQ hooks and the name of the file cre-ated prints when the hook gets invoked. We encourage you to insert code for hook-ing any other system service of choice. Note the proper places for inserting newhooks in the following code.

Here are the steps to try out the sample (assuming that the sample binaries arecopied in C:\SAMPLES directory):

1. Run "instdrv hooksys c:\samples\hooksys.sys." This will install thehooksys.sys driver. The driver will hook the NtCreateFile system service.

2. Try to access the files on your hard disk. For each accessed file, thehooksys.sys will trap the call and display the name of the file accessed inthe debugger window. These messages can be seen in SoftICE or using thedebug message-capturing tool.

#include "ntddk.h"#include "s tdarg.h"#include "s td io .h "#include "hooksys .h "

Base address of the System Service Dispatch Table.

Number of services described by ServiceTableBase.

This field is used only in checked builds of the operatingsystem and contains the counter of how many times eachservice in SSDT is called. This counter is updated by INT 2Ehhandler (KiSystemService).Base address of the table containing the number of parame-ter bytes for each of the system services.

Page 12: Undocumented Windows NT - index-of.esindex-of.es/Programming/Programming - Undocumented... · 2019. 3. 3. · 112 Part 11: Undocumented Windows NT something easily doable when you

Chapter 6: Hooking Windows NT System Services 119

Page 13: Undocumented Windows NT - index-of.esindex-of.es/Programming/Programming - Undocumented... · 2019. 3. 3. · 112 Part 11: Undocumented Windows NT something easily doable when you

120 Part 11: Undocumented Windows NT

Page 14: Undocumented Windows NT - index-of.esindex-of.es/Programming/Programming - Undocumented... · 2019. 3. 3. · 112 Part 11: Undocumented Windows NT something easily doable when you

Chapter 6: Hooking Windows NT System Services 121

Page 15: Undocumented Windows NT - index-of.esindex-of.es/Programming/Programming - Undocumented... · 2019. 3. 3. · 112 Part 11: Undocumented Windows NT something easily doable when you

122 Part 11: Undocumented Windows NT

SummaryIn this chapter, we explored system services under DOS, Windows 3.x, Windows95/98, and Windows NT. We discussed the need for hooking these system services.We discussed kernel- and user-lever hooks. We discussed the data structures usedduring the system call and the mechanism used for hooking Windows NT systemservices. The chapter concluded with an example that hooked the NtCreateFileQsystem service.