Delphi Hook Library

常常见到有朋友问Hook怎么做和COM的HOOK怎么弄.
来点干货,给Delphi业界朋友做点贡献.把我之前写的一个Delphi Hook库放到了Google Code上.方便大家.
微软官方钩子库Detours X86是免费的,X64可是要1000美刀的哦.
支持X86,X64的函数钩子.线程安全.
封装了对COM对象的Hook.在Hook COM对象的时候方法时会自动判断是Delphi还是其他语言实现的COM对象,从而进行智能处理.

其实代码加注释也就几百行.一个单元文件而已.
其中使用了开源的BeaEngine的反汇编引擎来判断代码的大小,避免机器指令被从中间切开.

Google Code
http://code.google.com/p/delphi-hook-library/

更新在

http://www.raysoftware.cn/?p=493

关键文件按内容如下:

unit HookUtils;

{
  wr960204武稀松.2012.2

  主页  http://www.raysoftware.cn

  通用Hook库.
  支持X86和X64.
  使用了开源的BeaEngine反汇编引擎.BeaEngine的好处是可以用BCB编译成OMF格式的Obj,
  被链接进Delphi的DCU和目标文件中.不需要额外带DLL.
  BeaEngin引擎

http://www.beaengine.org/

  限制:
  1.不能Hook代码大小小于5个字节的函数.
  2.不能Hook前五个字节中有跳转指令的函数.
  希望使用的朋友们自己也具有一定的汇编或者逆向知识.
  Hook函数前请确定该函数不属于上面两种情况.


  另外钩COM对象有一个技巧,如果你想在最早时机勾住某个COM对象,
  可以在你要钩的COM对象创建前自己先创建一个该对象,Hook住,然后释放你自己的对象.
  这样这个函数已经被下钩子了,而且是钩在这个COM对象创建前的.
}
interface

{ 下函数钩子
  64位中会有一种情况失败,就是VirtualAlloc不能在被Hook函数地址正负2Gb范围内分配到内存.
  不过这个可能微乎其微.几乎不可能发生.
}
function HookProc(Func, NewFunc: Pointer): Pointer; overload;
function HookProc(DLLName, FuncName: PChar; NewFunc: Pointer): Pointer;
  overload;
{ 计算COM对象中方法的地址;AMethodIndex是方法的索引.
  AMethodIndex是接口包含父接口的方法的索引.
  例如:
  IA = Interface
  procedure A();//因为IA是从IUnKnow派生的,IUnKnow自己有3个方法,所以AMethodIndex=3
  end;
  IB = Interface(IA)
  procedure B(); //因为IB是从IA派生的,所以AMethodIndex=4
  end;
}
function CalcInterfaceMethodAddr(var AInterface; AMethodIndex: Integer)
  : Pointer;
// 下COM对象方法的钩子
function HookInterface(var AInterface; AMethodIndex: Integer;
  NewFunc: Pointer): Pointer;
// 解除钩子
function UnHook(OldFunc: Pointer): boolean;

implementation

uses
  BeaEngineDelphi, Windows, TLHelp32;

const
  PageSize = 4096;
{$IFDEF CPUX64}
{$DEFINE USELONGJMP}
{$ENDIF}
  { .$DEFINE USEINT3 }// 在机器指令中插入INT3,断点指令.方便调试.

type
  THandles = array of THandle;
  ULONG_PTR = NativeUInt;
  POldProc = ^TOldProc;

  PJMPCode = ^TJMPCode;

  TJMPCode = packed record
{$IFDEF USELONGJMP}
    JMP: Word;
    JmpOffset: Int32;
{$ELSE}
    JMP: byte;
{$ENDIF}
    Addr: UIntPtr;
  end;

  TOldProc = packed record
{$IFDEF USEINT3}
    Int3OrNop: byte;
{$ENDIF}
    BackCode: array [0 .. $20 - 1] of byte;
    JmpRealFunc: TJMPCode;
    JmpHookFunc: TJMPCode;

    BackUpCodeSize: Integer;
    OldFuncAddr: Pointer;
  end;

  PNewProc = ^TNewProc;

  TNewProc = packed record
    JMP: byte;
    Addr: Integer;
  end;

  // 计算需要覆盖的机器指令大小.借助了BeaEngin反汇编引擎.以免指令被从中间切开
function CalcHookCodeSize(Func: Pointer): Integer;
var
  ldiasm: TDISASM;
  len: longint;
begin
  Result := 0;
  ZeroMemory(@ldiasm, SizeOf(ldiasm));
  ldiasm.EIP := UIntPtr(Func);
  ldiasm.Archi := {$IFDEF CPUX64}64{$ELSE}32{$ENDIF};
  while Result < SizeOf(TNewProc) do
  begin
    len := Disasm(ldiasm);
    Inc(ldiasm.EIP, len);
    Inc(Result, len);
  end;
end;

const
  THREAD_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED or SYNCHRONIZE or $3FF;

