为梦想而生

碧海青天的追梦之旅

   ::  :: 新随笔  ::  ::  :: 管理

控制台程序:DllLoader

Dll加载器,用于动态加载目标Dll,并动态调用目标函数

 1 #include <cstdio>
 2 #include <windows.h>
 3 
 4 typedef int (*pAdd) (int a, int b);
 5 
 6 int main()
 7 {
 8     HMODULE hModule = GetModuleHandleA("Dll.dll") != NULL ? GetModuleHandleA("Dll.dll") : LoadLibraryA("Dll.dll");
 9     pAdd Add = (pAdd)GetProcAddress(hModule, "Add");
10     if (NULL == Add)
11         printf("Failed\n");
12     else
13         printf("Succeed\n1 + 1 = %d\n", Add(1, 1));
14 
15     system("pause > nul");
16     return 0;
17 }
main.cpp

 

原Dll:Dll

很简单的一个Dll,只有一个隐式函数Add.仅仅是一个简单的加法..

 1 #include <cstdio>
 2 #include <windows.h>
 3 
 4 #define EXTERNC extern "C"
 5 #define EXPORT __declspec(dllexport)
 6 #define ECEP EXTERNC EXPORT
 7 
 8 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
 9 {
10     switch(fdwReason)
11     {
12     case DLL_PROCESS_ATTACH:
13         MessageBoxA(NULL, "Attach", "", MB_ICONINFORMATION);
14         break;
15     case DLL_PROCESS_DETACH:
16         MessageBoxA(NULL, "Detach", "", MB_ICONINFORMATION);
17         break;
18     default:
19         break;
20     }
21 
22     return TRUE;
23 }
24 
25 ECEP int Add(int a, int b)
26 {
27     return a + b;
28 }
main.cpp

 

劫持Dll:HijackDll

用于劫持原Dll,并转发原程序的动态调用

 1 //last code by gwsbhqt at 20150727
 2 
 3 #include <cstdio>
 4 #include <windows.h>
 5 
 6 #define EXTERNC extern "C"
 7 #define NAKED __declspec(naked)
 8 #define EXPORT __declspec(dllexport)
 9 #define ECEP EXTERNC EXPORT
10 #define ENCDECL EXTERNC NAKED void __cdecl
11 #define EENSTD EXTERNC EXPORT NAKED void __stdcall
12 #define EENFAST EXTERNC EXPORT NAKED void __fastcall
13 #define ENDEF ENCDECL
14 
15 #define JMPFARPROC(lpModuleName, hProcName) \
16     HMODULE hModule; \
17     hModule = GetModuleHandleA((lpModuleName)); \
18     if (NULL == hModule) hModule = LoadLibraryA((lpModuleName)); \
19     if (NULL != GetProcAddress(hModule, (hProcName))) __asm JMP EAX;
20 
21 #pragma comment (linker, "/EXPORT:Add=_Add,@1")
22 
23 ENDEF Add()
24 {
25     JMPFARPROC("Dll.tmp", "Add");
26 }
27 
28 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
29 {
30     switch (fdwReason)
31     {
32     case DLL_PROCESS_ATTACH:
33         MessageBoxA(NULL, "Hijack Dll Attach", "", MB_ICONINFORMATION);
34         break;
35     case DLL_PROCESS_DETACH:
36         MessageBoxA(NULL, "Hijack Dll Detach", "", MB_ICONINFORMATION);
37         break;
38     default:
39         break;
40     }
41 
42     return TRUE;
43 }
main.cpp

 

此处的宏JMPFARPROC看起来似乎每次转发函数都会加载一次hModule,其实不会,先GetModuleHandle获得的hModule是不会增加引用计数的.

所以即使是大量的转发,也应该不会出现内存泄漏的问题.

 

都是些很简单的代码,仔细认真看看就好了

 

测试是只需要新建一个工程,工程下新建三个项目,分别是一个控制台程序和两个动态链接库,

在每个项目新建main.cpp文件,将代码贴入,生成工程之后.在Debug/Release文件夹下,将Dll.dll更名为Dll.tmp,将HijackDll.dll更名为Dll.dll...

即可完成Dll劫持...

posted on 2015-07-27 00:37  gwsbhqt  阅读(725)  评论(0编辑  收藏  举报