Search This Blog

Monday, 15 September 2014

WinDbg : the !object Command & It's Usage

WinDbg : !object

The NT Kernel tries to maintain an object based environment. A core set of objects are exposed which are used by the NT Executive. A set of functions are also provided to act upon these objects.  The NT Executive uses these objects, to create even more complex objects, many of which are available to the user.

Note: The NT Kernel does not depend on the Object Manager (which forms part of the Executive) to manage the kernel defined object types.

Kernel Objects are of the following two types:

Dispatcher Objects : These are used to control the synchronization and dispatching of system threads. Examples include thread, event, timer, mutex etc. 

Control Objects : These objects affect the operation of Kernel-mode code, but do not affect synchronization or dispatching. Examples include Interrupt objects, process objects, APC and DPC objects etc.

Lets have a look at the list of kernel objects we can wait on in Windows. It is stored in an enum.


kd> dt nt!_KOBJECTS
   EventNotificationObject = 0n0
   EventSynchronizationObject = 0n1
   MutantObject = 0n2
   ProcessObject = 0n3
   QueueObject = 0n4
   SemaphoreObject = 0n5
   ThreadObject = 0n6
   GateObject = 0n7
   TimerNotificationObject = 0n8
   TimerSynchronizationObject = 0n9
   Spare2Object = 0n10
   Spare3Object = 0n11
   Spare4Object = 0n12
   Spare5Object = 0n13
   Spare6Object = 0n14
   Spare7Object = 0n15
   Spare8Object = 0n16
   Spare9Object = 0n17
   ApcObject = 0n18
   DpcObject = 0n19
   DeviceQueueObject = 0n20
   EventPairObject = 0n21
   InterruptObject = 0n22
   ProfileObject = 0n23
   ThreadedDpcObject = 0n24
   MaximumKernelObject = 0n25


An Object, in NT, is an opaque data structure, implemented, maintained and manipulated by the NT executive. Each such object, has a set of operations defined for it, example : 
  • Create an instance of the object
  • Delete a created instance of the object
  • Wait On an object instance for it to become signaled.
  • Signal an object instance.
The object manager provides us with :
  • A global naming hierarchy, much like that used in file systems.
  • Methods to create and delete object instances.
  • Methods to add security restrictions on objects.
  • Maintain reference counts for object instances.
  • Add new object types dynamically to the the system.
Note: The Object manager does not concern itself with the internal data structure of the object.  the object structure contains a header and then a body.

kd> dt nt!_OBJECT_HEADER
   +0x000 PointerCount     : Int4B
   +0x004 HandleCount      : Int4B
   +0x004 NextToFree       : Ptr32 Void
   +0x008 Lock             : _EX_PUSH_LOCK
   +0x00c TypeIndex        : UChar
   +0x00d TraceFlags       : UChar
   +0x00e InfoMask         : UChar
   +0x00f Flags            : UChar
   +0x010 ObjectCreateInfo : Ptr32 _OBJECT_CREATE_INFORMATION
   +0x010 QuotaBlockCharged : Ptr32 Void
   +0x014 SecurityDescriptor : Ptr32 Void

   +0x018 Body             : _QUAD

The global namespace maintained by the object manager contains all named objects in the system. The object name space is modeled like an inverted tree (much like a file system does) and the global root directory for this tree is called "\". This namespace is initialized during system boot up.

NT Executive can create sub-directories under root and create instances of already defined object types. 

Lets try to parse the object manager through the debugger. The !object extension command is extremely helpful in this case.


kd> !object \


Object: 874010e8  Type: (839b7e90) Directory
    ObjectHeader: 874010d0 (new version)
    HandleCount: 0  PointerCount: 42
    Directory Object: 00000000  Name: \

Hash Address Type Name
---- ------- ---- ----
0 8740bbe0 Directory ArcName
8470c9f0 Device Ntfs
1 84ccfde8 ALPC Port SeLsaCommandPort
83a2b658 Event UniqueInteractiveSessionIdEvent
3 87408d10 Key \REGISTRY
4 83a295f8 ALPC Port PowerPort
5 84f2bf00 ALPC Port ThemeApiPort
9 8745d920 Directory NLS
10 87405df0 SymbolicLink DosDevices
12 84f319a8 ALPC Port UxSmsApiPort
13 84938038 ALPC Port SeRmCommandPort
14 84d66380 Event LanmanServerAnnounceEvent
8756d6e0 SymbolicLink Dfs
8744a360 Directory UMDFCommunicationPorts
16 8744cf58 Directory Driver
18 846fd4d0 Device clfs
19 8740f030 Directory Device
20 8b21e580 Directory Windows
84f03810 ALPC Port MmcssApiPort
849056e0 Event CsrSbSyncEvent
21 8b249bc8 Directory Sessions
84cebb38 Event SAM_SERVICE_STARTED
22 8b2487f8 Directory RPC Control
84958048 ALPC Port SmApiPort
23 95e0ee30 Directory BaseNamedObjects
874054c0 Directory KernelObjects
83a16038 ALPC Port PowerMonitorPort
24 87408f58 Directory GLOBAL??
87468330 Directory FileSystem
25 84d169c0 Event DSYSDBG.Debug.Trace.Memory.208
95ee6318 Section LsaPerformance
26 84d8da18 ALPC Port SmSsWinStationApiPort
87405b80 Directory ObjectTypes
27 8740ae38 Directory Security
30 851c9c20 ALPC Port AELPort
31 875dbd70 SymbolicLink SystemRoot
32 87405aa8 Directory Callback
33 84c28298 Event UniqueSessionIdEvent
84bcd6b8 Event EFSInitEvent
35 8b265108 Directory KnownDlls
This displays all the object types with the hierarchy they are in the name space. So see a sub-tree we can give it's path as well. E.g. Drivers.