function OpenThread(dwDesiredAccess: DWORD; bInheritHandle: BOOL;
  dwThreadId: DWORD): THandle; stdcall; external kernel32;

function SuspendOneThread(dwThreadId: NativeUInt; ACode: Pointer;
  ASize: Integer): THandle;
var
  hThread: THandle;
  dwSuspendCount: DWORD;
  ctx: TContext;
  IPReg: Pointer;
  tryTimes: Integer;
begin
  Result := INVALID_HANDLE_VALUE;
  hThread := OpenThread(THREAD_ALL_ACCESS, FALSE, dwThreadId);
  if (hThread <> 0) and (hThread <> INVALID_HANDLE_VALUE) then
  begin
    dwSuspendCount := SuspendThread(hThread);
    // SuspendThread返回的是被挂起的引用计数,-1的话是失败.
    if dwSuspendCount <> DWORD(-1) then
    begin
      while (GetThreadContext(hThread, ctx)) do
      begin
        tryTimes := 0;
        IPReg := Pointer({$IFDEF CPUX64}ctx.Rip{$ELSE}ctx.EIP{$ENDIF});
        if (NativeInt(IPReg) >= NativeInt(ACode)) and
          (NativeInt(IPReg) <= (NativeInt(ACode) + ASize)) then
        begin
          ResumeThread(hThread);
          Sleep(100);
          SuspendThread(hThread);
          Inc(tryTimes);
          if tryTimes > 5 then
          begin
            Break;
          end;
        end
        else
        begin
          Result := hThread;
          Break;
        end;
      end;
    end;
  end;
end;

function SuspendOtherThread(ACode: Pointer; ASize: Integer): THandles;
var
  hSnap: THandle;
  te: THREADENTRY32;
  nThreadsInProcess: DWORD;
  hThread: THandle;
begin
  Exit;
  hSnap := CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, GetCurrentProcessId());
  te.dwSize := SizeOf(te);

  nThreadsInProcess := 0;
  if (Thread32First(hSnap, te)) then
  begin
    while True do
    begin
      if (te.th32OwnerProcessID = GetCurrentProcessId()) then
      begin

        if (te.th32ThreadID <> GetCurrentThreadId()) then
        begin
          hThread := SuspendOneThread(te.th32ThreadID, ACode, ASize);
          if hThread <> INVALID_HANDLE_VALUE then
          begin
            Inc(nThreadsInProcess);
            SetLength(Result, nThreadsInProcess);
            Result[nThreadsInProcess - 1] := hThread;
          end;
        end
      end;
      te.dwSize := SizeOf(te);
      if not Thread32Next(hSnap, te) then
        Break;
    end;
    // until not Thread32Next(hSnap, te);
  end;

  CloseHandle(hSnap);
end;

procedure ResumOtherThread(threads: THandles);
var
  i: Integer;
begin
  Exit;
  for i := Low(threads) to High(threads) do
  begin
    ResumeThread(threads[i]);
    CloseHandle(threads[i]);
  end;
end;

{
  尝试在指定指针APtr的正负2Gb以内分配内存.32位肯定是这样的.
  64位JMP都是相对的.操作数是32位整数.所以必须保证新的函数在旧函数的正负2GB内.
  否则没法跳转到或者跳转回来.
}
function TryAllocMem(APtr: Pointer; ASize: Cardinal): Pointer;
const
  KB: Int64 = 1024;
  MB: Int64 = 1024 * 1024;
  GB: Int64 = 1024 * 1024 * 1024;
var
  mbi: TMemoryBasicInformation;
  Min, Max: Int64;
  pbAlloc: Pointer;
  sSysInfo: TSystemInfo;
begin

  GetSystemInfo(sSysInfo);
  Min := NativeUInt(APtr) - 2 * GB;
  if Min <= 0 then
    Min := 1;
  Max := NativeUInt(APtr) + 2 * GB;

  Result := nil;
  pbAlloc := Pointer(Min);
  while NativeUInt(pbAlloc) < Max do
  begin
    if (VirtualQuery(pbAlloc, mbi, SizeOf(mbi)) = 0) then
      Break;
    if ((mbi.State or MEM_FREE) = MEM_FREE) and (mbi.RegionSize >= ASize) and
      (mbi.RegionSize >= sSysInfo.dwAllocationGranularity) then
    begin
      pbAlloc :=
        PByte(ULONG_PTR((ULONG_PTR(pbAlloc) + (sSysInfo.dwAllocationGranularity
        - 1)) div sSysInfo.dwAllocationGranularity) *
        sSysInfo.dwAllocationGranularity);
      Result := VirtualAlloc(pbAlloc, ASize, MEM_COMMIT or MEM_RESERVE
{$IFDEF CPUX64}
        or MEM_TOP_DOWN
{$ENDIF}
        , PAGE_EXECUTE_READWRITE);
      if Result <> nil then
        Break;
    end;
    pbAlloc := Pointer(NativeUInt(mbi.BaseAddress) + mbi.RegionSize);
  end;

