其他分享
首页 > 其他分享> > DLL注入(一)全局钩子注入进行键盘信息监听

DLL注入(一)全局钩子注入进行键盘信息监听

作者:互联网

DLL注入之全局钩子注入进行键盘信息监听

参考《逆向工程核心原理》

一、编写键盘监听DLL

// dllmain.cpp : 定义 DLL 应用程序的入口点。
#include <Windows.h>
#include <stdio.h>

HMODULE g_hDll;
HHOOK g_hHook;

BOOL APIENTRY DllMain(HMODULE hModule,
    DWORD  ul_reason_for_call,
    LPVOID lpReserved
)
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        g_hDll = hModule;
        break;
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

LRESULT CALLBACK KeyboarProc(int nCode, WPARAM wParam, LPARAM lParam)
{
	char szPath[MAX_PATH];
	char* p = NULL;
	if (nCode >= 0)
	{
		if (!(lParam & 0x80000000))
		{
			GetModuleFileNameA(NULL, szPath, MAX_PATH);
			p = strrchr(szPath, '\\');
			if (!_stricmp(p + 1, "notepad.exe"))//只对notepad进程拦截
			{
				return 1;
			}
		}
	}
	return CallNextHookEx(g_hHook, nCode, wParam, lParam);
}

EXTERN_C __declspec(dllexport) void HookStart()
{
	g_hHook = SetWindowsHookEx(WH_KEYBOARD, KeyboarProc, g_hDll, 0);
	DWORD errCode = GetLastError();
	printf("%d", errCode);
}

EXTERN_C __declspec(dllexport) void HookStop()
{
	if (g_hHook)
	{
		UnhookWindowsHookEx(g_hHook);
		g_hHook = NULL;
	}
}

二、编写DLL加载器

//hook.cpp
#include <Windows.h>
#include <conio.h>
#include <stdio.h>

typedef void(*HOOKSTART)();
typedef void(*HOOKSTOP)();

int main()
{
	HMODULE hDll = LoadLibrary(L"kbhook.dll");
	if (!hDll)
	{
		return 0;
	}

	HOOKSTART hookStart = (HOOKSTART)GetProcAddress(hDll, "HookStart");
	if (!hookStart)
	{
		return 0;
	}
	HOOKSTOP hookStop = (HOOKSTOP)GetProcAddress(hDll, "HookStop");
	if (!hookStop)
	{
		return 0;
	}
	hookStart();
	printf("press 'q' to quit\n");

	while (_getch() != 'q')
	{
	}

	hookStop();

	FreeLibrary(hDll);
}

三、编译运行

image-20210719230711609

​ 注意,因为我这台电脑是win10,64位,所以应该编译成64位运行,否则32位的DLL不能注入64位的程序就会整个窗口卡住。

image-20210719235152948

image-20210719235343147

​ 可以看到dll被注入,并且无论输入什么都不会输出

标签:hDll,return,钩子,DLL,hHook,include,注入
来源: https://www.cnblogs.com/S1mba/p/15042249.html