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

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

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

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

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

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

写得很不错的文章,国人用英语写的,还有代码。) N! T* V" z* Q5 U6 I5 |
Hooking Direct3d, f9 e4 i  e. \/ A2 S# r/ e1 B9 V
By Jijun Wang/ e4 m! k1 D9 E: X: d
Introduction- g3 H5 |, v, t& {, ^: r- M
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. + D: ]- c) ?, H0 T5 \0 M! I& |

" j% _5 o5 v+ m7 }' VIn 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.  
; h, D/ g6 m1 J0 j* J+ ?; RHooking Technologies( E7 s- x( I0 S! i. C' T
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
: @5 M3 l- O' H$ z1) Register your DLL to the registry table. * F3 f4 K+ u& A# F1 I& S# A$ E* F% V
This 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.
. s2 t3 L& f' {" [2 e2) System-wide Windows Hooks. z+ W; a2 w% m
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.
2 Z( m; O7 R; @# Y& c9 F. |3) Create Remote Thread! y4 J$ t5 {8 a! X
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.
- S. p: o2 C" u  v
$ ^8 N/ Q+ Y. G6 x5 T5 WTo inject your code into another process’ code, we could use:
) f3 v/ v' }+ ]/ g  b1) Proxy DLL
( \$ P# c8 v- f+ b2 {! o0 gThis 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.   
* N$ H4 y# s1 `2) Altering of the IAT (Import Address Table)
. g: J# H6 j" x; @0 Q0 ?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.6 c1 r  H; {& g3 k" o
3) Code Overwriting8 G* J' R" R+ {1 A) Q
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.
" ~' K+ U) A3 d! a& X
; K2 B$ I- |% oFor 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./ m% `- C) T5 g* }+ ^
Detours
- L) c& m' W: S: U“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/
: X1 @; e6 e; W! ^: `4 d, n2 v9 E6 n6 l  {
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.  }( Q4 [* X' K' D
8 ~) u3 F& s7 h% ?) d# a3 |) \) `5 E
DETOUR_TRAMPOLINE(
* n1 T4 W* ~# i0 d# nUINT WINAPI Real_SetTimer(HWND hWnd,     // handle of window for timer messages
3 o4 M; E7 j& O6 I& G                        UINT nIDEvent,         // timer identifier7 W) \' l9 B& D+ L
                        UINT uElapse,            // time-out value
/ K3 k. T2 j7 g: j2 l                        TIMERPROC lpTimerFunc), // address of timer procedure& H& e% Z: ]' F: L# r" @. z- j
SetTimer);5 `4 d) _2 k! o& e* g0 D8 b- U
4 {2 e8 W+ M; c
Then we write our own SetTimer function.' e. I2 p& Y, a# u8 q
UINT WINAPI Mine_SetTimer(' N% F4 |. w: C6 @1 }
    HWND hWnd,           // handle of window for timer messages0 l1 O& n- |' k6 h2 r
    UINT nIDEvent,        // timer identifier
. t/ V" S: K' x6 l4 }7 m    UINT uElapse,           // time-out value; }0 \0 ^7 ?' Q. H5 R: g+ J
    TIMERPROC lpTimerFunc   // address of timer procedure
( S$ ~1 O" \9 W. {2 ^    )' t3 Q  `# g7 L9 J
{4 s5 H! s/ j' Z
    uElapse=10* uElapse;
+ }0 y4 R/ m# Z    return Real_SetTimer(hWnd,nIDEvent,uElapse,lpTimerFunc);
! |( ^9 {9 _" b6 W: Q}
( \2 p7 ]4 r& O
8 s, Z  J, u2 n) x) P4 I; JThen write the functions to intercept the Real_SetTimer() function to your own Mine_SetTimer() function and the function that removes the interception.
+ \3 F5 w0 V1 ~
! S2 \" T8 B! ^; e% s* T$ UBOOL TrampolineWith(VOID)9 Z$ K! P9 i" T: A4 F0 u* C
{
& Z& V+ F+ M$ g# t8 p2 Q4 V3 x/ z- G    DetourFunctionWithTrampoline((PBYTE)Real_SetTimer,; U8 z6 Y# S5 f( u: N& j
                                        (PBYTE)Mine_SetTimer);+ y& x+ b- z. y  U" [
    return TURE;9 v% f- a4 R3 P1 g$ p$ \
}3 a: M) X9 L  l) A