kd> !object \Driver
Object: 8744cf58  Type: (839b7e90) Directory
    ObjectHeader: 8744cf40 (new version)
    HandleCount: 0  PointerCount: 87
    Directory Object: 874010e8  Name: Driver

Hash Address Type Name
---- ------- ---- ----
0 8470c4a0 Driver KSecDD
8474c3b8 Driver NDIS
8494b878 Driver Beep
8492d3b0 Driver rdpbus
1 847bfa58 Driver storflt
848df5d0 Driver SynthVid
848de030 Driver mouclass
2 8475c3b8 Driver KSecPkg
3 848a2db8 Driver kbdclass
4 839e87f0 Driver msisadrv
846aa940 Driver vmbus
8494b980 Driver VgaSave
84be2e28 Driver NDProxy
5 846ecdb8 Driver mountmgr
6 8474bb98 Driver pcw
8 85029960 Driver PEAUTH
846ec770 Driver atapi
847ddc38 Driver hwpolicy
8490c438 Driver blbdrive
9 846aae90 Driver volmgrx
10 848d7188 Driver Psched
11 84904600 Driver Win32k
846f8970 Driver amdxata
84981960 Driver mouhid
12 848d23a8 Driver tunnel
848e92e0 Driver netvsc
8492b4f0 Driver RasSstp
84949dc8 Driver swenum
13 8.48E+34 Driver HTTP
848816b0 Driver RDPCDD
8.49E+303 Driver RasPppoe
14 848903b8 Driver TermDD
15 848e8c20 Driver fdc
848cf150 Driver VMBusHID
84931f38 Driver Rasl2tp
16 8470c5e8 Driver CNG
8488ce38 Driver RDPREFMP
17 84951f38 Driver umbus
8491b1c0 Driver s3cap
18 84837de0 Driver secdrv
83a42da8 Driver ACPI_HAL
83a42670 Driver WMIxWDM
83a51338 Driver CLFS
848de250 Driver Serenum
8492ea18 Driver PptpMiniport
19 8.47E+102 Driver storvsc
847bf7b8 Driver spldr
21 8509d080 Driver tcpipreg
848d80c0 Driver NetBT
22 8484f4e0 Driver RDPENCDD
848a4030 Driver cdrom
84a515f0 Driver mssmbios
23 84f34b90 Driver rspndr
84856a80 Driver tdx
84967680 Driver WfpLwf
24 84fd1160 Driver mpsdrv
847613b8 Driver Tcpip
847ab530 Driver fvevol
25 839b7580 Driver 0000149
84307240 Driver volmgr
847c4d48 Driver volsnap
84891948 Driver nsiproxy
26 849194d0 Driver intelppm
27 84f38158 Driver lltdio
84890660 Driver Wanarpv6
28 848a4778 Driver Null
84a51b38 Driver discache
29 839e8508 Driver pci
847dd9a8 Driver Disk
848d6c40 Driver CSC
30 84307928 Driver partmgr
849134a0 Driver Serial
84932188 Driver NdisTapi
848da530 Driver NdisWan
32 852541a0 Driver MYFAULT
839ca1a0 Driver Wdf01000
842b71c8 Driver ACPI
33 83a31c18 Driver PnpManager
84964d08 Driver flpydisk
34 842fc318 Driver vdrvroot
848a4cf0 Driver AFD
84915750 Driver CompositeBus
36 846aa838 Driver intelide
847aa4c0 Driver rdyboost
848cf790 Driver i8042prt
849316b0 Driver RasAgileVpn
Strangely, we do not see the name of NTFS, one of the mandatory drivers for Windows, in this list. The reason is that, NTFS is a file system, and Windows treats file systems separately. Infact, none of the file system drivers are to be seen here. They are all in the \Filesystem hive. Lets have a look:

kd> !object \Filesystem
Object: 87468330  Type: (839b7e90) Directory
    ObjectHeader: 87468318 (new version)
    HandleCount: 0  PointerCount: 27
    Directory Object: 874010e8  Name: FileSystem

Hash Address Type Name
---- ------- ---- ----
0 846d9b98 Driver srvnet
8470cb18 Driver Ntfs
1 84913250 Driver NetBIOS
3 84755378 Device ExFatRecognizer
5 846edac8 Driver rdbss
10 84fd3600 Driver bowser
15 849d7ce8 Driver Msfs
17 84c39a88 Driver mrxsmb
18 84750378 Device UdfsCdRomRecognizer
19 84fe6530 Driver srv
23 848d6ea8 Driver DfsC
24 848f2718 Driver srv2
847bf570 Driver Mup
842b41b8 Driver RAW
25 8488c2d0 Driver Npfs
8474e360 Driver Fs_Rec
26 8744eb50 Directory Filters
30 84fd1a88 Driver mrxsmb10
32 84753378 Device FatCdRomRecognizer
8474f378 Device CdfsRecognizer
846f8878 Driver FltMgr
33 84fd5848 Driver mrxsmb20
34 84752378 Device FatDiskRecognizer
8470d578 Driver FileInfo
36 84d4b030 Driver luafv
84751378 Device UdfsDiskRecognizer

