Hooking KiFastSystemCall

c++ / delphi package - dll injection and api hooking
Post Reply
XanSama
Posts: 15
Joined: Sat Mar 04, 2006 11:19 am

Hooking KiFastSystemCall

Post by XanSama »

Hey all,
I've just been working on a KiFastSystemCall hook using madCodeHook and since it was a bit harder than I would have hoped, I figured I'd share my code (incase someone cares :P).

Code: Select all

program KiFastSystemCall;

uses
  Windows, madCodeHook, SysUtils;

var
  realKiFastSystemCall: procedure;
  dwIndexPVM: DWORD;

function hookZwProtectVirtualMemory(hProcess: THandle; lpAddress: Pointer; dwSize, flNewProtect: DWORD; lpflOldProtect: Pointer): DWORD; stdcall;
var
  Stack1, Stack2: DWORD;
begin
  Result := 0;
  MessageBoxA(0, PChar(IntToHex(DWORD(lpAddress), 8)), 'ZwProtectVirtualMemory', 0);
  asm
    pop eax
    mov [Stack1], eax
    pop eax
    mov [Stack2], eax
    mov eax, [dwIndexPVM]
    call realKiFastSystemCall
    mov [Result], eax
    push [Stack2]
    push [Stack1]
  end;
end;

procedure hookKiFastSystemCall; assembler;
label
  CallPVM;
begin
  asm
    cmp eax, [dwIndexPVM]
    je @CallPVM
    jmp realKiFastSystemCall
    @CallPVM:
    pop eax
    jmp hookZwProtectVirtualMemory
  end;
end;

begin
  MessageBoxA(0, 'You need to call me once before you install the hook, otherwise I don''t initialize properly.', 'MessageBoxA Bug Fix', 0);
  dwIndexPVM := PDWORD(DWORD(GetProcAddress(GetModuleHandle('ntdll.dll'), 'ZwProtectVirtualMemory'))+1)^;
  HookAPI('ntdll.dll', 'KiFastSystemCall', @hookKiFastSystemCall, @realKiFastSystemCall);
end.
Now, I know someone is going to say "Why didn't you just hook ZwProtectVirtualMemory?" but before you do, let me just say, that I thought it might be interesting not to :P

@madshi
While I don't think it's a big issue (at all), I do think it might be neat if you could add some form of support/automation to make hooking KiFastSystemCall simpler :)

Edit: Just a note, I probably could have made this code substantialy more modular in terms of being able to hook more than one system function, but I haven't looked into wether I can use the same return code for all of the functions yet.
Sirmabus
Posts: 89
Joined: Fri May 28, 2004 6:20 pm

Post by Sirmabus »

That's only for ntdll.dll though. I'm sure there is a similar one for user32.dll too, but this won't work for other API DLL's and layers that don't have such a call gate.
iconic
Site Admin
Posts: 1065
Joined: Wed Jun 08, 2005 5:08 am

Post by iconic »

I've done this in the past and win2k was different than xp when hooking it if I remember correctly. INT 2E/SYSENTER/SYSCALL is also fairly well documented online, if you look in the right places. Nonetheless, thanks for your contribution Xan.

--Iconic
Post Reply