写得很不错的文章,国人用英语写的,还有代码。
0 M8 j$ Y3 N6 _6 hHooking Direct3d
$ @; M0 I2 `$ a$ O: CBy Jijun Wang
/ y8 k( t, ~& F( |! FIntroduction
( D/ T* M- u8 F( l* g9 wIn 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. - y3 w3 {/ }5 c: d/ V
1 J* `* @# B. k+ y7 u: i0 gIn 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.
5 e" I5 S0 o8 L2 f0 h5 |Hooking Technologies' l, d; V# a2 i& R
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 ) A8 E1 h- o/ Q% O8 [# j8 m
1) Register your DLL to the registry table.
% w7 }% i- [1 f2 kThis 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.
3 K6 d# v, v2 z2) System-wide Windows Hooks K9 p5 z# _& t( W# }: h
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. : {, `0 ~+ E0 R; j7 ]! n+ H
3) Create Remote Thread
; @* N3 ?$ h4 ^% n: I, q3 CThis 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.
& f; O1 N: Z7 T( f7 B
. b+ b* e4 t$ E1 r$ dTo inject your code into another process’ code, we could use:
" E' y- S, B% N1 v8 ]7 `1) Proxy DLL
7 K" e+ U) m" Q1 H4 ]! Y$ ~, lThis 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.
+ M+ O D0 D4 [2 M2) Altering of the IAT (Import Address Table)
+ }. v% ~3 Q2 e) |4 x" Z, DThis 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.
. z- ]6 }' F k/ ]2 J3) Code Overwriting
8 k& s% ^, o0 E2 B; i. D4 O" e, `7 \The 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.- S2 o/ ?1 h& N
# A7 L8 [2 z, ~- BFor 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.
' q6 e6 P- A$ Z" ~) I: P9 {# H$ |8 a; tDetours# z3 t8 Y3 `1 I
“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/' i) }& e2 R0 _1 Z- A) _) w
, ]: D* t: f2 ]$ R# F0 BAs 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.( j8 Q, k& z( Z( U/ w# [. F4 o
3 k' e0 _4 y+ v% W" k6 c/ e
DETOUR_TRAMPOLINE() k" K: P( k3 S+ y
UINT WINAPI Real_SetTimer(HWND hWnd, // handle of window for timer messages8 N6 p) H$ f$ G- D
UINT nIDEvent, // timer identifier
: M4 f: k# I# K UINT uElapse, // time-out value
: e C8 ~: }+ a5 D* G1 N- K5 J TIMERPROC lpTimerFunc), // address of timer procedure& u( P% N- u. O
SetTimer);
1 e7 W T( k- Y& f8 G6 V. I
2 E8 x# l, Y+ J8 ]; q" l; L) aThen we write our own SetTimer function.
$ Y7 C, ?. v* T7 W7 H7 l, ~/ tUINT WINAPI Mine_SetTimer(3 H; Z! C0 n7 ~ z4 |& k( e
HWND hWnd, // handle of window for timer messages
* O) `% z, G9 G7 ] UINT nIDEvent, // timer identifier
! u: ] L/ U/ h UINT uElapse, // time-out value
" c; |( D7 j N. b2 ^) p- x TIMERPROC lpTimerFunc // address of timer procedure
0 l; Q( ^$ J9 X# |( ~% r )2 y0 R R/ _/ [* G& R
{: i; A" p# s2 [- v
uElapse=10* uElapse;
3 f9 d! ?% T# X+ O2 U, e return Real_SetTimer(hWnd,nIDEvent,uElapse,lpTimerFunc);; `! F6 W: K: S3 T
}0 _( X4 q5 l2 t3 M& Y1 t$ Q! R
6 n. E( [3 N- l6 ]! n8 _' e! ~Then write the functions to intercept the Real_SetTimer() function to your own Mine_SetTimer() function and the function that removes the interception., ~& n C. }7 ^+ h$ N ^1 N
6 h9 A) q; N$ I( G+ v; J: \
BOOL TrampolineWith(VOID)1 l# E, ~; v8 `9 h
{
& n+ |9 @+ |9 f8 C$ a+ M6 u DetourFunctionWithTrampoline((PBYTE)Real_SetTimer,6 o. v: W! `0 U! q }. H
(PBYTE)Mine_SetTimer);8 x% b" I+ J. L4 w
return TURE;* y3 @# i. E8 k/ F7 M
}: u- M" E1 m2 Z; W: R
( W6 x6 d/ a; X; f; uBOOL TrampolineRemove(VOID). C: x8 Q Y9 k
{( I- M5 T. m l
DetourRemove((PBYTE)Real_SetTimer,
3 A: `( R. l) M; _; s3 C (PBYTE)Mine_SetTimer);
. I4 Q- j1 e% g5 n- w& V1 }% I return TRUE;0 d B+ `* B, G* x6 \6 j/ Q a
}$ I2 {: C9 ^7 r) `: q" Y: L
1 S, g/ c2 X0 t0 J2 u/ fAt last, we write the DLLmain function.# s. C8 {* E8 J
3 y6 D; c5 d9 f) ?
BOOL APIENTRY DllMain(HINSTANCE hModule, DWORD dwReason, PVOID lpReserved)
, Y, I! v. w: a{
* F8 J8 W4 }* d switch (dwReason) {! K9 [1 G/ y0 U* }* j. Q
case DLL_PROCESS_ATTACH:
' A9 x3 i: t, R* i+ T, Q& {2 V return TrampolineWith();
! U% f4 J9 w+ k1 j; J( R0 @ case DLL_PROCESS_DETACH:
) A' @& \5 x& i6 z2 F* j0 c return TrampolineRemove();
D- H- B4 D' y/ P9 y8 p5 V case DLL_THREAD_ATTACH: F+ f) _1 G( n& H
return TrampolineWith();7 r; p. Q8 {( h g! r$ U
case DLL_THREAD_DETACH:& [; F7 t* E- A% @# N! T
return TrampolineRemove();
3 z- u5 C; G" v4 Y$ \ }
, F. K3 t9 t4 V2 K, ]( W return TRUE;5 d/ y) ]" j* T& I. I) _8 x
}
; a* j( n7 K) g+ {6 m6 V, ?; s* F1 o. O0 j) K4 T
By 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.$ J* p. G, L1 n6 H# _1 e9 Z! a; ]9 Z; Z
& S% s9 d/ c& L/ z. ]8 ?" MThis 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. - f+ g! v4 r/ x7 j! w% I$ t2 x
5 M/ t, N7 D a
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.
. @& R8 T3 c! ]: F9 c% kUnderstanding Virtual Functions and Hooking Direct3d5 Z# i M, f: f+ ^0 m) _, Z
Virtual 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”.
0 Z9 n2 R4 P' n" p t8 S( M* H- W) [' p' T
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:5 F0 n7 t0 ]3 _
1) Catch Direct3DCreate8() to get the IDirect3D8 object
) j e) W b( i5 Q$ }# p0 F& J2) Use the pointer of IDirect3D8 object, catch the CreateDevice() function to get the IDirect3DDevice8 object.: [& s8 k# Y) }$ s, t# ]1 f: F
3) Use the pointer of IDirect3DDevice8 object, catch Present() function.& Z m3 ^ o0 Y6 i* @0 t4 p
4) In the Present() function calculates the frame rate.
; e a+ Q( w l0 {' Q8 D) w
$ r' J7 d1 n6 }) O1 e$ vHowever, 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.
n9 j; u# {. `8 U
) w5 n1 j; r( p* t9 E# \873: // Create the device
6 _. X' U4 K$ R874: hr = m_pD3D->CreateDevice( m_dwAdapter, pDeviceInfo->DeviceType,% P2 j( m: v, m4 ^7 m4 m8 d2 ]7 v
875: m_hWndFocus, pModeInfo->dwBehavior, &m_d3dpp,
7 G4 g$ [+ @/ a$ k7 ?876: &m_pd3dDevice );3 U3 o; m4 m/ r- h ~# j n+ D
00403114 mov eax,dword ptr [this]: _2 W. c5 ]1 x
00403117 add eax,2A4A8h+ g, w4 c, h9 P" ?- G- E/ }/ K
0040311C push eax // push the sixth parameter &m_pd3dDevice$ t9 ~8 W. A- [& K9 S0 J- Y5 A
0040311D mov ecx,dword ptr [this]
8 J4 r3 C0 K4 B. N1 H2 ?00403120 add ecx,2A464h8 N1 m+ }! j- ~- i: j6 ~
00403126 push ecx //push the fifth parameter &m_d3dp4 [( H. w- r6 m8 f- ?2 D
00403127 mov edx,dword ptr [pModeInfo]
4 |" x$ S2 k9 K! [0040312A mov eax,dword ptr [edx+0Ch]# i% v% g9 g' b7 f& X4 j c
0040312D push eax //push the fourth parameter pModeInfo->dwBehavior( a5 L2 Z: E6 i G- {
0040312E mov ecx,dword ptr [this]
e8 z. G" D3 N00403131 mov edx,dword ptr [ecx+2A49Ch]
+ b1 j3 S! x) f5 ]' @! s00403137 push edx //push the third parameter m_hWndFocus
1 x! M3 g8 @9 E2 J2 c, h- @# ]00403138 mov eax,dword ptr [pDeviceInfo]( e2 ~: n+ I3 d7 o% l5 L& I v
0040313B mov ecx,dword ptr [eax]
3 O2 Z' L" h% B6 @0 h3 ]0040313D push ecx //push the second parameter pDeviceInfo->DeviceType. T' X' [+ F- y! N8 ?; }$ @
0040313E mov edx,dword ptr [this]
3 Z% t) }5 J" {1 I+ {" x9 q" A9 x00403141 mov eax,dword ptr [edx+2A448h]2 Q V: s, u9 T* }! L
00403147 push eax //push the first parameter m_dwAdapter
0 {1 E! r5 `0 K, X5 w9 ]00403148 mov ecx,dword ptr [this]4 P) E; L5 [$ [" l
0040314B mov edx,dword ptr [ecx+2A4A4h] //calculate the return address3 d5 \' I7 l, @: a3 m; A& B+ o
00403151 mov eax,dword ptr [this]
" n% f9 k E! {! e/ M1 |2 o00403154 mov ecx,dword ptr [eax+2A4A4h]
8 @" a! m& ~+ }" r; V* {) H0040315A mov eax,dword ptr [ecx] //calculate the vtable address. It’s the value
' y/ Z, ?7 P' s A //stored in ecx register. & l7 j$ @+ A# `# [% J2 u
0040315C push edx //push the return address: [0 \) y1 K! W
0040315D call dword ptr [eax+3Ch] //call the CreateDevice() function + s7 I; P9 U! o* c* g4 ?
00403160 mov dword ptr ,eax2 z+ T( I( M0 d, s: B0 X
2 w7 y. p# O' u" @6 tFrom 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.
s3 @. T4 O: }; L% d; d5 e# k* U' |( `4 w$ u; ]
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.
X1 F8 a3 K' N1 t$ OReference:) ^6 A4 v3 f% F! N
[1] “API hooking revealed”, Ivo Ivanov
4 i9 g# F) q5 D[2] “madCodeHook”, madshi! W% l$ A0 u4 _; c7 @) G3 o! ~
[3] "Detours", Galen Hunt and Doug Brubacher$ d9 J: t7 H2 W5 O) C, R
[4] “Virtual Functions and their implementation in C”, Shivesh V.) B% K) u# s( x) Z s
[5] “Pointers to C++ Member Functions”, Michael D. Crawford |