设为首页收藏本站官方微博

【汉化资料】中国人写的Hooking Direct3d

[复制链接]
查看: 2019|回复: 0
打印 上一主题 下一主题

【汉化资料】中国人写的Hooking Direct3d

跳转到指定楼层
楼主
发表于 2009-4-6 13:41 | 只看该作者 回帖奖励 |正序浏览 |阅读模式

【汉化资料】中国人写的Hooking Direct3d

写得很不错的文章,国人用英语写的,还有代码。
* e! J$ p4 b& x1 Z; k, }! x, `Hooking Direct3d6 c  d& H9 G! j- S% v& V$ l
By Jijun Wang
6 y3 e+ }" J, J( jIntroduction, F1 b2 S( p" b) M! m, m% u
In the field of hooking technologies, hooking COM based applications is a big challenging because you can’t know their member functions’ real addresses previously. There are many papers on the Internet that talk about how to hook (somebody call it hijack) an application. However, seldom of them mention how to hook COM. Since I have seen some people asked questions about this topic and nobody answered their questions clearly, I decide to write this paper to share my experience with the guys who are interested in hooking COM. 0 u9 r$ }  q3 Z. Z3 J* e
8 W1 |3 _) O* ~( v+ K, \1 D
In this paper, I use direct3d, which is widely used in current games, as an example of COM. At first I will briefly introduce the hooking technologies and explain why I select Detours to hook direct3d. Then more details and examples of Detours will be presented and I will discus virtual functions and find the way to hook direct3d.  ) p/ }0 h: R* \% {0 @- G  Y
Hooking Technologies5 c6 h3 @  S4 Z, @% P
The basic idea of hooking is injecting your code into a piece of code. When the target code executes your code will be invoked. To do this, you need to at first attach your code into the target process. And then inject your code into the target process’ code. The ways to attach your code into another thread or process include 8 k9 b& ^) [+ Q* B7 x
1) Register your DLL to the registry table.
0 a) ?$ `' v2 B* l; @8 H8 bThis method registers your DLL to the key: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Windows\AppInit_DLLs and the dll will be loaded when user32.dll initializes itself. It is a safe method. But it only works for the applications that use user32.dll. And it’s not convenient to activate/deactivate your DLL. % B% ~7 ^# e( ~8 W# ?+ a) L3 u  v
2) System-wide Windows Hooks' @6 X7 Z4 j5 M8 C; z, I
This method use SetWindowsHookEx(),CallNextHookEx() and UnhookWindowsHookEx() winapis to monitor the system’s message traffic and attach your code into the processes that fit the hook filter. Since it is system-wide message monitor, the system’s performance will be significantly affected.
4 g5 ^0 M( O: N3) Create Remote Thread' X3 M4 u% K2 l5 x$ d
This method use CreateRemoteThread()to inject your DLL into another thread (the to-be-hooked thread). It’s a very effective method. But there is one thing we need to consider. You must make sure you have enough privileges to access the to-be-hooked thread. ) L$ \8 ~: I4 b) U- N