To see details of a named object we can give the name of the object. Example for details of the C: (which is a symbolic link) we can use the following command.

kd> !object \Global??\c:
Object: 875dbd28  Type: (839b7dc8) SymbolicLink
    ObjectHeader: 875dbd10 (new version)
    HandleCount: 0  PointerCount: 1
    Directory Object: 87408f58  Name: C:
    Target String is '\Device\HarddiskVolume2'
    Drive Letter Index is 3 (C:)

We had discussed object types in a previous section, to see all the object types currently supported we can use:

kd> !object \ObjectTypes
Object: 87405b80  Type: (839b7e90) Directory
    ObjectHeader: 87405b68 (new version)
    HandleCount: 0  PointerCount: 44
    Directory Object: 874010e8  Name: ObjectTypes

Hash Address Type Name
---- ------- ---- ----
0 83a28c58 Type TpWorkerFactory
839b7e90 Type Directory
1 83a25418 Type Mutant
839b78b0 Type Thread
3 846ff870 Type FilterCommunicationPort
4 83a31eb0 Type TmTx
5 83a28ac8 Type Controller
6 83a43f78 Type EtwRegistration
7 83a28f78 Type Profile
83a33420 Type Event
839b7f58 Type Type
9 83a31b50 Type Section
83a2f3f8 Type EventPair
839b7dc8 Type SymbolicLink
10 83a28d20 Type Desktop
839b77e8 Type UserApcReserve
11 83a43eb0 Type EtwConsumer
83a26350 Type Timer
12 83a287a8 Type File
83a28de8 Type WindowStation
14 8474b298 Type PcwObject
15 83a31d20 Type TmEn
16 83a28938 Type Driver
18 83a42528 Type WmiGuid
83a28eb0 Type KeyedEvent
19 83a28a00 Type Device
839b7b80 Type Token
20 83a298f0 Type ALPC Port
839af878 Type DebugObject
21 83a28870 Type IoCompletion
22 839b7978 Type Process
23 83a31de8 Type TmRm
24 83a28b90 Type Adapter
26 83a16f18 Type PowerRequest
83a2d388 Type Key
28 839b7a40 Type Job
30 83a317b0 Type Session
83a31f78 Type TmTm
31 839afef8 Type IoCompletionReserve
32 83a25350 Type Callback
33 846ec158 Type FilterConnectionPort
34 83a26418 Type Semaphore




NT maintains a data structure called the OBJECT_TYPE which contains all relevant information about any object. We will be using the dt command. To read more about what dt is, read here.

kd> dt nt!_OBJECT_TYPE
   +0x000 TypeList         : _LIST_ENTRY
   +0x008 Name             : _UNICODE_STRING
   +0x010 DefaultObject    : Ptr32 Void
   +0x014 Index            : UChar
   +0x018 TotalNumberOfObjects : Uint4B
   +0x01c TotalNumberOfHandles : Uint4B
   +0x020 HighWaterNumberOfObjects : Uint4B
   +0x024 HighWaterNumberOfHandles : Uint4B
   +0x028 TypeInfo         : _OBJECT_TYPE_INITIALIZER
   +0x078 TypeLock         : _EX_PUSH_LOCK
   +0x07c Key              : Uint4B
   +0x080 CallbackList     : _LIST_ENTRY

The TypeInfo structure will reveal information like the memory pool where this object is allocated from, several function pointers which will act upon the object, counts of handles etc. 

kd> dt nt!_OBJECT_TYPE TypeInfo.
   +0x028 TypeInfo  : 
      +0x000 Length    : Uint2B
      +0x002 ObjectTypeFlags : UChar
      +0x002 CaseInsensitive : Pos 0, 1 Bit
      +0x002 UnnamedObjectsOnly : Pos 1, 1 Bit
      +0x002 UseDefaultObject : Pos 2, 1 Bit
      +0x002 SecurityRequired : Pos 3, 1 Bit
      +0x002 MaintainHandleCount : Pos 4, 1 Bit
      +0x002 MaintainTypeList : Pos 5, 1 Bit
      +0x002 SupportsObjectCallbacks : Pos 6, 1 Bit
      +0x004 ObjectTypeCode : Uint4B
      +0x008 InvalidAttributes : Uint4B
      +0x00c GenericMapping : _GENERIC_MAPPING
      +0x01c ValidAccessMask : Uint4B
      +0x020 RetainAccess : Uint4B
      +0x024 PoolType  : _POOL_TYPE
      +0x028 DefaultPagedPoolCharge : Uint4B
      +0x02c DefaultNonPagedPoolCharge : Uint4B
      +0x030 DumpProcedure : Ptr32        void 
      +0x034 OpenProcedure : Ptr32        long 
      +0x038 CloseProcedure : Ptr32        void 
      +0x03c DeleteProcedure : Ptr32        void 
      +0x040 ParseProcedure : Ptr32        long 
      +0x044 SecurityProcedure : Ptr32        long 
      +0x048 QueryNameProcedure : Ptr32        long 
      +0x04c OkayToCloseProcedure : Ptr32        unsigned char 

Note: Observe the . (dot) after the TypeInfo in the above command. It is used to expand structure fields.

Lets use this to see the values for an actual Object. Processes are also objects inside NT. So lets use our favorite process lsass.exe for this example.

kd> !process 0 0 lsass.exe
PROCESS 84cdc860  SessionId: 0  Cid: 0208    Peb: 7ffda000  ParentCid: 018c
    DirBase: 1eed30e0  ObjectTable: 95f00d18  HandleCount: 513.
    Image: lsass.exe

