GetWindowThreadProcessId()IAT挂钩:如何比较“ dwProcessID”参数?

时间:2018-10-12 22:49:19

标签: delphi delphi-10-seattle api-hook

我正在使用以下代码将GetWindowThreadProcessId()与成功挂钩。

现在,我要检查 dwProcessID 参数是否对应于确定的进程的ID,在肯定的情况下,请阻止执行原始功能:

Result := OldGetWindowThreadProcessId(hWnd, dwProcessID);

我尝试了这个,但是没有用:

if dwProcessID = 12345 then exit;

这是我完整的代码:

library MyLIB;

uses
  Windows,
  ImageHlp;

{$R *.res}

type
  PGetWindowThreadProcessId = function(hWnd: THandle; dwProcessID: DWord)
    : DWord; stdcall;

var
  OldGetWindowThreadProcessId: PGetWindowThreadProcessId;

function HookGetWindowThreadProcessId(hWnd: THandle; dwProcessID: DWord)
  : DWord; stdcall;

begin
  try
    // Check if is some process
  except
    MessageBox(0, 'Error', 'HookGetWindowThreadProcessId Error', 0);
  end;
  Result := OldGetWindowThreadProcessId(hWnd, dwProcessID);
end;

procedure PatchIAT(strMod: PAnsichar; Alt, Neu: Pointer);
var
  pImportDir: pImage_Import_Descriptor;
  size: CardinaL;
  Base: CardinaL;
  pThunk: PDWORD;
begin
  Base := GetModuleHandle(nil);
  pImportDir := ImageDirectoryEntryToData(Pointer(Base), True,
    IMAGE_DIRECTORY_ENTRY_IMPORT, size);
  while pImportDir^.Name <> 0 Do
  begin
    If (lstrcmpiA(PAnsichar(pImportDir^.Name + Base), strMod) = 0) then
    begin
      pThunk := PDWORD(Base + pImportDir^.FirstThunk);
      While pThunk^ <> 0 Do
      begin
        if DWord(Alt) = pThunk^ Then
        begin
          pThunk^ := CardinaL(Neu);
        end;
        Inc(pThunk);
      end;
    end;
    Inc(pImportDir);
  end;
end;

procedure DllMain(reason: Integer);

begin
  case reason of
    DLL_PROCESS_ATTACH:
      begin
        OldGetWindowThreadProcessId := GetProcAddress(GetModuleHandle(user32),
          'GetWindowThreadProcessId');

        PatchIAT(user32, GetProcAddress(GetModuleHandle(user32),
          'GetWindowThreadProcessId'), @HookGetWindowThreadProcessId);

      end;
    DLL_PROCESS_DETACH:
      begin
      end;
  end;
end;

begin
  DllProc := @DllMain;
  DllProc(DLL_PROCESS_ATTACH);

end.

1 个答案:

答案 0 :(得分:2)

您的PGetWindowThreadProcessId类型和HookGetWindowThreadProcessId()函数都错误地声明了dwProcessID参数。它是一个输出参数,因此需要声明为var dwProcessID: DWorddwProcessID: PDWord

然后您需要调用OldGetWindowThreadProcessId()来检索实际的PID,然后才能将其与任何内容进行比较。因此,您对“ <肯定>阻止执行原始功能的要求”是不现实的,因为您需要执行原始功能以确定要比较的dwProcessID值。

尝试以下方法:

type
  PGetWindowThreadProcessId = function(hWnd: THandle; var dwProcessID: DWord): DWord; stdcall;

...

function HookGetWindowThreadProcessId(hWnd: THandle; var dwProcessID: DWord): DWord; stdcall;
begin
  Result := OldGetWindowThreadProcessId(hWnd, dwProcessID);
  try
    if dwProcessID = ... then
      ...
  except
    MessageBox(0, 'Error', 'HookGetWindowThreadProcessId Error', 0);
  end;
end;
相关问题