DLL注入——使用SetWindowsHookEx函数实现消息钩取

MSDN:

SetWindowsHookEx Function


The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain. You would install a hook procedure to monitor the system for certain types of events. These events are associated either with a specific thread or with all threads in the same desktop as the calling thread.

Syntax

HHOOK SetWindowsHookEx(      

    int idHook,
    HOOKPROC lpfn,
    HINSTANCE hMod,
    DWORD dwThreadId//为0时表示全局钩取
);

Parameters

idHook
[in] Specifies the type of hook procedure to be installed. This parameter can be one of the following values.
WH_CALLWNDPROC
Installs a hook procedure that monitors messages before the system sends them to the destination window procedure. For more information, see the CallWndProc hook procedure.
WH_CALLWNDPROCRET
Installs a hook procedure that monitors messages after they have been processed by the destination window procedure. For more information, see the CallWndRetProc hook procedure.
WH_CBT
Installs a hook procedure that receives notifications useful to a computer-based training (CBT) application. For more information, see the CBTProc hook procedure.
WH_DEBUG
Installs a hook procedure useful for debugging other hook procedures. For more information, see the DebugProc hook procedure.
WH_FOREGROUNDIDLE
Installs a hook procedure that will be called when the application's foreground thread is about to become idle. This hook is useful for performing low priority tasks during idle time. For more information, see the ForegroundIdleProc hook procedure.
WH_GETMESSAGE
Installs a hook procedure that monitors messages posted to a message queue. For more information, see the GetMsgProc hook procedure.
WH_JOURNALPLAYBACK
Installs a hook procedure that posts messages previously recorded by a WH_JOURNALRECORD hook procedure. For more information, see the JournalPlaybackProc hook procedure.
WH_JOURNALRECORD
Installs a hook procedure that records input messages posted to the system message queue. This hook is useful for recording macros. For more information, see the JournalRecordProc hook procedure.
WH_KEYBOARD
Installs a hook procedure that monitors keystroke messages. For more information, see the KeyboardProc hook procedure.
WH_KEYBOARD_LL
Windows NT/2000/XP: Installs a hook procedure that monitors low-level keyboard input events. For more information, see the LowLevelKeyboardProc hook procedure.
WH_MOUSE
Installs a hook procedure that monitors mouse messages. For more information, see the MouseProc hook procedure.
WH_MOUSE_LL
Windows NT/2000/XP: Installs a hook procedure that monitors low-level mouse input events. For more information, see the LowLevelMouseProc hook procedure.
WH_MSGFILTER
Installs a hook procedure that monitors messages generated as a result of an input event in a dialog box, message box, menu, or scroll bar. For more information, see the MessageProc hook procedure.
WH_SHELL
Installs a hook procedure that receives notifications useful to shell applications. For more information, see the ShellProc hook procedure.
WH_SYSMSGFILTER
Installs a hook procedure that monitors messages generated as a result of an input event in a dialog box, message box, menu, or scroll bar. The hook procedure monitors these messages for all applications in the same desktop as the calling thread. For more information, see the SysMsgProc hook procedure.
lpfn
[in] Pointer to the hook procedure. If the dwThreadId parameter is zero or specifies the identifier of a thread created by a different process, the lpfn parameter must point to a hook procedure in a DLL. Otherwise, lpfn can point to a hook procedure in the code associated with the current process.
hMod
[in] Handle to the DLL containing the hook procedure pointed to by the lpfn parameter. The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by the current process and if the hook procedure is within the code associated with the current process.
dwThreadId
[in] Specifies the identifier of the thread with which the hook procedure is to be associated. If this parameter is zero, the hook procedure is associated with all existing threads running in the same desktop as the calling thread.

Return Value

If the function succeeds, the return value is the handle to the hook procedure.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

SetWindowsHookEx can be used to inject a DLL into another process. A
32-bit DLL cannot be injected into a 64-bit process, and a 64-bit DLL cannot be
injected into a 32-bit process. If an application requires the use of hooks in
other processes, it is required that a 32-bit application call
SetWindowsHookEx to inject a 32-bit DLL into 32-bit processes, and a
64-bit application call SetWindowsHookEx to inject a 64-bit DLL into
64-bit processes. The 32-bit and 64-bit DLLs must have different names.

An error may occur if the hMod parameter is NULL and the
dwThreadId parameter is zero or specifies the identifier of a thread
created by another process.

Calling the CallNextHookEx
function to chain to the next hook procedure is optional, but it is highly
recommended; otherwise, other applications that have installed hooks will not
receive hook notifications and may behave incorrectly as a result. You should
call CallNextHookEx unless you absolutely need to prevent the
notification from being seen by other applications.