end;

function HookProc(DLLName, FuncName: PChar; NewFunc: Pointer): Pointer;
var
  h: HMODULE;
begin
  Result := nil;
  h := GetModuleHandle(DLLName);
  if h = 0 then
    h := LoadLibrary(DLLName);
  if h = 0 then
    Exit;
  Result := HookProc(GetProcAddress(h, FuncName), NewFunc);
end;

function HookProc(Func, NewFunc: Pointer): Pointer;
var
  oldProc: POldProc;
  newProc: PNewProc;
  backCodeSize: Integer;
  newProtected, oldProtected: DWORD;
  threads: THandles;
  nOriginalPriority: Integer;
  JmpAfterBackCode: PJMPCode;
begin
  Result := nil;
  if (Func = nil) or (NewFunc = nil) then
    Exit;
  newProc := PNewProc(Func);
  backCodeSize := CalcHookCodeSize(Func);
  if backCodeSize < 0 then
    Exit;
  nOriginalPriority := GetThreadPriority(GetCurrentThread());
  SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  // 改写内存的时候要挂起其他线程,以免造成错误.
  threads := SuspendOtherThread(Func, backCodeSize);
  try
    if not VirtualProtect(Func, backCodeSize, PAGE_EXECUTE_READWRITE,
      oldProtected) then
      Exit;
    //

    Result := TryAllocMem(Func, PageSize);
    // VirtualAlloc(nil, PageSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
    if Result = nil then
      Exit;

    FillMemory(Result, SizeOf(TOldProc), $90);
    oldProc := POldProc(Result);
{$IFDEF USEINT3}
    oldProc.Int3OrNop := $CC;
{$ENDIF}
    oldProc.BackUpCodeSize := backCodeSize;
    oldProc.OldFuncAddr := Func;
    CopyMemory(@oldProc^.BackCode, Func, backCodeSize);
    JmpAfterBackCode := PJMPCode(@oldProc^.BackCode[backCodeSize]);
{$IFDEF USELONGJMP}
    oldProc^.JmpRealFunc.JMP := $25FF;
    oldProc^.JmpRealFunc.JmpOffset := 0;
    oldProc^.JmpRealFunc.Addr := UIntPtr(Int64(Func) + backCodeSize);

    JmpAfterBackCode^.JMP := $25FF;
    JmpAfterBackCode^.JmpOffset := 0;
    JmpAfterBackCode^.Addr := UIntPtr(Int64(Func) + backCodeSize);

    oldProc^.JmpHookFunc.JMP := $25FF;
    oldProc^.JmpHookFunc.JmpOffset := 0;
    oldProc^.JmpHookFunc.Addr := UIntPtr(NewFunc);
{$ELSE}
    oldProc^.JmpRealFunc.JMP := $E9;
    oldProc^.JmpRealFunc.Addr := (NativeInt(Func) + backCodeSize) -
      (NativeInt(@oldProc^.JmpRealFunc) + 5);

    oldProc^.JmpHookFunc.JMP := $E9;
    oldProc^.JmpHookFunc.Addr := NativeInt(NewFunc) -
      (NativeInt(@oldProc^.JmpHookFunc) + 5);
{$ENDIF}
    //
    FillMemory(Func, backCodeSize, $90);

    newProc^.JMP := $E9;
    newProc^.Addr := NativeInt(@oldProc^.JmpHookFunc) -
      (NativeInt(@newProc^.JMP) + 5);;
    // NativeInt(NewFunc) - (NativeInt(@newProc^.JMP) + 5);

    if not VirtualProtect(Func, backCodeSize, oldProtected, newProtected) then
      Exit;
    // 刷新处理器中的指令缓存.以免这部分指令被缓存.执行的时候不一致.
    FlushInstructionCache(GetCurrentProcess(), newProc, backCodeSize);
    FlushInstructionCache(GetCurrentProcess(), oldProc, PageSize);
  finally
    ResumOtherThread(threads);
    SetThreadPriority(GetCurrentThread(), nOriginalPriority);
  end;
end;

function UnHook(OldFunc: Pointer): boolean;
var
  oldProc: POldProc ABSOLUTE OldFunc;
  newProc: PNewProc;
  backCodeSize: Integer;
  newProtected, oldProtected: DWORD;
  threads: THandles;
  nOriginalPriority: Integer;