Passing this process address to the !object extension we extract information about it.

kd> !object 84cdc860  
Object: 84cdc860  Type: (839b7978) Process
    ObjectHeader: 84cdc848 (new version)
    HandleCount: 10  PointerCount: 254

Lets try to typecast this address to OBJECT_TYPE.

kd> dt nt!_OBJECT_TYPE 839b7978
   +0x000 TypeList         : _LIST_ENTRY [ 0x839b7978 - 0x839b7978 ]
   +0x008 Name             : _UNICODE_STRING "Process"
   +0x010 DefaultObject    : (null)
   +0x014 Index            : 0x7 ''
   +0x018 TotalNumberOfObjects : 0x1f
   +0x01c TotalNumberOfHandles : 0xaf
   +0x020 HighWaterNumberOfObjects : 0x22
   +0x024 HighWaterNumberOfHandles : 0xbd
   +0x028 TypeInfo         : _OBJECT_TYPE_INITIALIZER
   +0x078 TypeLock         : _EX_PUSH_LOCK
   +0x07c Key              : 0x636f7250
   +0x080 CallbackList     : _LIST_ENTRY [ 0x839b79f8 - 0x839b79f8 ]

Notice that the Name of this Object is 'Process'.

...and extract the TypeInfo sub structure fields....

kd> dt nt!_OBJECT_TYPE 839b7978 TypeInfo.
   +0x028 TypeInfo  :
      +0x000 Length    : 0x50
      +0x002 ObjectTypeFlags : 0x4a 'J'
      +0x002 CaseInsensitive : 0y0
      +0x002 UnnamedObjectsOnly : 0y1
      +0x002 UseDefaultObject : 0y0
      +0x002 SecurityRequired : 0y1
      +0x002 MaintainHandleCount : 0y0
      +0x002 MaintainTypeList : 0y0
      +0x002 SupportsObjectCallbacks : 0y1
      +0x004 ObjectTypeCode : 0
      +0x008 InvalidAttributes : 0xb0
      +0x00c GenericMapping : _GENERIC_MAPPING
      +0x01c ValidAccessMask : 0x1fffff
      +0x020 RetainAccess : 0x101000
      +0x024 PoolType  : 0 ( NonPagedPool )
      +0x028 DefaultPagedPoolCharge : 0x1000
      +0x02c DefaultNonPagedPoolCharge : 0x2f0
      +0x030 DumpProcedure : (null)
      +0x034 OpenProcedure : 0x82819ccb        long  nt!PspProcessOpen+0
      +0x038 CloseProcedure : 0x82879d2e        void  nt!PspProcessClose+0
      +0x03c DeleteProcedure : 0x8287c5f5        void  nt!PspProcessDelete+0
      +0x040 ParseProcedure : (null)
      +0x044 SecurityProcedure : 0x8286e5b6        long  nt!SeDefaultObjectMethod+0
      +0x048 QueryNameProcedure : (null)
      +0x04c OkayToCloseProcedure : (null) 

We had discussed before about the object having a header and a body. Lets see if we can extract the appropriate fields displayed by the !object extension ourselves.

kd> dt nt!_OBJECT_HEADER
   +0x000 PointerCount     : Int4B
   +0x004 HandleCount      : Int4B
   +0x004 NextToFree       : Ptr32 Void
   +0x008 Lock             : _EX_PUSH_LOCK
   +0x00c TypeIndex        : UChar
   +0x00d TraceFlags       : UChar
   +0x00e InfoMask         : UChar
   +0x00f Flags            : UChar
   +0x010 ObjectCreateInfo : Ptr32 _OBJECT_CREATE_INFORMATION
   +0x010 QuotaBlockCharged : Ptr32 Void
   +0x014 SecurityDescriptor : Ptr32 Void
   +0x018 Body             : _QUAD

In my version of Windows the body starts at offset 0x18, which means to get the header we need to move the pointer by 0x18. using the address of lsass.ee from the output of !process above...

kd> !process 0 0 lsass.exe
PROCESS 84cdc860  SessionId: 0  Cid: 0208    Peb: 7ffda000  ParentCid: 018c
    DirBase: 1eed30e0  ObjectTable: 95f00d18  HandleCount: 513.
    Image: lsass.exe

kd> dt nt!_OBJECT_HEADER 84cdc860-18
   +0x000 PointerCount     : 0n254
   +0x004 HandleCount      : 0n10
   +0x004 NextToFree       : 0x0000000a Void
   +0x008 Lock             : _EX_PUSH_LOCK
   +0x00c TypeIndex        : 0x7 ''
   +0x00d TraceFlags       : 0 ''
   +0x00e InfoMask         : 0x8 ''
   +0x00f Flags            : 0 ''
   +0x010 ObjectCreateInfo : 0x8273ecc0 _OBJECT_CREATE_INFORMATION
   +0x010 QuotaBlockCharged : 0x8273ecc0 Void
   +0x014 SecurityDescriptor : 0x87405f79 Void
   +0x018 Body             : _QUAD

Which are the same as given by the !object extension.

kd> !object 84cdc860
Object: 84cdc860  Type: (839b7978) Process
    ObjectHeader: 84cdc848 (new version)
    HandleCount: 10  PointerCount: 254

Note: The Object header structure has changed from the previous versions of Windows. Earlier the _OBJECT_TYPE pointer used to be available in the header itself. Hre is an output from an older version of Windows.