Before terminating, an application must call the UnhookWindowsHookEx
function to free system resources associated with the hook.

The scope of a hook depends on the hook type. Some hooks can be set only with
global scope; others can also be set for only a specific thread, as shown in the
following table.

Hook Scope
WH_CALLWNDPROC Thread or global
WH_CALLWNDPROCRET Thread or global
WH_CBT Thread or global
WH_DEBUG Thread or global
WH_FOREGROUNDIDLE Thread or global
WH_GETMESSAGE Thread or global
WH_JOURNALPLAYBACK Global only
WH_JOURNALRECORD Global only
WH_KEYBOARD Thread or global
WH_KEYBOARD_LL Global only
WH_MOUSE Thread or global
WH_MOUSE_LL Global only
WH_MSGFILTER Thread or global
WH_SHELL Thread or global
WH_SYSMSGFILTER Global only

For a specified hook type, thread hooks are called first, then global hooks.

The global hooks are a shared resource, and installing one affects all
applications in the same desktop as the calling thread. All global hook
functions must be in libraries. Global hooks should be restricted to
special-purpose applications or to use as a development aid during application
debugging. Libraries that no longer need a hook should remove its hook
procedure.

Windows 95/98/Me: SetWindowsHookEx is supported by the
Microsoft Layer for Unicode (MSLU). However, it does not make conversions. To
see Unicode messages, notifications, and so forth, you must subclass the window.
To use this version of the API, you must add certain files to your application,
as outlined in Installing and Releasing Hook
Procedures.

HOOK 记事本键盘输入:

主程序:

#include <iostream>
#include "windows.h" #define DEF_DLL_NAME "KeyHook.dll"
#define DEF_HOOKSTART "HookStart"
#define DEF_HOOKSTOP "HookStop" typedef void (*PFN_HOOKSTART)();
typedef void (*PFN_HOOKSTOP)(); void main()
{
HMODULE hDll = NULL;
PFN_HOOKSTART HookStart = NULL;
PFN_HOOKSTOP HookStop = NULL;
char ch = 0; // 加载KeyHook.dll HMODULE —— Handle to a module.
hDll = LoadLibraryA(DEF_DLL_NAME);
if (hDll == NULL)
{
printf("LoadLibrary(%s) failed!!! [0x%08X]\n", DEF_DLL_NAME, GetLastError());
return;
}
//printf("hDll(0x%08X)\n", hDll);
// 获取导出函数地址
HookStart = (PFN_HOOKSTART)GetProcAddress(hDll, DEF_HOOKSTART);
//printf("HookStart(0x%08X)\n", HookStart);
HookStop = (PFN_HOOKSTOP)GetProcAddress(hDll, DEF_HOOKSTOP);
//printf("HookStop(0x%08X)\n", HookStop);
// 开始勾取
HookStart(); // 等待直到用户输入q
printf("input 'q' to quit!\n");
while (getchar() != 'q')
;//循环空 // 停止勾取
HookStop(); // 卸载KeyHook.dll
FreeLibrary(hDll);
}

全局DLL:(hook中筛选记事本进程)