begin
  Result := FALSE;
  if (OldFunc = nil) then
    Exit;
  backCodeSize := oldProc^.BackUpCodeSize;
  newProc := PNewProc(oldProc^.OldFuncAddr);

  nOriginalPriority := GetThreadPriority(GetCurrentThread());
  SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  threads := SuspendOtherThread(oldProc, SizeOf(TOldProc));
  try
    if not VirtualProtect(newProc, backCodeSize, PAGE_EXECUTE_READWRITE,
      oldProtected) then
      Exit;

    CopyMemory(newProc, @oldProc^.BackCode, oldProc^.BackUpCodeSize);

    if not VirtualProtect(newProc, backCodeSize, oldProtected, newProtected)
    then
      Exit;
    VirtualFree(oldProc, PageSize, MEM_FREE);
    // 刷新处理器中的指令缓存.以免这部分指令被缓存.执行的时候不一致.
    FlushInstructionCache(GetCurrentProcess(), newProc, backCodeSize);
  finally
    ResumOtherThread(threads);
    SetThreadPriority(GetCurrentThread(), nOriginalPriority);
  end;
end;

function CalcInterfaceMethodAddr(var AInterface; AMethodIndex: Integer)
  : Pointer;
type
  TBuf = array [0 .. $FF] of byte;
  PBuf = ^TBuf;
var
  pp: PPointer;
  buf: PBuf;
begin
  pp := PPointer(AInterface)^;
  Inc(pp, AMethodIndex);
  Result := pp^;
  { Delphi的COM对象的方法表比较特别,COM接口实际上是对象的一个成员,实际上调用到
    方法后Self是这个接口成员的地址,所以Delphi的COM方法不直接指向对象方法,而是指向
    一小段机器指令,把Self减去(加负数)这个成员在对象中的偏移,修正好Self指针后再跳转
    到真正对象的方法入口.

    所以这里要"偷窥"一下方法指针指向的头几个字节,如果是修正Self指针的,那么就是Delphi
    实现的COM对象.我们就再往下找真正的对象地址.

    下面代码就是判断和处理Delphi的COM对象的.其他语言实现的COM对象会自动忽略的.
    因为正常的函数头部都是对于栈底的处理或者参数到局部变量的处理代码.
    绝不可能一上来修正第一个参数,也就是Self的指针.所以根据这个来判断.
  }
  buf := Result;
  {
    add Self,[-COM对象相对实现对象偏移]
    JMP  真正的方法
    这样的就是Delphi生成的COM对象方法的前置指令
  }
{$IFDEF CPUX64}
  // add rcx, -COM对象的偏移, JMP 真正对象的方法地址,X64中只有一种stdcall调用约定.其他约定都是stdcall的别名
  if (buf^[0] = $48) and (buf^[1] = $81) and (buf^[2] = $C1) and (buf^[7] = $E9)
  then
    Result := Pointer(NativeInt(@buf[$C]) + PDWORD(@buf^[8])^);
{$ELSE}
  // add [esp + $04],-COM对象的偏移, JMP真正的对象地址,stdcall/cdecl调用约定
  if (buf^[0] = $81) and (buf^[1] = $44) and (buf^[2] = $24) and
    (buf^[03] = $04) and (buf^[8] = $E9) then
    Result := Pointer(NativeInt(@buf[$D]) + PDWORD(@buf^[9])^)
  else // add eax,-COM对象的偏移, JMP真正的对象地址,那就是Register调用约定的
    if (buf^[0] = $05) and (buf^[5] = $E9) then
      Result := Pointer(NativeInt(@buf[$A]) + PDWORD(@buf^[6])^);
{$ENDIF}
end;

function HookInterface(var AInterface; AMethodIndex: Integer;
  NewFunc: Pointer): Pointer;
begin
  Result := HookProc(CalcInterfaceMethodAddr(AInterface, AMethodIndex),
    NewFunc);
end;

end.

此条目发表在Delphi, 未分类分类目录。将固定链接加入收藏夹。

