Monday, February 16, 2009

System call hooking - I

In this post I will be telling you about system call hooking by patching the System Service Descriptor Table (SSDT). But before that let's see what SSDT actually is, who uses it and other BLAH! BLAH!

SSDT is created during the initialization of NTOSKRNL and is used by KiSystemService() to look up entry points of native APIs. KiSystemService is the handler for INT 2Eh/ SYSENTER. Now let us take a look at the structure of this table.

typedef struct SERVICE_DESCRIPTOR_TABLE {

PNTPROC pServiceTable; // Array of entry points

PULONG pdwCounterTable; // Array of usage counters

ULONG dwServiceLimit;     // No. of table entries

PUCHAR pArgumentTable;     // Array of byte counts

} SERVICE_DESCRIPTOR_TABLE, *PSERVICE_DESCRIPTOR_TABLE;

There are two service descriptor tables present in the system: KeServiceDescriptorTable and KeServiceDescriptorTableShadow. Ntoskrnl exports the KeServiceDescriptorTable but not the shadow one. Both of them are defined as an array of SERVICE_DESCRIPTOR_TABLE. Something like SERVICE_DESCRIPTOR_TABLE KeServiceDescriptorTable[NoOfTables].

In both KeServiceDescriptorTable and KeServiceDescriptorTableShadow, the first table (KeServiceDescriptorTable[0] and KeServiceDescriptorTableShadow[0]) contains addresses of Nt APIs.

Let's suppose that we have to hook NtCreateFile. Obviously, we need a mechanism to replace the address of the entry point of NtCreateFile with address of our hook function. Let's do it step by step.

Step 1: Finding an entry for any given function in the SSDT (KeServiceDescriptorTable). Entry for any function 'func' is given by KeServiceDescriptorTable[0].pServiceTable[*(PULONG) ((PUCHAR) func + 1 ))]

Step 2: Read the value present in the entry corresponding to NtCreateFile and save it.

Step 3: Change the value for that entry with address of your hook function.

Apart from the above steps, you need to disable to the write protect bit that is set before writing to the table and then enable it again.

I intentionally did not put the code here! J

3 comments:

  1. Again very very old and nothing new... :(

    ReplyDelete
  2. Thanks for your suggestions! :-)
    Will definitely improve upon my posts.
    Improvement often needs suggestions; and now you gave one!

    ReplyDelete