kd>dt_object_header  8a4ce650
nt!_OBJECT_HEADER
  +0x000PointerCount     : 79
  +0x004HandleCount      : 2
  +0x004NextToFree       : 0x00000002
  +0x008 Type            : 0x8a4ceca0
  +0x00cNameInfoOffset   : 0''
  +0x00dHandleInfoOffset : 0''
  +0x00eQuotaInfoOffset  : 0''
  +0x00fFlags            : 0x22'"'
  +0x010ObjectCreateInfo : 0x80545620
  +0x010QuotaBlockCharged : 0x80545620
  +0x014SecurityDescriptor : 0xe10001dc
  +0x018Body             : _QUAD

We will revisit the object manager again later on when we see how names are resolved in Windows.

Thursday, 11 September 2014

WinDbg : Walking Windows Linked Lists (LIST_ENTRY)

WinDbg : Walking Windows Linked Lists (LIST_ENTRY)


The Windows implementation of the linked list is slightly different from how we are used to seeing it. Most of us start programming data structures with this simple, yet highly used data structure. We usually define a linked list node as follows: 


typedef struct _Node{
    int       ndata;
    _Node *pNext;
} NODE, *PNODE, **PNODE;

Using such a construct tightly couples the data part of the list to the list implementation. If someone later needs to store a character instead of integer, they have to rewrite the node structure. One way to avoid the problem is to use void pointers. redefining the node structure this way would solve the problem partially.

typedef struct _Node{
    void    *pDataBlob;
    _Node *pNext;
} NODE, *PNODE, **PNODE;


The above construct solves most problems, except that the memory for the data blob will have to be elsewhere, and not part of the node itself. This is not a big problem most of the time, unless one wants to serialize the Node and pass it.

Windows has a slightly different way of implementing linked lists.  Windows defines the entry to the list as:

typedef struct _LIST_ENTRY {
  struct _LIST_ENTRY  *Flink;
  struct _LIST_ENTRY  *Blink;
} LIST_ENTRY, *PLIST_ENTRY;

This is exported in the debugger, and we can use the dt command to view it as well.

kd> dt _LIST_ENTRY
ntdll!_LIST_ENTRY
   +0x000 Flink            : Ptr32 _LIST_ENTRY
   +0x004 Blink            : Ptr32 _LIST_ENTRY

Anyone wanting to use linked lists would then use this structure in the following manner:
typedef struct _MY_DATA_STRUCT{
    void             *pDataBlob;
    LIST_ENTRY   List;
} MY_DATA_STRUCT, *PMY_DATA_STRUCT, **PMY_DATA_STRUCT;

Observe, that the LIST_ENTRY struct is embedded inside the data structure we want the list to be of. It is not a pointer. The idea here is that  a separate pointer be maintained which can be used to traverse from one list entry to another, thus we would land up somewhere in the middle of the data structure, then we use the popular CONTAINING_RECORD macro to find the base of the structure.

Cumbersome? Not really. Depending on where you place the LIST_ENTRY inside your structure, you can use this to your advantage as well.

Assume that instead of defining MY_DATA_STRUCT the way we did, we do it this way:

typedef struct _MY_DATA_STRUCT{
    LIST_ENTRY   List;
    void             *pDataBlob;    
} MY_DATA_STRUCT, *PMY_DATA_STRUCT, **PMY_DATA_STRUCT;

In this scenario, since the LIST_ENTRY is the first member, we do not need to find the beginning of the struct at all, a simple C-style cast of one pointer type to another would make the entire structure accessible.

This article is not intended to teach you how to use LIST_ENTRY, but to help us debug structures which already are using this construct. So, after this very brief introduction to lists, I leave it to you to write a few programs using this data type, if you are not already familiar with it, to make yourself comfortable.

The rest of this article will focus on traversing such lists inside the debugger.

Commands used in this article Are:
Lets try to walk the list of active processes. For this we need to find the head of this list. It is exported by the NT kernel.

kd> x nt!psacti*
8274af18          nt!PsActiveProcessHead = <no type information>

Great, so we now have the pointer to the head of this list.

kd> dt nt!_LIST_ENTRY 8274af18          
 [ 0x839afcb0 - 0x851d1400 ]
   +0x000 Flink            : 0x839afcb0 _LIST_ENTRY [ 0x8490da80 - 0x8274af18 ]
   +0x004 Blink            : 0x851d1400 _LIST_ENTRY [ 0x8274af18 - 0x846e98c8 ]

Okay, so it has a set of valid pointers. However, we need to find out which data structure in Windows is using this list. That is when we can type cast the pointer to the right data structure. In this case, the kernel _EPROCESS data structure is the one using this list. Lets find out which offset of _EPROCESS has this list.

Note: _EPROCESS is a large data structure, so the following output is snipped off after the first few lines.

kd> dt nt!_EPROCESS
   +0x000 Pcb              : _KPROCESS
   +0x098 ProcessLock      : _EX_PUSH_LOCK
   +0x0a0 CreateTime       : _LARGE_INTEGER
   +0x0a8 ExitTime         : _LARGE_INTEGER
   +0x0b0 RundownProtect   : _EX_RUNDOWN_REF
   +0x0b4 UniqueProcessId  : Ptr32 Void
   +0x0b8 ActiveProcessLinks : _LIST_ENTRY
   +0x0c0 ProcessQuotaUsage : [2] Uint4B
   +0x0c8 ProcessQuotaPeak : [2] Uint4B
   +0x0d0 CommitCharge     : Uint4B
   +0x0d4 QuotaBlock       : Ptr32 _EPROCESS_QUOTA_BLOCK
   +0x0d8 CpuQuotaBlock    : Ptr32 _PS_CPU_QUOTA_BLOCK
   +0x0dc PeakVirtualSize  : Uint4B
   +0x0e0 VirtualSize      : Uint4B
   +0x0e4 SessionProcessLinks : _LIST_ENTRY