5 L; e+ Y' F, s+ S9 zBOOL TrampolineRemove(VOID)
0 i# N  G. t+ f. G( T+ Z" ?% l, C{
. D) Z2 D+ B9 v6 Z4 F( L    DetourRemove((PBYTE)Real_SetTimer,, U+ K5 {& s: m' R: D0 u8 P0 h
               (PBYTE)Mine_SetTimer);9 J' S/ N5 A# f, ~# w
    return TRUE;
$ ?4 R4 M  Y8 g& K2 i}
8 j8 H" u2 v3 \. d4 W; J2 V& k
6 \) d2 Z0 v( ^/ u# a' a3 dAt last, we write the DLLmain function.0 y/ e+ V4 a( H

; _( I( ^" |. k8 Y2 G( yBOOL APIENTRY DllMain(HINSTANCE hModule, DWORD dwReason, PVOID lpReserved)
1 A; y9 s* Z2 N8 Y- H# ?( y{
7 Q6 s4 A* @4 Z" V    switch (dwReason) {
2 n8 _5 A2 Y+ N# i      case DLL_PROCESS_ATTACH:
2 C* t- B! l; y; R        return TrampolineWith();
" k5 ~' r+ [. U8 h. w      case DLL_PROCESS_DETACH:
5 k9 Q8 b( ?; \1 m1 j+ t        return TrampolineRemove();0 d" {/ h& c9 t. a5 C" W7 ~1 B7 s
      case DLL_THREAD_ATTACH:3 W( f8 ^; c. L, p4 d0 _, j$ q
        return TrampolineWith();
2 B# p9 I# f! {6 n7 J7 d      case DLL_THREAD_DETACH:
0 S3 M' e; r% h/ F4 n: L        return TrampolineRemove();' L/ M1 O2 L" k, d! p1 X' N6 p7 z
    }
  I3 f* Q! q9 [" L; @    return TRUE;
% Y, q' D5 ?7 C) e+ p}' ], E' i/ A: v! F

' R% \  w, d( A9 L! wBy 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.
7 X  N* Q3 W! t& {/ l- M$ a5 J) c; h( _; Y  t  _
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.
% b) y( ]9 Y% M: O: S7 g& j- l3 D! L. M6 _/ @' n, t+ L' O7 K4 i2 }- S
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.
5 q! F6 P' ^% V  h3 ?  ~( |- b. \Understanding Virtual Functions and Hooking Direct3d
# W: x" M3 _( B0 H, m7 t  P/ S: oVirtual 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”.
3 O0 w% K6 R9 @* t
+ B( r( R1 ~" _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:1 B% g0 |2 [: D9 L- m/ m
1) Catch Direct3DCreate8() to get the IDirect3D8 object: f. X0 R; B6 }2 O
2) Use the pointer of IDirect3D8 object, catch the CreateDevice() function to get the IDirect3DDevice8 object.. A6 a( e3 O  d0 \& m
3) Use the pointer of IDirect3DDevice8 object, catch Present() function.
% @% p1 \# E+ P4 b4) In the Present() function calculates the frame rate.) ?2 y: a' W2 C( d" Q- W& \$ ], @
' m8 @+ y$ x3 b' L9 M9 H# h+ X
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.
& v) E3 ~' I$ l5 S0 m' w! Q1 B" e/ M$ _) j
873:      // Create the device
' T1 N: T( u+ h% ~8 [1 n1 j2 b874:      hr = m_pD3D->CreateDevice( m_dwAdapter, pDeviceInfo->DeviceType,
" B: V! x' G# ]( J875:                                 m_hWndFocus, pModeInfo->dwBehavior, &m_d3dpp,. g( m3 U  _. o6 k6 U
876:                                 &m_pd3dDevice );
5 N  Z; t5 J6 e& ]& w" R; ]00403114   mov         eax,dword ptr [this]. y/ m, z: o" z) W' y+ D: |& M& o) z
00403117   add         eax,2A4A8h6 E" _. f2 [) z/ q, G0 W  M" w
0040311C   push        eax            // push the sixth parameter &m_pd3dDevice5 ^* _9 Z# i# l+ [
0040311D   mov         ecx,dword ptr [this]7 w- O. n" @+ n- }! s; @! Z
00403120   add         ecx,2A464h% z6 j+ }/ K: F" Q
00403126   push        ecx            //push the fifth parameter &m_d3dp
; D+ @" _; ^: E' }; R00403127   mov         edx,dword ptr [pModeInfo]1 m. Z; Z' \; g6 x7 M& i9 y
0040312A   mov         eax,dword ptr [edx+0Ch]3 M) t2 D" Y3 L, t# b6 m: y
0040312D   push        eax    //push the fourth parameter pModeInfo->dwBehavior9 u& Q+ x8 W# {' A0 W* w( Q
0040312E   mov         ecx,dword ptr [this]
$ s& A  n6 m/ h$ t( A) b7 l, \00403131   mov         edx,dword ptr [ecx+2A49Ch]
7 [  m7 m5 z8 c  ^' J00403137   push        edx    //push the third parameter m_hWndFocus
  G) {+ K* S! M: i00403138   mov         eax,dword ptr [pDeviceInfo]* l; {% N( ^7 z! m
0040313B   mov         ecx,dword ptr [eax]
( r7 R$ Y4 u# \; [0040313D   push        ecx    //push the second parameter pDeviceInfo->DeviceType
% ]- r$ J' L7 u7 J7 w6 N0040313E   mov         edx,dword ptr [this]! K7 L  D* B; \$ Q! g0 O' O7 @
00403141   mov         eax,dword ptr [edx+2A448h]
& ^) P  _$ `( X  K* F9 f0 [2 I3 p00403147   push        eax    //push the first parameter m_dwAdapter
& E% z0 L8 c$ v! U6 ~00403148   mov         ecx,dword ptr [this]
* X. g( M7 A: t( a* h: t0040314B   mov         edx,dword ptr [ecx+2A4A4h]    //calculate the return address
8 E2 H: a0 A: L00403151   mov         eax,dword ptr [this]" w; v$ q9 B; H6 x0 K
00403154   mov         ecx,dword ptr [eax+2A4A4h]
0 ~% z7 a. H* x, ^+ {+ t) t0040315A   mov         eax,dword ptr [ecx]    //calculate the vtable address. It’s the value
9 V+ E' h* c" [5 e                        //stored in ecx register.
8 \7 t2 v/ Q2 M  |) b0040315C   push        edx    //push the return address$ m9 A  G9 [1 r* ?4 b0 R
0040315D   call        dword ptr [eax+3Ch]    //call the CreateDevice() function ' v/ j) o% N/ D9 O; q: l; p
00403160   mov         dword ptr
,eax' Z1 D- k/ Y& n+ r. ^
3 k  E$ S% u4 X" V" C9 X. e) x2 @
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.
1 Z/ W+ q: P/ f0 q2 V
; O. c! F8 `# K. @6 v9 JThe 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./ r, L% s9 Q- P# `* V; l
Reference:. B# c( w+ _& C) w/ C
[1] “API hooking revealed”, Ivo Ivanov; J! f* G* S- C- ?
[2] “madCodeHook”, madshi: u. S7 J( g/ I" a; O7 q
[3] "Detours", Galen Hunt and Doug Brubacher& T8 W/ C- ~$ B1 E# [% n4 K) s
[4] “Virtual Functions and their implementation in C”, Shivesh V.5 `0 I) ?$ r% k$ d2 c7 N4 m" `
[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日,是全球华人共同的冒险解谜类游戏家园。我们致力于提供各类冒险游戏资讯供大家学习交流。本站所有资源均不用于商业用途。

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