我可以在链接库中挂钩函数吗?

时间:2010-08-26 16:11:58

标签: windows hook code-injection easyhook

使用EasyHook我已经成功地为各种C ++类连接了导出函数和已知的vtable函数。在所有这些情况下,目标程序都使用了DLL。

如果我知道函数入口点的地址,那么当一个库链接到目标程序而不是一个单独的库时,是否可以这样做?

1 个答案:

答案 0 :(得分:2)

EasyHook一起显示,您可以挂钩任何地址可计算的子程序。

在我的案例中,在OpenSSL中挂钩静态链接SSL_read和SSL_write就像用我喜欢的调试器识别偏移然后安装钩子一样简单。

// delegate for EasyHook:
[UnmanagedFunctionPointer(CallingConvention.Cdecl, 
    SetLastError = true, CharSet = CharSet.Ansi)]
delegate Int32 SLL_readDelegate(IntPtr SSL_ptr, IntPtr buffer, Int32 length);

// import SSL_read (I actually did it manually, but this will work in most cases)
/* proto from ssl_lib.c -> int SSL_read(SSL *s,void *buf,int num) */
[DllImport("ssleay32.dll", SetLastError = true)]
public static extern Int32 SSL_read(IntPtr ssl, IntPtr buffer, Int32 len);

// the new routine
static Int32 SSL_readCallback(IntPtr SSL_ptr, IntPtr buffer, Int32 length)
{
    /* call the imported SSL_read */
    int ret = SSL_read(SSL_ptr, buffer, length);
    /* TODO: your code here, e.g:
     * string log_me = Marshal.PtrToString(buffer, ret);
     */
    return ret;
}

现在剩下的就是安装钩子:

private LocalHook sslReadHook;

public void Run(RemoteHooking.IContext InContext, String InArg1)
{
    // ... initialization code omitted for brevity

    /* the value for ssl_read_addr is made up in this example
     * you'll need to study your target and how it's loaded(?) to 
     * identify the addresses you want to hook
     */
    int ssl_read_addr = 0x12345678; /* made up for examples sake */
    sslReadHook = LocalHook.Create(new IntPtr(ssl_read_addr),
        new SSL_readDelegate(SSL_readCallback), this);

    // ...
}

我应该提一下,在这个例子中你需要libeay32.dll和ssleay32.dll,因为后者依赖于前者。

快乐的挂钩!