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 Chapter 6 T N s Window g Hookin s Service m Syste

R CHAPTE S THI N I

+ Looking at system services under various operating systems + Examining the need for hooking system services s hook f o s type g Implementin +

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 set of functions (primitive or elaborate) provided by the . Application programming interfaces () enable developers to call several system services, di- dynami a f o m for e th n i s API s provide m syste g operatin e Th . indirectly r o y rectl link library (DLL) or a static compiler library. These APIs are often based on system d base y directl e ar s call I AP e th f o e Som . system g operatin e th y b d provide s service m syste e multipl g jlepene makin som n do d an , service m syste g correspondin a n o . services m syste o t s call y an e mak t no y ma s call I AP e th f o e som , Also . calls e servic In short, you do not need a one-to-one mapping between API functions and system services. Figure 6-1 demonstrates this in context of Windows NT. w Vie g Lon e Th : Services m Syste System services and the APIs calling these system services have come a long way . NT s Window o t S DO m fro System Services under DOS including ( l kerne S MS-DO e th f o t par e compris s service m syste , DOS r Unde f o m for e th n i s user o t e availabl e ar s service m syste e Thes . IO.SYS) d an S MSDOS.SY e appropriat e th g callin y b d invoke e b n ca s ISR ISRs). ( s Routine e Servic t Interrup interrupt handlers using the INT instruction. API functions, provided by compiler r Fo . interrupt) h 21 T IN (the s service m syste r fo r handle t interrup e th l cal , libraries example, to open a file, MS-DOS provides a system service for you have to 109 110 Part 11: Undocumented Windows NT

- reg L C e th n i k mas e attribut , register H A e th n i D Ox3 r numbe n functio e th y specif 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 function for this purpose.

System Services under Windows 3.x and 8 95/9 s Window Under Windows 3.x or Windows 95/98, the core system services take the form of m for e th n i d provide e ar s API e Th . code S DO e real-mod e som d an s DLL d an s VXD of dynamic link libraries. These dynamic link libraries call the system services to implement the APIs. For example, to open a file, applications call an API function a 1 cal , turn n i , APIs e Thes . OpenFiles a h suc CreateFilefJ r L Qo KERNEL32.DL m fro system service. T N s Window r unde s Service m Syste Under Windows NT, the NT executive (part of NTOSKRNL.EXE) provides core sys- tem services. These services are rather generic and primitive. Various APIs such as l cal , turn n i , APIs e Thes . DLLs f o m for e th n i d provide e ar X POSI d an , OS/2 , Win32 services provided by the NT executive. The name of the API function to call differs s i e servic m syste e sam e th h thoug n eve s subsystem t differen m fro g callin s user r fo l cal s application , API 2 Win3 e th m fro e fil a n ope o t , example r Fo . invoked ) open( e th l cal s application , API X POSI e th m fro e fil a n ope o t d an O CreateFile e servic m syste Q NtCreateFile e th l cal y ultimatel s application e thes f o h Bot . function . executive T N e th m fro Chapter 6: Hooking Windows NT System Services 111

Under Windows NT 3.51, the system services are provided by a kernel-mode component called NTOSKRNL.EXE. Most of the KERNEL32.DLL calls —such as — t managemen s object l kerne d an t managemen y memor o t d relate e thos are handled by these system services.The USER32 and GDI32 calls are han- dleseparata y db e subsystem process called CSRSS. Starting with Windows NT 4.0, Microsoft moved most of the functionality of CSRSS into a kernel- mode driver called WIN32K.SYS.The functionality moved into WIN32K.SYS is - sys e services.Thes m syste f o m for e th n i s application e th o t e availabl e mad - spe e ar y the e sinc s service m syste e nativ f o t par y trul t no e ar s service m te cific to the user interface and not used by all subsystems.This chapter and the . NTOSKRNL.EXE y b d provide s service m syste e th n o y onl s focu r chapte t nex

Need for Hooking System Services

Hooking represents a very common mechanism oTfntercepting a particular section e th f o r behavio e th g modifyin f o y wa l usefu a s provide g Hookin . code g executin f o operating system. Hooking can help the developer in several ways. Often develop- r rathe l cal I AP n a r o e servic m syste a k hoo o t w ho h wit e mor d concerne e ar s er than why to hook. Nevertheless, we examine the various possible situations in which the need to hook a system service arises. How hooking can help the devel- . sections g followin e th n i d explaine s i r ope e Occurrenc t a s Event g Trappin - mu a f o n creatio , (CreateFileO) e fil a f o n creatio e th s a h suc s event p tra s Developer tex (CreateMutex()), or Registry accesses (RegCreateKeyO) for specific purposes. n ca , synchronously , call e servic m syste r o I AP d event-relate r particula a g Hookin s kind e thes d fin l wil g monitorin m syste g doin s Application . events e thos p tra p hel - occur e th y b d triggere s interrupt s a t ac d coul s hook e Thes . invaluable g hookin f o rence of these events. A developer could write a routine to handle the occurrence of these events and take appropriate action. s Need r Use t Sui o t r Behavio m Syste g Modifyin - operat y modif n ca s hook e th g introducin y b l contro f o w flo l norma e th g Divertin ing system behavior. This enables the developer to change structures and con- text at the time of hooking - enough to induce new behavior. For example, you can . NtCreateFilee th g service m hookin Qsyste y b e fil e sensitiv a f o g openin e th t protec Although NTFS provides user-level security for files, this security is not available e undesirabl y an e hav t no s doe g hookin t tha e ensur d shoul u Yo . partitions T FA n o side effects on the operating system. Protecting modifications to Registry keys is T N s Window d 112Undocumente : 11 t Par

something easily doable when you hook the Registry system services. This has sev- eral applications, since little protection is provided for Registry settings created by applications. •- ' m Syste e th f o r Behavio e th g Studyin In 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 will s require y functionalit m syste g operatin d undocumente f o g Understandin . to e relat a lot of hacking, which goes hand in hand with hooking. Debugging - sticki e th g debu o t g hookin e system-servic f o e us e mak d coul s program x Comple n installatio e th h wit m proble a d ha e w , back s day w fe a , example r Fo . problems t es of a piece of software. We had difficulty creating folders and shortcuts for this ap- - pro n installatio e th t tha d figure y quickl e w , hook e systemwid a g Usin . plication s folder e th l instal o t e wher d indicate t tha e valu y Registr a r fo g lookin s wa m gra e NtQueryValueKeyth d hooke e W , . Qcall menu) t Star e th e b o t d happene h (whic t tha d create e W . for g lookin s wa m progra n installatio e th e valu e th d obtaine n the . problem r ou d solve d an e valu d an s Task c Specifi r fo a Dat e Performanc g Gettin Generating Statistics These tasks can prove very useful to those writing benchmarks and applications to g measurin n Eve . conditions c specifi r unde e performanc m syste e measur y criticall the frequency of certain system services becomes very easy with this type of hook- ing. Measuring file system performance by hooking the file system-related system . procedure s thi y exemplif s service Life without hooking is unthinkable for most Windows developers in today's e li s service m syste T N s Window . systems g operatin f o d worl d Microsoft-dominate - ex e prov n ca e thes k hoo o t y abilit e th g havin d an , universe T N e th f o r cente e th t a . handy y tremel Types of Hooks

The following sections explore two types of hooking. Kern el-Level Hooking s thi n I . driver e devic r o D VX a g writin y b g hookin l kernel-leve e achiev n ca u Yo f o e advantag e Th . hooked e ar l kerne e th y b d provide s function l essentia , method ______Chapter 6: Hooking Windows NT System Services____113 r monito n ca u yo h whic m fro e plac l centra e on t ge u yo t tha s i g hookin f o e typ s thi - dis e Th . call kernel-mode a r o l cal user-mode a f o t resul a s a g occurrin s event e th l cal e th f o s parameter e th r deciphe o t d nee u yo t tha s i d metho s thi f o e advantag , Also . undocumented e ar s service e thes s time y man e sinc , mode l kerne m fro d passe the data passed to the kernel-mode call might differ from the data passed in a user- o t s call e multipl g usin d implemente e b t migh l cal I AP l user-leve a , Also . call e mod the kernel. In this case, hooking becomes far more difficult. In general, this type of hooking is more difficult to achieve, but it can produce more rewarding results. User-Level Hooking . driver e devic r o D VX a m fro p hel e som h wit g hookin f o e typ s thi m perfor n ca u Yo 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. k hoo e th e writ o t y eas t i s make s Thi . expect o t s parameter e th w kno u yo , Therefore function. This type of hooking limits your field of vision to user mode only and . mode l kerne o t d exten t no s doe Implementations of Hooks

The following sections detail the implementation of hooks under various Microsoft platforms. DOS e routin r handle t interrup n a s a d implemente e ar s service m syste , world S DO e th n I (INT 2In). The compiler library routines typically call this interrupt handler to pro- vide an API function to the . It is trivial to hook this handler using the GetVect (INT 21h, AX=25h) and SetVect (Int 21h, AX=35h) services. Hence, hooking system services are fairly straightforward. DOS does not contain separate user and . modes l kerne Windows 3.x r compile e Th . DLLs n i d implemente e ar s service m syste , world x 3. s Window e th n I library routines represent stubs that jump to the DLL code (this is called dynamic linking of DLLs). Also, because the address space is common to all applications, hooking amounts to getting the address of that particular system service and changing a few bytes at that address. Changing of these bytes sometimes requires - . selectors f o g aliasin e simpl e th 114 Part 11: Undocumented Windows NT

Refer to the MSDN article in Microsoft Systems Journal (Vol. 9, No. 1) entitled, k ProcHoo r Ou h Wit n Functio ) Windows(tm t 16-bi y An r Monito d an k "Hoo DLL," by James Finnegan.

Windows 95 and 98 In the Windows 95/98 world, system services are implemented in a DLL as in Windows 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 is w fe a y modif y simpl u Yo . KERNEL32.DLL s a h suc L DL d share a k hoo o t y eas y fairl k hoo r you e writ d an k hoo o t t wan u yo e servic m syste e th f o t star e th t a s byte e cod y ma s byte e cod e th g Modifyin . memory d share n i d loade s i t tha L DL a n i n functio involve writing a VXD, because KERNEL32.DLL is loaded in the upper 2GB of the . system g operatin e th y b d protecte d an e spac s addres r Windows NT In the Windows NT world, system services are implemented in the kernel compo- , (Win32 s subsystem s variou y b d supporte s API e Th . (NTOSKRNL.EXE) T N f o t nen no doc- no is There . services m syste e thes g usin y b d implemente e ar ) POSIX d an , OS/2 l severa e ar e Ther mode. kernel from services system these hooking of way umented documented ways for hooking user-level API calls.

e MSDRefeth o Nt r article n Microsofti s Systems Journal entitled, "Learn System-Level Win32(r) Coding Techniques by Writing and API Spy Program," r Anothe o int L DL t 32-bi r You d "Loa d an , No.12) , (Vol.9 k Pietre t Mat y b Process's Address Space Using INJLIB,"by Jeffrey Richter (Vol.9, No.5). $ Refer to CyberSensor on http://www.cybermedia.co.in l kerne n i s service m syste T N f o g hookin g achievin f o y wa e on t presen l wil e W mode in this chapter. We also provide the code for this on the CD-ROM accompa- nying this book. s Service m Syste T N s Window Windows NT has been designed with several design goals in mind. Support for multiple (popular) APIs, extensibility, isolation of various APIs from each other, and security are some of the most important ones. The present design incorporates Chapter 6: Hooking Windows NT System Services 115

- sub X POSI e th , subsystem 2 Win3 e th , example r (fo s subsystem d protecte l severa system, and others) that reside in the user space isolated from each other. The NT - subsys e th l al o t t suppor e nativ s provide d an e mod l kerne e th n i s run e executiv o t e executiv T N e th y b d provide s service m syste T N e th e us s subsystem l Al . tems . functionality e cor r thei f o t mos t implemen 2 GDI3 d an , USER32 , KERNEL32 e th h wit k lin y the n whe , s Window g supportin s service m syste T N e th f o e existenc e th f o e unawar y completel e ar , DLLs the various Win32 calls they make. Similarly, POSIX clients using the POSIX API t wan y the t wha t ge o t s service m syste T N f o t se e sam e th s les r o e mor g usin p u d en r fo e interfac l fundamenta e th t represen s service m syste T N , Thus . kernel e th m fro any user-mode application or subsystem to the kernel. X CreateProcesss POSI call a n n whe r Qo applicatio Win32 a n whe , example r Fo application calls the fork() call, both ultimately call the NtCreateProcessQ system service from the NT executive. r Fo . mode l kerne e th n i y entirel n ru h whic , routines t represen s service m syste T N e th d considere e b n ca s service m syste T N , world x Uni e th h wit r familia e thos equivalent 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. The only 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 about - de e som n i m the o t d passe s parameter e th s cover d an s service m syste t differen 5 2 tail. You'll see from Appendix A that this is only the tip of the iceberg. In Windows 116 Part 11: Undocumented Windows NT

NT 3.51, OxC4 different system services exist, in Windows NT 4.0, OxD3 different s service m syste t differen 4 OxF , Beta-2 0 200 s Window n i d an , exist s service m syste exist. We deciphered the parameters of 90°/o of the system services. Prototypes for all these system services can be found in UNDOCNT.H on the CD-ROM included with this book. We also provide detailed documentation of some of the system services in Appendix A. In the following section, you will learn how to hook these system services. Hooking NT System Services

- op T N s Window e th n i d implemente e ar s Service m Syste T N w ho t a k loo t firs s Let' erating system. We also will discuss the exact mechanics of hooking an NT system e provid d an d involve s structure a dat l kerne e th e explor l we'l , addition n I . service sample code to aid hooking of system services.

D < E TH N O Check out hookdrv.c on the accompanying CD-ROM.

Implementation of a System Service in Windows NT e th n i d provide s i L NTOSKRN f o s service m syste e th o t e interfac e mod r use e Th - NT d calle L DL a n i t presen e ar s function r wrappe e Thes . functions r wrappe f o m for e mod l kerne e th o t h switc o t n instructio E 2 T IN e th e us s wrapper e Thes . DLL.DLL and execute the requested system service. The Win32 API functions (mainly in KERNEL32.DLL and ADVAPI32.DLL) use these wrappers for calling a system ser- o t d passe s parameter e th n o s validation s perform s function I AP 2 Win3 e Th . vice the API functions, and translates everything to Unicode. After this, the Win32 API - re e th o t g correspondin L NTDL n i n functio r wrappe e appropriat n a s call n functio 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 EDX o t r processo e th s change n instructio s Thi . instruction E 2 T IN e th s issue d an , register e th r fo d specifie r handle e th g executin s start r processo e th d an , mode l kerne e th INT 2E in the Interrupt Descriptor Table (TDT). The Windows NT executive sets up o t k stac e user-mod m fro s parameter e th s copie r handle E 2 T IN e Th . handler s thi kernel-mode stack. The base of the stack frame is identified by the contents of the Chapter 6: Hooking Windows NT System Services 117

EDX register. The INT 2E handler provided by NT Executive is internally called as KiSystemServiceQ. 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 address of the function to be executed for a given service ID. The INT 2Eh handler looks up - correspond e th s call d an r registe X EA n i d passe D I e servic e th n o d base e tabl s thi - an , Similarly . kernel e th n i s reside n functio h eac r fo e cod e Th . service m syste g in other table called the ParamTable (hereafter referred to as System Service Parameter Table [SSPT]) provides the handler with the number of parameter bytes to expect from a particular service.

e Tabl r Paramete d an e Tabl h Dispatc e Servic m Syste : 6-3 e Figur s Service m Syste T N g Hookin The easiest way to put a hook into the system services is to locate the System n functio e th e chang d an m syste g operatin e th y b d use e Tabl h Dispatc e Servic pointers to point to some other function inserted by the developer. You can do this - oper e th y b d protecte s i e tabl s thi e becaus r drive e devic e kernel-mod a m fro y onl ating system at the page table level. The page attribute for these pages is set so that only kernel-mode components can read from and write to this table. User-level ap- plications cannot read or write these memory locations. 118 Part 11: Undocumented Windows NT

E TH N I E TABL H DISPATC E SYSTEE TH G MSERVIC LOCATIN NTOSKR1ML d calle L NTOSKRN f o t lis t expor e th n i y entr d undocumente one s i e Ther KeServiceDescriptorTable(). This entry is the key to accessing the System Service Dispatch Table. The structure of this entry looks like this:

typedef struct ServiceDescriptorTable { PVOID ServiceTableBase; PVOID ServiceCounterTable(O); • j • ; NumberOfServices t in d unsigne PVOID ParamTableBase; }

Base address of the System Service Dispatch Table. Number of services described by ServiceTableBase. g operatin e th f o s build d checke n i y onl d use s i d fiel s Thi system and contains the counter of how many times each service in SSDT is called. This counter is updated by INT 2Eh handler (KiSystemService). Base address of the table containing the number of parame- ter bytes for each of the system services. h Eac . entries s NumberOfService n contai e ParamTableBas d an e ServiceTableBas m syste g correspondin e th g implementin n functio a o t r pointe a s represent y entr service. The following program provides an example of hooking system services, under Windows NT. The system service NtCreateFileQ hooks and the name of the file cre- - hook r fo e cod t inser o t u yo e encourag e W . invoked s get k hoo e th n whe s print d ate ing any other system service of choice. Note the proper places for inserting new hooks in the following code. e ar s binarie e sampl e th t tha g (assumin e sampl e th t ou y tr o t s step e th e ar e Her copied in C:\SAMPLES directory):

1. Run "instdrv hooksys c:\samples\hooksys.sys." This will install the hooksys.sys driver. The driver will hook the NtCreateFile system service. 2. Try to access the files on your hard disk. For each accessed file, the hooksys.sys will trap the call and display the name of the file accessed in the debugger window. These messages can be seen in SoftICE or using the debug message-capturing tool. #include "ntddk.h" #include "stdarg.h" " "stdio.h e #includ #include "hooksys.h" Chapter 6: Hooking Windows NT System Services 119 120 Part 11: Undocumented Windows NT Chapter 6: Hooking Windows NT System Services 121 T N s Window d 122Undocumente : 11 t Par

Summary In this chapter, we explored system services under DOS, Windows 3.x, Windows 95/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 used during the system call and the mechanism used for hooking Windows NT system services. The chapter concluded with an example that hooked the NtCreateFileQ . service m syste