写得很不错的文章,国人用英语写的,还有代码。5 e' y+ a( l3 F0 H. F f
Hooking Direct3d" N. p+ p- j' G/ g" n# I- R% D% P
By Jijun Wang
4 {8 ?( K$ r! b G TIntroduction
$ r W; y3 G% l5 G) {1 _9 N3 v( kIn 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. o: L- ~+ [% f" n! t
7 P8 K8 i) q" X6 d" h1 j* H
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.
& m2 Y! I, ~5 Z" Z. }Hooking Technologies1 ?5 |/ `7 M% [3 @. W, F
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 ' ~1 L* U c: Y& A: C: b; n( Y! o
1) Register your DLL to the registry table.
+ i$ F! J/ I& @; a9 H4 sThis 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.
( i* ]3 f7 x: }& [0 b5 N6 }2) System-wide Windows Hooks4 U/ p/ ~0 Z/ o9 E/ D
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. 5 z% X& P$ @ G2 ^
3) Create Remote Thread& s; m, t3 r" M; V8 Y% c
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. 7 n& ^' X5 _9 ?! \' k
8 ?: ?$ ~3 E! o' B0 D% ^
To inject your code into another process’ code, we could use:0 U4 q+ A7 R3 h$ t6 {* O
1) Proxy DLL
5 A7 k( O4 G+ z, b- @, a0 vThis 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.
. V, n9 U8 }4 S/ i" n2) Altering of the IAT (Import Address Table)- Y6 H! x O) F# N6 K
This 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.
3 F9 m- e5 t6 q( E; u3) Code Overwriting% H L: W# R7 Q6 ? k& a
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.+ B' M7 k- s, D
! k: Z# v6 w w; M9 O
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.7 x/ f( _, P w& n, e
Detours
( p3 Q( F& B0 X. I8 ~# i9 c“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/
( x. R$ v; f9 R) E. h+ `- v2 Z: |( [! }' F) g
As 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.# \- \2 h- `/ W, [
7 _9 P! x j5 |6 C/ I9 e. P) |DETOUR_TRAMPOLINE(
' }. T' Z! u. O' ~" L' KUINT WINAPI Real_SetTimer(HWND hWnd, // handle of window for timer messages: A1 Q9 f9 _; K
UINT nIDEvent, // timer identifier
) c+ n2 S& m7 }, [; b UINT uElapse, // time-out value
; V5 D! p% Q" j" Y; V TIMERPROC lpTimerFunc), // address of timer procedure3 Z- l3 u+ P L/ w$ } i
SetTimer);
3 N" \& J6 ^9 j# \ B, ~% l& \4 a1 ~% \" g9 A$ F
Then we write our own SetTimer function.
/ z1 Y# |( q$ e& d% eUINT WINAPI Mine_SetTimer(
# w# A$ h; L7 G5 L HWND hWnd, // handle of window for timer messages- b1 V' J, ?+ a3 f. U; V4 g. ^* A3 O
UINT nIDEvent, // timer identifier: W! o7 M( }% e6 V g1 H R9 p
UINT uElapse, // time-out value
1 } V w. j6 V" L, n TIMERPROC lpTimerFunc // address of timer procedure# `- h! N# m! r8 t* I) f( ^
)0 s% ]; W) W1 U9 t% X# u
{+ F! G! e) F& E+ c
uElapse=10* uElapse;1 H% O0 u6 x/ h l% y( W
return Real_SetTimer(hWnd,nIDEvent,uElapse,lpTimerFunc);
* \$ {* ^- I+ D& {}
3 C& `: a8 l5 j
5 Q9 f" w% n) d0 c" \. y2 \3 W& xThen write the functions to intercept the Real_SetTimer() function to your own Mine_SetTimer() function and the function that removes the interception.
$ S5 g6 O* O ~
7 `+ I ~& A& y! j+ h) o# @+ G& ^BOOL TrampolineWith(VOID)+ I+ Q4 O' F! w9 w5 m3 ~0 w
{! |" D' l% z5 f: Q% W* a
DetourFunctionWithTrampoline((PBYTE)Real_SetTimer,
/ ^! l5 o0 M" H6 R0 d (PBYTE)Mine_SetTimer);
3 l8 `; B0 k5 H, r& _3 H7 n) g return TURE;
0 B0 `) H& g& O& P}$ A' \$ `3 ^* U' z& @9 s- B+ r( a
1 x' b' l' R* W( y. ]7 h6 e
BOOL TrampolineRemove(VOID)9 c! K/ o2 A1 E/ S J6 U
{
: M+ ]; [7 S. a5 D$ G4 Q DetourRemove((PBYTE)Real_SetTimer,3 s; _) V$ l3 b. [
(PBYTE)Mine_SetTimer);' ~- [) `5 M8 _- A/ G
return TRUE;% k# H+ E3 m: N& J
}$ I0 K, W+ I5 Q3 W; W0 X* B
) L8 C/ X9 F+ f2 [% h% fAt last, we write the DLLmain function.
7 D2 \2 V6 Z6 G$ N, e1 X8 I, b
BOOL APIENTRY DllMain(HINSTANCE hModule, DWORD dwReason, PVOID lpReserved)
+ H8 G6 ?" t/ S& M9 S* d2 Z3 a{
6 D9 i8 [5 m0 L" f$ G switch (dwReason) {
0 T% E8 o) n. p6 A) `# { case DLL_PROCESS_ATTACH:
5 o& H) R% F8 w$ t. ]/ k return TrampolineWith();9 k/ Q) @1 V+ O/ f/ [* l8 {
case DLL_PROCESS_DETACH:/ h; [" q, [. ^, r
return TrampolineRemove();$ f' p o8 g o3 s: j7 ~
case DLL_THREAD_ATTACH: ]! ~$ A# F8 J: n
return TrampolineWith();* b1 [9 v* T% Q( g" N/ f
case DLL_THREAD_DETACH:( c/ ^9 q7 s- G" j
return TrampolineRemove();
# g! [) I( a8 _3 M3 s5 r }; w, Q- k( u+ V# {
return TRUE;
" ]: i* U. u( r- h8 g, x}
7 }+ B8 G3 ?; x3 }* Q% f& k$ t! U0 u' P& q! I& d, o
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." `; U5 ]% b7 T
$ L3 e& c9 a" a- E5 N XThis 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.
6 W! p7 _3 U. J" N) D& l
! b" I" C7 P2 k! I! z# F3 m6 g. z! dTo 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.) U$ {: Y' d7 s4 K
Understanding Virtual Functions and Hooking Direct3d
6 f' F# f4 P; aVirtual 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”. ! z5 u( V A! i8 m+ D; M' ^3 i
! i i. i! U* s5 DBasically, 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:$ Q W1 k4 b9 ?+ e' q
1) Catch Direct3DCreate8() to get the IDirect3D8 object
% o W4 M! c/ x, k2) Use the pointer of IDirect3D8 object, catch the CreateDevice() function to get the IDirect3DDevice8 object.. |: H+ ]$ _" |7 Z6 q F1 O6 W4 ^; g' h
3) Use the pointer of IDirect3DDevice8 object, catch Present() function.
3 |, J/ ?3 A9 _* H& ^4) In the Present() function calculates the frame rate.. W$ c/ J+ c# ]; N
6 ~2 e' |$ V6 S* d) R5 P* ?$ y
However, 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.* D6 z# Y- l; U9 H* \' V; j" [# o
& w1 O5 Y, f5 P$ N( L3 F; @0 {
873: // Create the device& Q$ F( r( w9 f3 a
874: hr = m_pD3D->CreateDevice( m_dwAdapter, pDeviceInfo->DeviceType,
# \3 j4 b0 D8 ^3 f) u875: m_hWndFocus, pModeInfo->dwBehavior, &m_d3dpp,
( ?/ M. p e/ i/ M* t- l" h( ~876: &m_pd3dDevice );! T7 x" b3 |9 p
00403114 mov eax,dword ptr [this]
/ E/ l8 R. M- V# a- g) X/ Z00403117 add eax,2A4A8h
# ~7 B9 y$ `- t+ h% u0040311C push eax // push the sixth parameter &m_pd3dDevice+ }/ e5 F9 l0 H" v, M
0040311D mov ecx,dword ptr [this]5 d9 t' `$ g* T4 C$ A9 X8 M
00403120 add ecx,2A464h8 e* Q9 X' k. _9 g# n [
00403126 push ecx //push the fifth parameter &m_d3dp
" C) g# e- o/ t00403127 mov edx,dword ptr [pModeInfo]& A( S/ {" L! w8 m! S
0040312A mov eax,dword ptr [edx+0Ch]
8 f4 l" i. p3 c" {( G0040312D push eax //push the fourth parameter pModeInfo->dwBehavior
; J( U* {) A4 O0040312E mov ecx,dword ptr [this]
; s8 i7 ~( g. h8 v" j00403131 mov edx,dword ptr [ecx+2A49Ch]9 {4 a1 @7 _; x0 {* C! o8 }) _
00403137 push edx //push the third parameter m_hWndFocus
# ], Z9 P3 K0 |* J00403138 mov eax,dword ptr [pDeviceInfo]
' R, s2 e) W. C/ e( A0040313B mov ecx,dword ptr [eax]1 y1 U- `0 ^$ ^: X8 P: S7 B2 B4 g
0040313D push ecx //push the second parameter pDeviceInfo->DeviceType
" K3 _4 }. b5 s/ O% u" `* i0040313E mov edx,dword ptr [this]9 L: ^" T" V5 l) a$ j9 `
00403141 mov eax,dword ptr [edx+2A448h]
/ f6 I; ^# Y1 R& U00403147 push eax //push the first parameter m_dwAdapter4 b; R! L& u% u
00403148 mov ecx,dword ptr [this]3 f' L" S! K, _
0040314B mov edx,dword ptr [ecx+2A4A4h] //calculate the return address3 t4 D" z, U" [" i
00403151 mov eax,dword ptr [this] c2 N, |% \& M0 D0 `+ z# [ c
00403154 mov ecx,dword ptr [eax+2A4A4h]4 ~% z# v& _; r2 o) a) [& h$ K
0040315A mov eax,dword ptr [ecx] //calculate the vtable address. It’s the value
( b% ?/ i/ g: t8 Z w //stored in ecx register. 5 d1 ]+ [1 o3 G& T
0040315C push edx //push the return address( E- w4 ~1 d, ], {, P
0040315D call dword ptr [eax+3Ch] //call the CreateDevice() function 1 C0 |3 l& r8 X' |+ V
00403160 mov dword ptr ,eax
7 t# k7 O3 r8 ^3 L3 Q% U L w: w0 b n
From 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.
/ U* R" ^$ b R6 l- N$ u
* A y. A/ b" O+ N3 \ l4 I+ xThe 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.
/ K6 b) {6 ]3 u/ PReference:7 x4 T* R& R) A A
[1] “API hooking revealed”, Ivo Ivanov4 W: A0 D, v% q$ d5 T( q7 c( W/ g
[2] “madCodeHook”, madshi
- t4 T0 Z/ F3 I3 f4 w; y[3] "Detours", Galen Hunt and Doug Brubacher2 D, L* A7 W3 E( ?. F8 i
[4] “Virtual Functions and their implementation in C”, Shivesh V.3 R/ A: u. ^, b" W: Y- Y
[5] “Pointers to C++ Member Functions”, Michael D. Crawford |