<Output Snipped>

Okay, so we found the offset of the LIST_ENTRY we want. this means that for any LIST_ENTRY address, belonging to a list of processes, subtracting 0x0b8 from it would lead us to the beginning of the _EPROCESS structure.

Note: The offset of this member could vary between one Windows flavor to another, even between service packs. So it it critical to know the right offset for the particular debugging session.

Okay, lets try to validate our example with a simple experiment. lets see for the process lsass.exe how this goes.

kd> !process 0 0 lsass.exe
PROCESS 84cdc860  SessionId: 0  Cid: 0208    Peb: 7ffda000  ParentCid: 018c
    DirBase: 1eed30e0  ObjectTable: 95f00d18  HandleCount: 513.
    Image: lsass.exe

kd> dt nt!_EPROCESS 84cdc860  
   +0x000 Pcb              : _KPROCESS
   +0x098 ProcessLock      : _EX_PUSH_LOCK
   +0x0a0 CreateTime       : _LARGE_INTEGER 0x01cf0ae6`f5dbfe68
   +0x0a8 ExitTime         : _LARGE_INTEGER 0x0
   +0x0b0 RundownProtect   : _EX_RUNDOWN_REF
   +0x0b4 UniqueProcessId  : 0x00000208 Void
   +0x0b8 ActiveProcessLinks : _LIST_ENTRY [ 0x849390e8 - 0x84ccb4c0 ]
   +0x0c0 ProcessQuotaUsage : [2] 0x2cdc
   +0x0c8 ProcessQuotaPeak : [2] 0x2cdc
   +0x0d0 CommitCharge     : 0x219
   +0x0d4 QuotaBlock       : 0x8273ecc0 _EPROCESS_QUOTA_BLOCK
   +0x0d8 CpuQuotaBlock    : (null) 
<output snipped>

So we see that for this particular debugging instance, for lsass.exe, the base of the _EPROCESS is at 0x84cdc860. Adding 0xb8 to it gives us 0x84CDC918. So if this is a valid offset inside the _EPROCESS, then subtracting 0xb8 from it should get us the _EPROCESS base address back. this is exactly what we will do with the nt!PsActiveProcessHead pointer and how do we do that? Well, the versatile dt command already supports walking windows lists. here is how it is done.

Find the pointer to the list head for Active Processes.

kd> x nt!psact*
8274af18          nt!PsActiveProcessHead = <no type information>

Then find the Flink entry address for this List_ENTRY

kd> dt nt!_LIST_ENTRY 8274af18
 [ 0x839afcb0 - 0x851d1400 ]
   +0x000 Flink            : 0x839afcb0 _LIST_ENTRY [ 0x8490da80 - 0x8274af18 ]
   +0x004 Blink            : 0x851d1400 _LIST_ENTRY [ 0x8274af18 - 0x846e98c8 ]

Now we typecast the pointer we got to _EPROCESS, but we subtract the correct offset, 0x0b8 first. Then we use the -l switch of the dt command to tell it that we want it to parse a list, via the Flink member of _LIST_ENTRY, where the member variable inside _EPROCESS which is this _LIST_ENTRY type is called ActiveProcessLinks. We also ask it to print out the ImageFilename member inside _EPROCESS so that we can see what all processes are currently active.
 
kd> dt nt!_EPROCESS 0x839afcb0-0x0b8 -l ActiveProcessLinks.Flink -y ImageFileName
ActiveProcessLinks.Flink at 0x839afbf8
---------------------------------------------
   +0x0b8 ActiveProcessLinks :  [ 0x8490da80 - 0x8274af18 ]
   +0x16c ImageFileName : [15]  "System"

ActiveProcessLinks.Flink at 0x8490d9c8
---------------------------------------------
   +0x0b8 ActiveProcessLinks :  [ 0x84c3b0e8 - 0x839afcb0 ]
   +0x16c ImageFileName : [15]  "smss.exe"

ActiveProcessLinks.Flink at 0x84c3b030
---------------------------------------------
   +0x0b8 ActiveProcessLinks :  [ 0x84bf2df8 - 0x8490da80 ]
   +0x16c ImageFileName : [15]  "csrss.exe"

ActiveProcessLinks.Flink at 0x84bf2d40
---------------------------------------------
   +0x0b8 ActiveProcessLinks :  [ 0x848a7df8 - 0x84c3b0e8 ]
   +0x16c ImageFileName : [15]  "wininit.exe"

ActiveProcessLinks.Flink at 0x848a7d40
---------------------------------------------
   +0x0b8 ActiveProcessLinks :  [ 0x84c54df8 - 0x84bf2df8 ]
   +0x16c ImageFileName : [15]  "csrss.exe"

ActiveProcessLinks.Flink at 0x84c54d40
---------------------------------------------
   +0x0b8 ActiveProcessLinks :  [ 0x84ccb4c0 - 0x848a7df8 ]
   +0x16c ImageFileName : [15]  "winlogon.exe"

ActiveProcessLinks.Flink at 0x84ccb408
---------------------------------------------
   +0x0b8 ActiveProcessLinks :  [ 0x84cdc918 - 0x84c54df8 ]
   +0x16c ImageFileName : [15]  "services.exe"

ActiveProcessLinks.Flink at 0x84cdc860
---------------------------------------------
   +0x0b8 ActiveProcessLinks :  [ 0x849390e8 - 0x84ccb4c0 ]
   +0x16c ImageFileName : [15]  "lsass.exe"

<Output trimmed>

the list is long, so i trimmed the output. As we see, that one of the process names printed is lsass.exe
ActiveProcessLinks.Flink at 0x84cdc860
---------------------------------------------
   +0x0b8 ActiveProcessLinks :  [ 0x849390e8 - 0x84ccb4c0 ]
   +0x16c ImageFileName : [15]  "lsass.exe"

The address of the ActiveProcessLinks.Flink member is 0x84cdc860. So the address of it's corresponding _EPROCESS would be 0x84cdc860 - 0x0b8 = 0x84CDC860. This is exactly the address we get when we did a !process 0 0 lsass.exe.

kd> !process 0 0 lsass.exe
PROCESS 84cdc860  SessionId: 0  Cid: 0208    Peb: 7ffda000  ParentCid: 018c
    DirBase: 1eed30e0  ObjectTable: 95f00d18  HandleCount: 513.
    Image: lsass.exe

Lists are used extensively inside Windows, and we will use these commands in future blog posts. So I would suggest that you execute these yourselves to familiarize with the concept.


WinDbg : How to Debug a 32 bit Executable in A 64 bit debugger (wow64exts)

WinDbg : wow64exts


We often run 32 bit processes on 64 bit windows OS. Such processes are run through Windows On Windows (WoW). However, debugging dumps of such processes might pose certain problems. It is always advisable to use the 32 vbit version of WinDbg to debug the 32 bit process. However, at times when the 32 bit debugger is not available and we still want to debug a 32 bit process we need to tell the debugger that. If we don't, then the wow64 specific stack traces might show up and this might get confusing and at times, even misleading.





0:000> .load wow64exts
0:000> .chain
Extension DLL search Path:
    C:\WinDDK\7600.16385.1\Debuggers\WINXP;C:\WinDDK\7600.16385.1\Debuggers\winext;C:\WinDDK\7600.16385.1\Debuggers\winext\arcade;C:\WinDDK\7600.16385.1\Debuggers\pri;C:\WinDDK

\7600.16385.1\Debuggers;C:\WinDDK\7600.16385.1\Debuggers\winext\arcade;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files 

(x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL 

Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files\Perforce;C:\Program Files\Collaborator Client
Extension DLL chain:
    dbghelp: image 6.12.0002.633, API 6.1.6, built Tue Feb 02 01:45:44 2010
        [path: C:\WinDDK\7600.16385.1\Debuggers\dbghelp.dll]
    ext: image 6.12.0002.633, API 1.0.0, built Tue Feb 02 01:45:46 2010
        [path: C:\WinDDK\7600.16385.1\Debuggers\winext\ext.dll]
    wow64exts: image 6.1.7650.0, API 1.0.0, built Tue Feb 02 01:45:14 2010
        [path: C:\WinDDK\7600.16385.1\Debuggers\WINXP\wow64exts.dll]
    exts: image 6.12.0002.633, API 1.0.0, built Tue Feb 02 01:45:38 2010
        [path: C:\WinDDK\7600.16385.1\Debuggers\WINXP\exts.dll]
    uext: image 6.12.0002.633, API 1.0.0, built Tue Feb 02 01:45:36 2010
        [path: C:\WinDDK\7600.16385.1\Debuggers\winext\uext.dll]
    ntsdexts: image 6.1.7650.0, API 1.0.0, built Tue Feb 02 01:45:18 2010
        [path: C:\WinDDK\7600.16385.1\Debuggers\WINXP\ntsdexts.dll]

Wow64 has it's own hel section, which can be accessed with the help command. As shown below.

0:000> !wow64exts.help

Wow64 debugger extension commands: 

sw:            Switch between 32-bit and 64-bit mode
k <count>:     Combined 32/64 stack trace
info:          Dumps information about some important wow64 structures
r [addr]:      Dumps x86 CONTEXT
lf:            Dump/Set log flags
l2f:           Enable logging to file


Using the sw switch we can switch between the 32 and 64 bit modes.


0:000> !wow64exts.sw
Switched to 32bit mode

Tuesday, 9 September 2014

WinDbg : Trying To Find The Export Address Table (EAT) Of A Binary

WinDbg : Trying To Find The Export Address Table (EAT) Of A Binary


In the last article we learnt how to use the basic WinDbg commands we had learnt, to find out useful information within the loaded binary images. That article taught us how to parse the import address table (IAT) of a loaded binary. We will extend that study here, to try and learn one can parse the export address table (EAT) of a loaded binary image.

Commands used in this article are:


  1. dt
  2. !dh
  3. dd
  4. da
Before we begin, a brief introduction about the EAT is desirable. The EAT works in the same way as the IAT, apart from the fact that the library will be exporting the functions to the image executable, in which the program will import into the IAT. The key data structure that is used by Windows to map the EAT is _IMAGE_EXPORT_DIRECTORY. Now, we know from our previous learning that to see the types created by us, we can use the dt command. A quick recall of that exercise can be found here. Unfortunately, WinDbg(atleast the current version) cannot find this type! So we need to calculate the offsets manually. the structure is defined in the header file WinNt.H. I am copying the same here for convenience.

//

// Export Format
//

typedef struct _IMAGE_EXPORT_DIRECTORY {
    DWORD   Characteristics;
    DWORD   TimeDateStamp;
    WORD    MajorVersion;
    WORD    MinorVersion;
    DWORD   Name;
    DWORD   Base;
    DWORD   NumberOfFunctions;
    DWORD   NumberOfNames;
    DWORD   AddressOfFunctions;     // RVA from base of image
    DWORD   AddressOfNames;         // RVA from base of image
    DWORD   AddressOfNameOrdinals;  // RVA from base of image
} IMAGE_EXPORT_DIRECTORY, *PIMAGE_EXPORT_DIRECTORY;

The AddressOfFunctions is the field we are interested in. the comment says that the array contains Relative virtual Addresses (RVAs) from the base of the image. It is the the PE loaders responsibility to translate these to real addresses for the binary using it in the IAT.

The AddressOfNames and AddressOfNameOrdinals are loaded alongside each other, to provide a linkage between the address of the function and the name of the function. The AddressOfNames is a pointer to a array of function names, and the AddressOfNameOrdinals is a pointer to a array used to index into the AddressOfFunctions to obtain the addresses for the function names. Now, lets try to use this knowledge to see if we can actually find the names of the functions which a particular binary exports. Not all binaries will necessarily export, in such cases the number of entries in the EAT will be zero.

kd> !dh lsass.exe -f

File Type: EXECUTABLE IMAGE
FILE HEADER VALUES
     14C machine (i386)
       4 number of sections
4A5BBF3E time date stamp Tue Jul 14 04:41:58 2009

       0 file pointer to symbol table
       0 number of symbols
      E0 size of optional header
     122 characteristics
            Executable
            App can handle >2gb addresses
            32 bit word machine

OPTIONAL HEADER VALUES
     10B magic #
    9.00 linker version
    4200 size of code
    1000 size of initialized data
       0 size of uninitialized data
    2F3D address of entry point
    1000 base of code
         ----- new -----
00d90000 image base
    1000 section alignment
     200 file alignment
       2 subsystem (Windows GUI)
    6.01 operating system version
    6.01 image version
    6.01 subsystem version
    9000 size of image
     600 size of headers
    6193 checksum
00040000 size of stack reserve
00006000 size of stack commit
00100000 size of heap reserve
00001000 size of heap commit
    8140  DLL characteristics
            Dynamic base
            NX compatible
            Terminal server aware
    1EC4 [      6B] address [size] of Export Directory
    4478 [     154] address [size] of Import Directory
    7000 [     700] address [size] of Resource Directory
         0 [         0] address [size] of Exception Directory
         0 [         0] address [size] of Security Directory
    8000 [     368] address [size] of Base Relocation Directory
    5080 [      38] address [size] of Debug Directory
         0 [        0] address [size] of Description Directory
         0 [        0] address [size] of Special Directory
         0 [        0] address [size] of Thread Storage Directory
    3F90 [      40] address [size] of Load Configuration Directory
      280 [    294] address [size] of Bound Import Directory
    1000 [    1AC] address [size] of Import Address Table Directory
         0 [        0] address [size] of Delay Import Directory
         0 [        0] address [size] of COR20 Header Directory
         0 [        0] address [size] of Reserved Directory

Ok, now lets dump the contents at the offset of 0x1EC4 to see what they contain.
kd> dd 1EC4+lsass
00d91ec4  00000000 4a5bbf3e 00000000 00001f00
00d91ed4  00000001 00000002 00000002 00001eec
00d91ee4  00001ef4 00001efc 00002ef6 000023c9
00d91ef4  00001f0a 00001f1a 00010000 7361736c
00d91f04  78652e73 734c0065 74654761 65746e49
00d91f14  63616672 734c0065 67655261 65747369
00d91f24  74784572 69736e65 90006e6f 90909090
00d91f34  8b55ff8b 565351ec 57ff3357 00008a68

This is the _IMAGE_EXPORT_DIRECTORY structure. The three highlighted fields are the following:
00001f00 : Name
00001ef4 : AddressOfFunctions
00001efc : AddressOfNames
00002ef6 : AddressOfNameOrdinals

To verify whether we have indeed the right offsets, lets dump out the contents of the 'Name' to see if it is indeed lsass.exe.


kd> da 00001f00+lsass

00d91f00  "lsass.exe"

Looks like we did get he right members. Then lets use the other addresses to find the names of all the functions exported. Lets use the dd command to dump the addresses first.

kd> dd 00001ef4+lsass
00d91ef4  00001f0a 00001f1a 00010000 7361736c
00d91f04  78652e73 734c0065 74654761 65746e49
00d91f14  63616672 734c0065 67655261 65747369
00d91f24  74784572 69736e65 90006e6f 90909090
00d91f34  8b55ff8b 565351ec 57ff3357 00008a68
00d91f44  20206800 7fe800d9 33000009 ff5343db
00d91f54  d910fc15 41186800 15ff00d9 00d910f8
00d91f64  ff535753 d9108415 0cc48300 458d046a

Now we can use the da command to dump the name of each function that is exported. it is a manual process to walk the arrays or we can write scripts for it. Scripts are a slightly advanced topic, which will be covered in future posts, we can revisit the problem at that time.

kd> da 00001f0a+lsass
00d91f0a  "LsaGetInterface"