Delphi Hook Library》有 216 条评论

  1. XXOO说:

    搞两个例子就更好了 不错

  2. 匿名说:

    这个library非常好,希望可以放到github上面

  3. 匿名说:

    你这个大概是HOOK自身内的吧,能不能HOOK其他进程

    • admin说:

      只要你能把代码注入到其它进程,自身不自身没有区别.比如你能把这个代码封装到DLL,然后注入其它进程,在DLL里面打钩子.
      这个库仅仅是Hook技术.不涉及注入方式.具体怎么注入其他进程自己想办法.也可以我们底下讨论一下.
      或者说不定后面我会再写一些注入技术的博客.
      不过总得有点自己的东西.如果完全都用别人封装好的东西就没意思了.

  4. 不得闲说:

    呵呵,在看雪上,俺说了可以直接通过需要挂钩的函数动态获取偏移地址的。就是这种写法比较死,不灵活,不同接口下的不同的函数都需要自己算偏移,然后就可以通过算出来的这个偏移来对对应的函数进行挂钩了!今天偶然翻到了以前Hook D3D9中的Present函数的部分代码。
    var
    DllHandle: THandle;
    D3D: IDirect3D9;
    pVTable: Pointer;
    CreatD3d9: function(SDKVersion: LongWord): Pointer;
    d3dpp: D3DPRESENT_PARAMETERS;
    d3ddm: TD3DDisplayMode;
    pD3DDevice: IDirect3DDevice9;
    begin
    DllHandle := LoadLibrary(‘d3d9.dll’);
    CreatD3d9 := WIndows.GetProcAddress(DllHandle,’Direct3DCreate9′);
    if Assigned(CreatD3d9) then
    begin
    D3D := IDirect3D9(CreatD3d9(D3D_SDK_VERSION));
    Result := not Failed(D3D.GetAdapterDisplayMode(D3DADAPTER_DEFAULT, d3ddm ));
    if Result then
    begin
    ZeroMemory( @d3dpp, sizeof(d3dpp));
    d3dpp.Windowed := true;
    d3dpp.SwapEffect := D3DSWAPEFFECT_DISCARD;
    d3dpp.BackBufferFormat := d3ddm.Format;
    ShareData^.AppHandle := frmHandle;
    Result := not Failed(D3D.CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,frmHandle,D3DCREATE_SOFTWARE_VERTEXPROCESSING,@d3dpp,pD3DDevice));
    if Result then
    begin
    //@ShareData^.MsgBackCall := @MsgCallBack;
    pVTable := Pointer(Pinteger(pD3DDevice)^+D3D9PresentOffset*sizeof(DWORD));
    ShareData^.m_nDX9_PresentOffset := phandle(pVTable)^-dllhandle;//获得偏移
    pD3DDevice := nil;
    D3D := nil;
    SendMessage(frmHandle,WM_APP_DllMSG,Integer(ShareData),0);
    end;
    end;
    end
    else Result := False;
    FreeLibrary(DllHandle);
    end;

  5. 爱用软件说:

    偶像,偶像,2ccc上经常看到你,求个QQ 想加一下 :) see my email.

  6. diystar说:

    又来麻烦大侠了。我有一个音量控制软件,准备去窗口化,可是不知道怎么搞,请大侠帮忙看下。用到了hook技术。http://files.cnblogs.com/diystar/vcool_test.rar

  7. beginlove说:

    麻烦大侠, 我想用你这个库HOOK wininet.dll 里的InternetSetCookie 函数,但是似乎没啥效果,我的代码如下: 麻烦你帮我看看,谢谢

    var
    original_InternetSetCookie : function(lpszUrl, lpszCookieName,
    lpszCookieData: LPCWSTR): BOOL; stdcall;

    function replaced_InternetSetCookie(lpszUrl, lpszCookieName,
    lpszCookieData: LPCWSTR): BOOL; stdcall;
    begin
    Form1.Memo1.Lines.Add(‘hook__url=’ + lpszUrl);
    Form1.Memo1.Lines.Add(‘hook__cname=’ + lpszCookieName);
    Form1.Memo1.Lines.Add(‘hook__cdata=’ + lpszCookieData);

    Result := original_InternetSetCookie(lpszUrl, lpszCookieName, lpszCookieData);
    end;

    procedure TForm1.GoClick(Sender: TObject);
    begin
    EmbeddedWB1.Go(Edit1.Text);
    end;

    procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
    begin
    if Assigned(original_InternetSetCookie) then
    UnHook(@original_InternetSetCookie);
    end;

    procedure TForm1.FormCreate(Sender: TObject);
    const
    {$IFDEF UNICODE}
    InternetSetCookieRealName = ‘InternetSetCookieW';
    {$ELSE}
    InternetSetCookieRealName = ‘InternetSetCookieA';
    {$ENDIF}
    begin
    Memo1.Clear;

    if not(Assigned(original_InternetSetCookie)) then
    begin
    @original_InternetSetCookie := HookProc(‘wininet.dll’, InternetSetCookieRealName, @replaced_InternetSetCookie);
    Memo1.Clear;
    end;
    end;

    procedure TForm1.GetCookiesClick(Sender: TObject);
    var
    buf: array[0..1024*4-1] of Char;
    size: DWORD;
    begin
    InternetGetCookie(PChar(Edit1.Text), nil, buf, size);
    Memo1.Lines.Add(string(buf));
    Memo1.Lines.Add(‘======================================’);
    end;

    PS: 非常感谢大侠的无私奉献,这个库非常好
    另搜到一片文章,不过是C#的:http://blog.csdn.net/wangjia184/article/details/4342393,不知用大侠的这个库是否能达到同样的效果

    • admin说:

      我试验了你得代码,发现WebBrowser控件似乎不是调用的InternetSetCookie 函数来设置Cookie的.
      var
      original_InternetSetCookie: function(lpszUrl, lpszCookieName,
      lpszCookieData: LPCWSTR): BOOL; stdcall;

      function replaced_InternetSetCookie(lpszUrl, lpszCookieName, lpszCookieData
      : LPCWSTR): BOOL; stdcall;
      begin
      Form1.Memo1.Lines.Add(‘ hook__url = ‘ + lpszUrl);
      Form1.Memo1.Lines.Add(‘ hook__cname = ‘ + lpszCookieName);
      Form1.Memo1.Lines.Add(‘ hook__cdata = ‘ + lpszCookieData);

      Result := original_InternetSetCookie(lpszUrl, lpszCookieName, lpszCookieData);
      end;

      procedure TForm1.Button1Click(Sender: TObject);
      begin
      //调用这个会走到replaced_InternetSetCookie中,说明Hook没问题
      InternetSetCookie(‘http://www.raysoftware.cn’,’fadfasdf’,’asdfasdfasdf’);
      end;

      procedure TForm1.Button2Click(Sender: TObject);
      begin
      //走不到,说明WebBrowser控件不是调用的InternetSetCookie方法,或者不是在本进程内调用的InternetSetCookie方法
      WebBrowser1.Navigate(‘http://www.2ccc.com’);
      end;

      procedure TForm1.FormCreate(Sender: TObject);
      const
      {$IFDEF UNICODE}
      InternetSetCookieRealName = ‘InternetSetCookieW';
      {$ELSE}
      InternetSetCookieRealName = ‘InternetSetCookieA';
      {$ENDIF}
      begin
      Memo1.Clear;

      if not(Assigned(original_InternetSetCookie)) then
      begin
      @original_InternetSetCookie := HookProc(‘Wininet.dll’,
      InternetSetCookieRealName, @replaced_InternetSetCookie);
      Memo1.Clear;
      end;

      end;

      • beginlove说:

        感谢大侠,我昨天又研究了一晚上,发现的确是你所说的原因

        IE控件是用
        InternetSetCookieEx : function(lpszUrl, lpszCookieName,
        lpszCookieData: LPCWSTR; dwFlags: DWORD; lpReserved: Pointer): DWORD; stdcall;

        InternetGetCookieEx : function(lpszUrl, lpszCookieName,
        lpszCookieData: LPCWSTR; var lpdwSize: DWORD; dwFlags: DWORD; lpReserved: Pointer): BOOL; stdcall;

        两个函数来操作内存的,HOOK 这两个函数就可以了。

        再次感谢!

  8. 匿名说:

    VirtualProtect 这个可以HOOK吗?

  9. 匿名说:

    老大,你试一下hook VirtualProtect。会有问题的。 在myVirtualProtect中unhook.

  10. 匿名说:

    这个可以HOOK某个代码段么? 比如XXXXXXXX,截取寄存器的值

  11. djsf说:

    uses
    SysUtils,
    Windows,
    Classes,
    messages,
    WinSock,

    unitHook in ‘unitHook.pas';

    {$R *.res}
    const
    WM_HOOKKEY = WM_USER + $1000;
    LLKHF_ALTDOWN = $20;
    WH_KEYBOARD_LL = 13;
    HOOK_MEM_FILENAME = ‘tmp.hkt';
    mycalsname=’ZwelL';
    const
    WM_CapIp = WM_USER + 200;

    {
    type
    //要HOOK的API函数定义

    TSockProc = function (s: TSocket; var Buf; len, flags: Integer): Integer; stdcall;
    TConnect =function (s: TSocket; var name: TSockAddr; namelen: Integer): Integer; stdcall;

    PJmpCode = ^TJmpCode;
    TJmpCode = packed record
    JmpCode: BYTE;
    Address: TSockProc;
    MovEAX: Array [0..2] of BYTE;
    end;
    }
    type
    Pkeyhook=^Tkeyhook;
    Tkeyhook=record
    startPid:DWORD;
    Enabled:boolean;
    fhProcess: THandle; //保存本进程在远程进程中的句柄
    end;
    var
    hhk1: HHOOK;
    Hook: array[0..2] of TApiHookInfo; //内存映射
    MemFile: THandle;
    PstartPid:Pkeyhook=nil;
    g_hForm:integer=0;
    Oldss:string=”;
    Fbuffer:array[0..254] of char;

    function NewOpenProcess(dwDesiredAccess: DWORD; bInheritHandle: BOOL; dwProcessId: DWORD): THandle; stdcall;
    begin
    try
    Hook[0].Lock;
    if PstartPid^.startPid = dwProcessId then
    begin
    result := 0;
    OutputDebugStr(‘禁止结束1!’);
    Exit;
    end;
    try
    Hook[0].UnHook;
    Result :=OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId);
    finally
    Hook[0].Hook;
    end;
    finally
    Hook[0].UnLock;
    end;
    end;
    {–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–}//安装API Hook
    function NewTerminateProcess(hProcess: THandle;uExitCode: UINT): BOOL; Stdcall;
    begin
    try
    Hook[1].Lock;
    result:=false;
    if (PstartPid^.fhProcess>0)and(PstartPid^.fhProcess = hProcess) then
    begin
    OutputDebugStr(‘禁止结束2!’);
    result := true;
    exit;
    end;
    try
    Hook[1].UnHook;
    Result :=TerminateProcess(hProcess, uExitCode);
    finally
    Hook[1].Hook;
    end;
    finally
    Hook[1].UnLock;
    end;
    end;

    function Newsend2(s: TSocket; const Buf; len, flags: Integer): Integer; stdcall;
    var dwSize: cardinal;iAddr,jAddr:TSockAddr;i:integer;
    ss:string;
    AsciiBuffer: string;
    hh:TSockAddrIn;
    dprot:integer;
    hProcess:THandle;
    mybuf:array[0..100] of char;
    str:array of Ansichar;
    begin
    try

    Hook[2].Lock;
    OutputDebugStr(‘拦截Newsend2!’);
    try

    try
    Hook[2].UnHook;
    Result :=send(s,buf,len,flags);
    finally
    Hook[2].Hook;
    end;
    finally
    Hook[2].UnLock;
    end;

    except

    end;
    end;

    procedure InitHook;
    begin
    g_hForm := FindWindow(‘ZwelL’,nil);
    getmodulefilename(GetModuleHandle(nil), Fbuffer, sizeof(Fbuffer));
    //try

    Hook[0]:=TApiHookInfo.Create;
    Hook[0].init(‘kernel32.dll’, ‘OpenProcess’,@NewOpenProcess);

    Hook[1]:=TApiHookInfo.Create;
    Hook[1].init(‘kernel32.dll’, ‘TerminateProcess’, @NewTerminateProcess);

    Hook[2]:=TApiHookInfo.Create;
    Hook[2].init(‘wsock32.dll’,’send’, @Newsend2);

    OutputDebugStr(strpas(Fbuffer)+':成功!’);
    //except

    //end;
    end;//删除API Hook
    procedure UninitHook;
    var I: Integer;
    begin
    //try
    // OutputDebugStr(‘UninitHook:’+strpas(Fbuffer));
    // Hook[0].UnHook;
    // Hook[1].UnHook;
    // Hook[2].UnHook;
    // Hook[3].UnHook;
    for I := 0 to High(Hook) do
    begin
    //Hook[I].Destroy;
    if assigned(Hook[I]) then
    begin
    Hook[i].Free;
    Hook[I]:=nil;
    end;
    end;
    //except

    //end;
    end;{–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–}//内存映射共想
    procedure MemShared();
    begin
    MemFile:=OpenFileMapping(FILE_MAP_ALL_ACCESS,False, HOOK_MEM_FILENAME); //打开内存映射文件
    if MemFile = 0 then
    begin //打开失败则衉c2建内存映射文件
    MemFile := CreateFileMapping($FFFFFFFF, nil, PAGE_READWRITE, 0,sizeof(Tkeyhook), HOOK_MEM_FILENAME);
    end;
    if MemFile 0 then //映射文件到变量
    begin
    // startPid := MapViewOfFile(MemFile,FILE_MAP_ALL_ACCESS,0,0,0);
    PstartPid := Pkeyhook(MapViewOfFile(MemFile,FILE_MAP_ALL_ACCESS,0,0,0));
    // PstartPid^.Enabled:=true;
    //PstartPid^.fhProcess:=0;
    end;
    end;//传递消息
    function HookProc1(ncode: Integer; wparam: WPARAM; lparam: LPARAM): LRESULT stdcall;
    begin
    Result := CallNextHookEx(hhk1, nCode, wParam, lParam);
    end;//开始HOOK

    procedure StartHook(pid: DWORD); stdcall;
    var dwThreadId: DWORD;
    begin
    PstartPid^.startPid:= pid;
    PstartPid^.fhProcess:=0;
    PstartPid^.Enabled:=true;
    //OutputDebugStr(‘gozi安装成!’);
    dwThreadId:=0;
    hhk1 := SetWindowsHookEx(WH_CALLWNDPROC, HookProc1, hInstance, dwThreadId);
    end;//结束HOOK
    procedure EndHook; stdcall;
    begin
    // OutputDebugStr(‘UninitHook0:’+strpas(Fbuffer));
    if hhk10 then
    begin
    UninitHook; //DLL删除
    UnhookWindowsHookEx(hhk1);
    hhk1:=0;
    end;
    end;//环境处理
    procedure DllEntry(dwResaon: DWORD);
    begin
    case dwResaon of
    DLL_PROCESS_ATTACH:
    InitHook; //DLL载入
    DLL_PROCESS_DETACH:
    begin
    if Assigned(PstartPid) then
    begin
    UnmapViewOfFile(PstartPid);
    PstartPid := nil;
    CloseHandle(MemFile);

    end;
    UninitHook; //DLL删除
    end;
    end;
    end;
    exports
    StartHook,
    EndHook;
    begin
    MemShared; { 分配DLL程序到 DllProc 变量 }
    DllProc := @DllEntry; { 调用DLL加载处理 }
    DllEntry(DLL_PROCESS_ATTACH);
    end.

    这是代码,其中 unitHook.pas就是您的文件。

    • djsf说:

      HOOK后,如果HOOK不卸载,没有问题,如果一卸载就崩溃了。而且有网络连接的进程,卸载后都会崩溃。如金山,360卫士等,这个。。。
      如果是火狐浏览器,会打不开的。直接崩溃。您试试。

  12. djsf说:

    昨天代码贴错,那是另一个HOOKAPI。
    现在这个才是使用老大的HookUtils.pas
    uses
    SysUtils,
    Windows,
    Classes,
    messages,
    WinSock2,
    HookUtils in ‘HookUtils.pas';

    {$R *.res}
    const
    WM_HOOKKEY = WM_USER + $1000;
    LLKHF_ALTDOWN = $20;
    WH_KEYBOARD_LL = 13;
    HOOK_MEM_FILENAME = ‘tmp.hkt';
    mycalsname=’ZwelL';
    const
    WM_CapIp = WM_USER + 200;

    {
    type
    //要HOOK的API函数定义

    TSockProc = function (s: TSocket; var Buf; len, flags: Integer): Integer; stdcall;
    TConnect =function (s: TSocket; var name: TSockAddr; namelen: Integer): Integer; stdcall;

    PJmpCode = ^TJmpCode;
    TJmpCode = packed record
    JmpCode: BYTE;
    Address: TSockProc;
    MovEAX: Array [0..2] of BYTE;
    end;
    }
    type
    Pkeyhook=^Tkeyhook;
    Tkeyhook=record
    startPid:DWORD;
    Enabled:boolean;
    fhProcess: THandle; //保存本进程在远程进程中的句柄
    end;
    var
    hhk1: HHOOK;
    MemFile: THandle;
    PstartPid:Pkeyhook=nil;
    g_hForm:integer=0;
    Oldss:string=”;
    Fbuffer:array[0..254] of char;

    OldOpenProcess:function(dwDesiredAccess: DWORD; bInheritHandle: BOOL; dwProcessId: DWORD): THandle; stdcall;
    OldTerminateProcess:function(hProcess: THandle;uExitCode: UINT): BOOL; Stdcall;
    Oldsend2:function(s: TSocket; const Buf; len, flags: Integer): Integer; stdcall;
    OldConnect2:function(s: TSocket; var name: TSockAddr; namelen: Integer): Integer; stdcall;

    procedure errjilu(const ABuffer:string);
    var FileStream: TFileStream;
    aabb:TStrings;
    begin
    aabb:=TStringList.Create;
    if fileexists(‘c:\errer.txt’) then
    begin
    aabb.LoadFromFile(‘c:\errer.txt’);
    if aabb.Count>500 then
    aabb.Delete(0);
    end;
    aabb.Add(datetimetostr(now)+':’+ABuffer);
    aabb.SaveToFile(‘c:\errer.txt’,TEncoding.Unicode);
    aabb.Free;
    end;
    procedure OutputDebugStr(const ADebugInfo: string); //输出调试信息
    begin
    OutputDebugString(PChar(ADebugInfo+#13+#10));
    end;

    //拦截MessageBoxA
    function SendMessagebufstring(buf:string;const vv:integer):integer;
    var ds: TCopyDataStruct;
    begin
    result:=0;
    if g_hForm>0 then
    begin
    ds.dwData:=vv;
    ds.cbData :=ByteLength(buf)+2;//sizeof(buf);
    getmem(ds.lpData,ds.cbData);
    ds.lpData:=pchar(buf+#0);
    result:=SendMessage (g_hForm, WM_COPYDATA,0,Cardinal(@ds)); // 向管理器发送消息
    //freemem(ds.lpData);
    end;
    end;

    function NewOpenProcess(dwDesiredAccess: DWORD; bInheritHandle: BOOL; dwProcessId: DWORD): THandle; stdcall;
    begin
    try
    if PstartPid^.startPid = dwProcessId then
    begin
    result := 0;
    OutputDebugStr(‘禁止结束1!’);
    Exit;
    end;
    try
    Result :=OldOpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId);
    finally
    end;
    finally
    end;
    end;
    {–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–+–}//安装API Hook
    function NewTerminateProcess(hProcess: THandle;uExitCode: UINT): BOOL; Stdcall;
    begin
    try
    result:=false;
    if (PstartPid^.fhProcess>0)and(PstartPid^.fhProcess = hProcess) then
    begin
    //showmessage(‘不准关闭我!’);
    OutputDebugStr(‘禁止结束2!’);
    result := true;
    exit;
    end;
    try
    Result :=OldTerminateProcess(hProcess, uExitCode);
    finally
    end;
    finally
    end;
    end;
    //网络===============================================================================
    //协议识别程序
    {
    function GetRemoteAddr(FSocket:TSocket): TSockAddrIn;
    var
    Size: Integer;
    begin
    try
    FillChar(Result, SizeOf(Result), 0);
    Size := SizeOf(Result);
    if getpeername(FSocket, Result, Size) 0 then
    FillChar(Result, SizeOf(Result), 0);
    finally