#include "pch.h"
#include <windows.h>
#define DEF_PROCESS_NAME "notepad.exe"
HINSTANCE g_hInstance = NULL;
HHOOK g_hHook = NULL;
HWND g_hWnd = NULL;
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
g_hInstance = hModule;
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
} LRESULT CALLBACK KeyboardProc(int nCode,
WPARAM wParam,
LPARAM lParam) {
char szPath[MAX_PATH] = { 0, };
char* p = NULL;
TCHAR tempChar[256] = { 0};
if (nCode == HC_ACTION) {
/*
wParam [in] Specifies the virtual-key code of the key that generated the keystroke message. lParam [in] Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag. For more information about the lParam parameter, see Keystroke Message Flags. This parameter can be one or more of the following values.
0-15//低2字节 指定重复计数。该值是由于用户按住键而重复击键的次数。
Specifies the repeat count. The value is the number of times the keystroke is repeated as a result of the user's holding down the key.
16-23//第三字节 指定扫描码。其值取决于OEM。
Specifies the scan code. The value depends on the OEM.
24//高字节最低位 指定该键是扩展键,例如功能键或者数字键盘上的键。如果键是扩展键,则值为1;否则,它是0。&0x01000000
Specifies whether the key is an extended key, such as a function key or a key on the numeric keypad. The value is 1 if the key is an extended key; otherwise, it is 0.
25-28//高字节 第2位到第5位 保留
Reserved.
29高字节的第6位 指定上下文代码。如果ALT键按下,则值为1;否则,它是0。
Specifies the context code. The value is 1 if the ALT key is down; otherwise, it is 0.
30高字节的第7位 指定前一个键的状态。如果在消息发送之前键down,则值为1;如果键是up的,则为0。 &0x40000000==0时释放,1时按下
Specifies the previous key state. The value is 1 if the key is down before the message is sent; it is 0 if the key is up.
31高字节的第8位(最高位) 指定转换状态。如果键被按下,值为0,如果键被释放,值为1。 &0x80000000==0时释放,1时按下
Specifies the transition state. The value is 0 if the key is being pressed and 1 if it is being released.
*/
if ((lParam & 0x80000000)) {//最高位0表示按下,1表示释放
GetModuleFileNameA(NULL, szPath, MAX_PATH);
p = strrchr(szPath, '\\');
tempChar[0] = MapVirtualKey(wParam, MAPVK_VK_TO_CHAR);
tempChar[1] = TEXT('\0');
if (!_stricmp(p + 1, DEF_PROCESS_NAME)) { if (isalpha(tempChar[0]) || isalnum(tempChar[0])) {
MessageBox(NULL, tempChar, TEXT("input"), 0);
} else {
wsprintf(tempChar, TEXT("0x%02X"), wParam);
MessageBox(NULL, tempChar, TEXT("special"), 0);
}
//return 1;
}
}
} return CallNextHookEx(g_hHook, nCode, wParam, lParam);
}
#ifdef __cplusplus
extern "C" {
#endif
__declspec(dllexport) void HookStart()
{
g_hHook = SetWindowsHookEx(WH_KEYBOARD, KeyboardProc, g_hInstance, 0);
} __declspec(dllexport) void HookStop()
{
if (g_hHook)
{
UnhookWindowsHookEx(g_hHook);
g_hHook = NULL;
}
}
#ifdef __cplusplus
}
#endif

指定进程注入:

1、获取进程ID 通过进程名称

2、编写DLL,将需要的函数进行导出

3、获取目标进程中的线程ID,为了保证线程ID的有效性,把所有的线程ID都获取出来,一一注入,直到注入成功

4、SetWindowsHookEx,实现钩子注入

DLL:

// dllmain.cpp : 定义 DLL 应用程序的入口点。
#include "pch.h"
#include <windows.h>
#include <Tlhelp32.h>
#include <tchar.h>
#include <vector>
using std::vector;
#define DEF_PROCESS_NAME "notepad.exe"
HINSTANCE g_hInstance = NULL;
HHOOK g_hHook = NULL;
HWND g_hWnd = NULL;
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
g_hInstance = hModule;
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
} LRESULT CALLBACK KeyboardProc(int nCode,
WPARAM wParam,
LPARAM lParam) {
char szPath[MAX_PATH] = { 0, };
char* p = NULL;
TCHAR tempChar[256] = { 0};
if (nCode == HC_ACTION) {
/*
wParam [in] Specifies the virtual-key code of the key that generated the keystroke message. lParam [in] Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag. For more information about the lParam parameter, see Keystroke Message Flags. This parameter can be one or more of the following values.
0-15//低2字节 指定重复计数。该值是由于用户按住键而重复击键的次数。
Specifies the repeat count. The value is the number of times the keystroke is repeated as a result of the user's holding down the key.
16-23//第三字节 指定扫描码。其值取决于OEM。
Specifies the scan code. The value depends on the OEM.
24//高字节最低位 指定该键是扩展键,例如功能键或者数字键盘上的键。如果键是扩展键,则值为1;否则,它是0。&0x01000000
Specifies whether the key is an extended key, such as a function key or a key on the numeric keypad. The value is 1 if the key is an extended key; otherwise, it is 0.
25-28//高字节 第2位到第5位 保留
Reserved.
29高字节的第6位 指定上下文代码。如果ALT键按下,则值为1;否则,它是0。
Specifies the context code. The value is 1 if the ALT key is down; otherwise, it is 0.
30高字节的第7位 指定前一个键的状态。如果在消息发送之前键down,则值为1;如果键是up的,则为0。 &0x40000000==0时释放,1时按下
Specifies the previous key state. The value is 1 if the key is down before the message is sent; it is 0 if the key is up.
31高字节的第8位(最高位) 指定转换状态。如果键被按下,值为0,如果键被释放,值为1。 &0x80000000==0时释放,1时按下
Specifies the transition state. The value is 0 if the key is being pressed and 1 if it is being released.
*/
if ((lParam & 0x80000000)) {//最高位0表示按下,1表示释放
GetModuleFileNameA(NULL, szPath, MAX_PATH);
p = strrchr(szPath, '\\');
tempChar[0] = MapVirtualKey(wParam, MAPVK_VK_TO_CHAR);
tempChar[1] = TEXT('\0');
if (!_stricmp(p + 1, DEF_PROCESS_NAME)) { if (isalpha(tempChar[0]) || isalnum(tempChar[0])) {
MessageBox(NULL, tempChar, TEXT("input"), 0);
} else {
wsprintf(tempChar, TEXT("0x%02X"), wParam);
MessageBox(NULL, tempChar, TEXT("special"), 0);
}
//return 1;
}
}
} return CallNextHookEx(g_hHook, nCode, wParam, lParam);
}
DWORD GetProcessIDByName(const TCHAR* pName)
{
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (INVALID_HANDLE_VALUE == hSnapshot) {
return NULL;
}
PROCESSENTRY32 pe = { sizeof(pe) };//等同于dwSize赋值
for (BOOL ret = Process32First(hSnapshot, &pe); ret; ret = Process32Next(hSnapshot, &pe)) {
if (_tcsicmp(pe.szExeFile, pName) == 0) {
CloseHandle(hSnapshot);
return pe.th32ProcessID;
}
//printf("%-6d %s\n", pe.th32ProcessID, pe.szExeFile);
}
CloseHandle(hSnapshot);
return 0;
}
vector<HANDLE> GetThreadIDByPID(DWORD pID) {
//DWORD pID = GetProcessIDByName(pName);
vector<HANDLE> ThreadIdentify;
THREADENTRY32 te;
te.dwSize = sizeof(te);//必须,否则失败
HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (Thread32First(h, &te))
{
do
{
if (te.th32OwnerProcessID == pID)
{ ThreadIdentify.emplace_back((HANDLE)te.th32ThreadID);
}
} while (Thread32Next(h, &te)); }
CloseHandle(h);
return ThreadIdentify;
}
/*
vector<HANDLE> GetThreadIDByName(const TCHAR* pName) {
DWORD pID = GetProcessIDByName(pName);
vector<HANDLE> ThreadIdentify;
THREADENTRY32 te;
te.dwSize = sizeof(te);
HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (Thread32First(h, &te))
{
do
{
if (te.th32OwnerProcessID == pID)
{ ThreadIdentify.emplace_back((HANDLE)te.th32ThreadID);
}
} while (Thread32Next(h, &te)); }
CloseHandle(h);
return ThreadIdentify;
}
*/ #ifdef __cplusplus
extern "C" {
#endif
__declspec(dllexport) void HookStart()
{
vector<HANDLE> ThreadIdentify;
DWORD pID = GetProcessIDByName(_T(DEF_PROCESS_NAME));
ThreadIdentify= GetThreadIDByPID(pID);
for (int i = 0; i < ThreadIdentify.size(); ++i)
{
g_hHook = SetWindowsHookEx(WH_KEYBOARD, KeyboardProc, g_hInstance, (DWORD)ThreadIdentify[i]);
if (g_hHook != NULL)
{
break;
}
}
} __declspec(dllexport) void HookStop()
{
if (g_hHook)
{
UnhookWindowsHookEx(g_hHook);
g_hHook = NULL;
}
}
#ifdef __cplusplus
}
#endif

Remarks

The calling application must set the dwSize member of THREADENTRY32 to the size, in bytes, of the structure.

Thread32First changes dwSize to the number of bytes written to the structure.

This number is never greater than the initial value of dwSize, but it can be smaller. If the value is smaller, do not rely on the values of members whose offsets are greater than this value.

To retrieve information about other threads recorded in the same snapshot, use the Thread32Next function.

注意:32位要使用32位程序注入32位的dll,否则会造成程序卡死

 