; g! i9 B9 P7 ]( _3 gTo inject your code into another process’ code, we could use:! M2 t5 K& E+ D( C9 D: c
1) Proxy DLL
8 |+ O# ]+ G) M0 I# kThis method writes a new DLL to replace the to-be-hooked DLL. The new DLL must have the same name, exported functions and variables as the old one. For example, the GLtrace is a replacement of the opengl32.dll. It is used to trace OpenGL. Although you could use function forward to reduce the time spent in rewriting functions, it’s a tedious work in some cases.   
1 m$ w6 j# C: y* T# P% P2) Altering of the IAT (Import Address Table)
4 ?0 j% b+ b) ]1 aThis is a wildly used hooking method. Windows use IAT to find the functions’ addresses. Through changing the data of IAT, you could use your own function to replace the to-be-hooked function. The method is robust and easy to implement. However, it only works for statically linked API calls. And sometimes you may miss API calls since you must patch every module in the target application.
( W  [& p- ?( G4 [( N' E, O3) Code Overwriting
; Y' _! R! m5 S' AThe basic idea is to overwrite the API’s binary code in memory. We could save and replace the first several codes of a function call to a JUMP code to jump to your codes and then go back to the original position and restore the saved codes. It’s very hard to implement. However, once you have mastered it, it’s really a good hooking method.
! p1 @. l1 J$ R& u7 J8 R6 {% A/ Z0 ]4 I4 Q1 G1 V8 ]+ @
For more details about hooking technologies you can read the wonderful paper “API hooking revealed” written by Ivo Ivanov and madshi’s discussion about hooking methods. There are some libraries or tools that wrap the hooking methods. "Detours" is a library developed by a Microsoft’s research term. It uses code overwriting technology. “madCodeHook” is a library built by madshi. It’s also based on code overwriting. “hookapi” is another tool can help you develop your hooking applications. Since Detours is free for research purpose and it’s stable and effective, I will use it to hook direct3d.
# }' g5 M5 g- s, y+ NDetours
, r" H) M  q6 ?5 j" Y  ^3 N) y9 V“Detours” is originally built for change a standalone system to distributed system. It can inject your code into another win32 function. Some utilities that attach your codes to another process are also provided in this library. The typical case you may need Detours is that you need to modify an application’s behavior without knowing its source code. For more details please visit Detours’ web site: http://www.research.microsoft.com/sn/detours/  O' P9 V& }* p9 z

8 U7 |, L/ M7 }$ l# f) m( f' JAs an example of how to use Detours, we will try to catch the function “SetTimer()”. Then change the elapse time to a big number. So for the applications use SetTimer(), you can steal time by hooking this function. The first step is to create TRAMPOLINE. It changes SetTimer()’s binary code and lets it jump to the Real_SetTimer() function.. {& B4 N- V6 C
" n  r6 N  K/ h( V
DETOUR_TRAMPOLINE(
5 Z7 B& v4 ^/ C( [" AUINT WINAPI Real_SetTimer(HWND hWnd,     // handle of window for timer messages& {; C4 Y& [) Z4 ]; G3 g' [! u
                        UINT nIDEvent,         // timer identifier- n% e9 d9 k; `1 ~$ J
                        UINT uElapse,            // time-out value
% B3 S- \- X8 Y9 {9 ^' m2 e                        TIMERPROC lpTimerFunc), // address of timer procedure
5 W, c) Y. U( f4 D  d* q0 ESetTimer);
) x  S1 q0 H& E$ y9 O0 g1 \1 C* i' N. w+ a2 f, }; g% v; f+ d* O
Then we write our own SetTimer function.+ ?, R8 ]4 I* b4 o7 X
UINT WINAPI Mine_SetTimer(+ K7 R4 O' r2 D; M" v
    HWND hWnd,           // handle of window for timer messages2 M6 l" k) g8 r( C/ s
    UINT nIDEvent,        // timer identifier! E4 ^/ n; T& @; ?
    UINT uElapse,           // time-out value
+ X! P: q. s% v/ M9 f9 C8 B5 L    TIMERPROC lpTimerFunc   // address of timer procedure
& Z8 a8 c4 l% }3 A7 j9 _  I& }    )
/ L( W- ~2 p* V& A, B' Z' N/ q{
# r9 ]0 B/ I% ]& E    uElapse=10* uElapse;
( v% N/ P, Q( F3 H- D" ^% s    return Real_SetTimer(hWnd,nIDEvent,uElapse,lpTimerFunc);
; O3 Y  O: d0 j# n8 f, |/ R8 T# G  p}
; R! k9 M: i8 {4 N" P% E$ B! l
! Q# [& H% I7 e" d, ^Then write the functions to intercept the Real_SetTimer() function to your own Mine_SetTimer() function and the function that removes the interception.) _6 I( p; q) `; W' H

! n  d8 Q0 J5 G) `* p. mBOOL TrampolineWith(VOID)" r" _" y" F2 g$ b0 G% m4 v8 ~
{8 \0 a/ d7 q; t/ Q) w
    DetourFunctionWithTrampoline((PBYTE)Real_SetTimer,) C! `( m! f+ b
                                        (PBYTE)Mine_SetTimer);
* I3 r6 L2 F7 @; f6 O    return TURE;
% ?( r  e! {$ `9 |: U' y}# m' Y9 Z" J; S% n0 o% Z) M8 V! Q
* Z  M4 X9 L9 N0 K% T1 h
BOOL TrampolineRemove(VOID)1 U) Y: w' [+ Z
{
' [9 w4 R+ j9 i. t    DetourRemove((PBYTE)Real_SetTimer,0 K5 z# u- v4 O9 {
               (PBYTE)Mine_SetTimer);3 M$ y) Q3 ^! ~1 ^
    return TRUE;! c- [1 l: E% x9 }  ~) a/ E
}
% M4 M" m# @; J+ V1 w( K, U% {# A# e: P
At last, we write the DLLmain function.
& M+ E+ T8 C# G! k
, v6 x% T9 E& f2 m9 @+ kBOOL APIENTRY DllMain(HINSTANCE hModule, DWORD dwReason, PVOID lpReserved)3 g4 i5 G; {$ C: W# F
{7 y$ ~& e" `4 K
    switch (dwReason) {" D2 U+ }6 |0 N6 `
      case DLL_PROCESS_ATTACH:+ H- L0 @" h5 Z$ X. x
        return TrampolineWith();
4 b- y: c" u3 I; o/ `      case DLL_PROCESS_DETACH:
+ ]$ k- G# ~; O  P1 |' n        return TrampolineRemove();9 `" V8 j( G* T, u; f
      case DLL_THREAD_ATTACH:
  d: d* u# d- {0 n        return TrampolineWith();
6 m' d8 |4 _3 N      case DLL_THREAD_DETACH:
0 A& ]+ e- ^  ]        return TrampolineRemove();$ |. J: B0 w2 a! Z( y2 Y
    }/ V& R8 o9 I9 Y" E
    return TRUE;
" q, [; W+ ~$ X" w/ s4 p% K+ t}
* R3 J( `2 H' |! o
/ P3 o' }. B* T5 q  L6 f$ OBy including the “detours.h” file and linking the “detours.lib”, you can build this DLL (let’s say it is myTest.dll). Then you can write your own application to attach the DLL into another application, or use the “withdll.exe”, which is included in Detours 1.5’s samples, to attach it. If you place the DLL file, withdll.exe and winmine.exe in the same directory, then play the Mine game use command “withdll.exe –d:myTest.dll winmine.exe”, you will get a very high score.
  ~! m; J- c. Y) [. q6 O  u$ t, f5 W% |' M% m3 _
This is the simplest case of using Detours. If you want to hook a member function of a class, you need to write your own class and your member function. You can find an example of hooking member function in Detours 1.5’s samples.
& |( g2 |8 c5 l" O/ d: f% G3 k6 G+ ]$ _# b2 ^7 U: y) `
To hook direct3d, you may create a class, write your own member functions, for example CreateDevice(), Present(), and then detour direct3d’s member function to your own functions. Unfortunately this doesn’t work. The reason is that Directx is COM based, it uses virtual functions. When you detour the member functions, you will use the virtual function’s address not the real implement function’s address. So the key of hooking direct3d is finding out the real function address. To do this we need to know how virtual function works.
$ x, \9 b2 X3 K9 M) I' d' }$ N; mUnderstanding Virtual Functions and Hooking Direct3d
1 R1 R: ~7 h2 L7 wVirtual function is used for reusable and polymorphic purposes. It is runtime bound to the real implement function. For more details about how virtual functions work, please read Shivesh V.’s paper “Virtual Functions and their implementation in C”. ) S/ K6 b7 z# ?' s- o
: B+ ]- D$ E8 b# _, X
Basically, after you call the Direct3DCreate8() function (let’s assume we use directx8), you will get a  pointer to the created IDirect3D8 object. In the pointer is the address of the vtable, a structure that contains all the member functions’ addresses. The address in the vtable is the real implement function’s address. So if we want to build a benchmark application to test the frame update rate, we could do it in the following steps:
+ I0 p6 l# L9 `  C8 c% F9 b  B1) Catch Direct3DCreate8() to get the IDirect3D8 object
2 V0 O8 ^: P6 b4 _, G/ ^2) Use the pointer of IDirect3D8 object, catch the CreateDevice() function to get the IDirect3DDevice8 object.. ?1 U5 ^* q( F" m& T
3) Use the pointer of IDirect3DDevice8 object, catch Present() function.$ g8 q; _$ M- u0 K  ~  K
4) In the Present() function calculates the frame rate./ i9 X) l% y5 W. X/ E( [

& X! g% m, ]; u+ tHowever, to catch the member function, there is a very important parameter we need to know. It’s the address data in the vtable that contain the to-be-hooked function’s address. There is no general way to know the offset in the vtable. For direct3d, you could use the d3d8.h file to figure out the offset. Or you can debug a direct3d application and get the offset by read the disassembly code. The following is a piece code of the directx 8.1 SDK’s Text3D sample code. The comments of the disassembly code are added by the author.* R' e0 p" |# V. u
: P' X9 v2 Z9 j' N* ^* f
873:      // Create the device. w& P/ x9 I, P" b
874:      hr = m_pD3D->CreateDevice( m_dwAdapter, pDeviceInfo->DeviceType,
5 {% ]! j6 Y# E9 M( p* V875:                                 m_hWndFocus, pModeInfo->dwBehavior, &m_d3dpp,
, H# N% g  t" J; U: q876:                                 &m_pd3dDevice );' K9 @3 K( K9 N' r
00403114   mov         eax,dword ptr [this]- x5 G3 s, C1 Z. j4 r% c
00403117   add         eax,2A4A8h# Q0 ]6 A9 l% x6 x( F6 q. J- O
0040311C   push        eax            // push the sixth parameter &m_pd3dDevice/ s0 c/ D0 S. M6 j# i; k
0040311D   mov         ecx,dword ptr [this]
1 o% T, i( ]- X' n0 Z) P00403120   add         ecx,2A464h5 C/ e- j4 M$ \) x; c
00403126   push        ecx            //push the fifth parameter &m_d3dp+ b( b# l' U' K& {8 w/ _
00403127   mov         edx,dword ptr [pModeInfo]
4 Y; U' D! h4 m! H% K0040312A   mov         eax,dword ptr [edx+0Ch]
0 p2 [" j1 x# w) k' A0040312D   push        eax    //push the fourth parameter pModeInfo->dwBehavior2 F9 n) p7 }" e! S0 N4 ]
0040312E   mov         ecx,dword ptr [this]% o4 z6 i1 @4 ~" c- h4 h$ c8 W
00403131   mov         edx,dword ptr [ecx+2A49Ch]
, o) K% }& v6 M. g00403137   push        edx    //push the third parameter m_hWndFocus0 c" B: h; }" o! ?5 C) W
00403138   mov         eax,dword ptr [pDeviceInfo]
; [6 ~$ _1 m/ q4 k5 i; G% u0040313B   mov         ecx,dword ptr [eax]3 b* d6 u2 I/ Q# @
0040313D   push        ecx    //push the second parameter pDeviceInfo->DeviceType5 h2 f7 N  p9 V: |% q9 u6 S) n3 `
0040313E   mov         edx,dword ptr [this]( u( ]2 |! P+ g: |2 s
00403141   mov         eax,dword ptr [edx+2A448h]% z$ F4 e5 @+ e& x# w
00403147   push        eax    //push the first parameter m_dwAdapter6 j, A/ y# S3 H: S1 g6 y; v
00403148   mov         ecx,dword ptr [this]
9 g; r" B, M7 h0040314B   mov         edx,dword ptr [ecx+2A4A4h]    //calculate the return address
1 ^9 q- H! D; V3 d7 v3 C00403151   mov         eax,dword ptr [this]/ ?8 O9 b" D8 Z  f% E  S$ \+ i" `7 }
00403154   mov         ecx,dword ptr [eax+2A4A4h]' i: I2 _9 U7 x$ w9 Q
0040315A   mov         eax,dword ptr [ecx]    //calculate the vtable address. It’s the value
4 M  P1 F7 d7 {7 |: U                        //stored in ecx register. 4 c" u2 J! V0 A7 Y; \5 a
0040315C   push        edx    //push the return address9 s' ]6 p8 s/ V0 ^, l2 k
0040315D   call        dword ptr [eax+3Ch]    //call the CreateDevice() function - X1 o/ k$ c8 m
00403160   mov         dword ptr
,eax5 l( b" y; s4 c- ~3 N3 ~1 O

6 Q  ~5 u0 x3 MFrom the assembler code, it’s obvious that the offset is 0x3ch. You can do the same thing for the Present() function. And the offset happen is also 0x3ch.1 l- {. @( q/ R' I: l  P6 Q0 @
2 f& _0 J6 R& Y9 ~+ ]' z( l
The sample code can be found at http://usl.sis.pitt.edu/wjj/UTClient/direct3d8.zip. To compile it you need Directx 8.1 SDK. Please note that the method of display frame count is not every effective. If you remove the displaying code, you will find Detours has almost no effect to the frame rate.- I! b; e% I1 S; a: @0 g
Reference:5 b  a0 O) I0 o) V; q8 D
[1] “API hooking revealed”, Ivo Ivanov
/ `5 L2 ~0 f# c9 ]$ @[2] “madCodeHook”, madshi
$ n. e6 ]8 u4 Z4 w) e0 i5 g[3] "Detours", Galen Hunt and Doug Brubacher
8 r4 ?4 l0 Z- F9 `. U[4] “Virtual Functions and their implementation in C”, Shivesh V.
0 T: V$ L- y  a+ C8 A[5] “Pointers to C++ Member Functions”, Michael D. Crawford

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 很美好很美好 很差劲很差劲
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

冒险解谜游戏中文网 ChinaAVG

官方微博官方微信号小黑屋 微信玩家群  

(C) ChinaAVG 2004 - 2019 All Right Reserved. Powered by Discuz! X3.2
辽ICP备11008827号 | 桂公网安备 45010702000051号

冒险,与你同在。 冒险解谜游戏中文网ChinaAVG诞生于2004年9月9日,是全球华人共同的冒险解谜类游戏家园。我们致力于提供各类冒险游戏资讯供大家学习交流。本站所有资源均不用于商业用途。

快速回复 返回顶部 返回列表