《逆向工程核心原理》Windows消息钩取的更多相关文章

  1. DLL注入之windows消息钩取

    DLL注入之windows消息钩取 0x00 通过Windows消息的钩取 通过Windows消息钩取可以使用SetWindowsHookEx.该函数的原型如下: SetWindowsHookEx( ...

  2. Reverse Core 第三部分 - 21章 - Windows消息钩取

    @author: dlive @date: 2016/12/19 0x01 SetWindowsHookEx() HHOOK SetWindowsHookEx( int idHook, //hook ...

  3. Windows消息钩取

    @author: dlive @date: 2016/12/19 0x01 SetWindowsHookEx() HHOOK SetWindowsHookEx( int idHook, //hook ...

  4. 逆向学习-Windows消息钩取

    钩子 Hook,就是钩子.偷看或截取信息时所用的手段或工具. 消息钩子 常规Windows流: 1.发生键盘输入事件时,WM_KEYDOWN消息被添加到[OS message queue]. 2.OS ...

  5. SetWindowsHookEx 消息钩取进程卡死

    <逆向工程核心原理> windows消息钩取部分的例子在win10下卡死,失败.通过搜索发现,要保证钩取的进程与注入的dll要保持cpu平台相同 SetWindowsHookEx可用于将d ...

  6. windows消息钩子注册底层机制浅析

    标 题: [原创]消息钩子注册浅析 作 者: RootSuLe 时 间: 2011-06-18,23:10:34 链 接: http://bbs.pediy.com/showthread.php?t= ...

  7. x64 下记事本WriteFile() API钩取

    <逆向工程核心原理>第30章 记事本WriteFile() API钩取 原文是在x86下,而在x64下函数调用方式为fastcall,前4个参数保存在寄存器中.在原代码基础上进行修改: 1 ...

  8. Windows消息机制详解

    消息是指什么?      消息系统对于一个win32程序来说十分重要,它是一个程序运行的动力源泉.一个消息,是系统定义的一个32位的值,他唯一的定义了一个事件,向 Windows发出一个通知,告诉应用 ...

  9. Windows消息机制知识点总结

    1.windows消息类型 以下四种,前三种是系统消息,范围在[0x0000, 0x03ff],第四种是用户自定义消息. 1.1 窗口消息 与窗口的内部运作有关,如创建窗口,绘制窗口,销毁窗口等.可以 ...

随机推荐

  1. 推荐一个vuepress模板,一键快速搭建文档站

    介绍 vuepress-template是一个简单的VuePress案例模板,目的是让用户可以直接clone这个仓库,作为初始化一个VuePress网站启动项目,然后在这个项目的基础上新增自定义配置和 ...

  2. js 实现前端路由的方法

    js 实现前端路由的方法 前端路由原理 History API https://developer.mozilla.org/en-US/docs/Web/API/History_API https:/ ...

  3. calendar merge date

    calendar merge date componentDidMount () { const { monthDays, // monthDates, } = this.props; const d ...

  4. ng 基础

    文档 组件的工作只管用户体验,而不用顾及其它. 它应该提供用于数据绑定的属性和方法,以便作为视图和应用逻辑的中介者 组件应该把诸如从服务器获取数据.验证用户输入或直接往控制台中写日志等工作委托给各种服 ...

  5. 以代码为剑、数学为犁,SPC构建NGK算力生态体系

    人类创造工具,工具反过来也改变着人类.以区块链为核心的货币革命率先吹响了对金融世界重塑的号角.以代码为剑.数学为犁,区块链构建了新的网路信任体系,这是一切的开始.基于此,NGK区块链技术将赋能实体产业 ...

  6. Renice INC:法国葡萄酒为什么独占世界鳌头?

    提起葡萄酒,许多人首先想到的就是法国.法国有着悠久的酿酒历史和精湛工艺,"82年的拉菲"几乎成了大众认识葡萄酒的代名词.市面上的进口葡萄酒琳琅满目,原产国众多,意大利.西班牙.美国 ...

  7. NGK:APP一站式挖矿高收益项目

    NGK是10月中旬刚上线的公链项目,采用手机挖矿形式.NGK数字增益平台,200美金即可入场,收益可观,分为静态和动态两种,投资算力收益超高.邀请好友挖矿还有额外的返佣. NGK立志为所有人创造无差别 ...

  8. 【转】主成分分析(PCA)

    原文网址:https://blog.csdn.net/sunshine_in_moon/article/details/51513880.转载主要方便随时可以查看,如有版权要求请及时联系. 相信大家对 ...

  9. JDK源码阅读-Reference

    本文转载自JDK源码阅读-Reference 导语 Java最初只有普通的强引用,只有对象存在引用,则对象就不会被回收,即使内存不足,也是如此,JVM会爆出OOME,也不会去回收存在引用的对象. 如果 ...

  10. Elasticsearch 分片集群原理、搭建、与SpringBoot整合

    单机es可以用,没毛病,但是有一点我们需要去注意,就是高可用是需要关注的,一般我们可以把es搭建成集群,2台以上就能成为es集群了.集群不仅可以实现高可用,也能实现海量数据存储的横向扩展. 新的阅读体 ...