Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to intercept dll method calls?

Tags:

windows

dll

How to intercept dll method calls?

  • What are the techniques available for it?
  • Can it be done only in C/C++?
  • How to intercept method calls from all running processes to a given dll?
  • How to intercept method calls from a given processes to a given dll?
like image 586
Daniel Silveira Avatar asked Oct 21 '08 01:10

Daniel Silveira


3 Answers

There are two standard ways I can think of for doing this

  • DLL import table hook.
    For this you need to parse the PE Header of the DLL, find the import table and write the address of your own function instead of what is already written there. You can save the address of the original function to be able to call it later. The references in the external links of this wikipedia article should give you all the information you need to be able to do this.

  • Direct modification of the code. Find the actual code of the function you want to hook and modify the first opcodes of it to jump to your own code. you need to save the opcode which were there so they will eventually get executed. This is simpler than it sounds mostly because it was already implement by no less than Microsoft themselves in the form of the Detours library.
    This is a really neat thing to do. with just a couple of lines of code you can for instance replace all calls to GetSystemMetrics() from say outlook.exe and watch the wonders that occur.

The advantages of one method are the disadvantages of the other. The first method allows you to add a surgical hook exactly to DLL you want where all other DLLs go by unhooked. The second method allows you the most global kind of hook to intercept all calls do the function.

like image 173
shoosh Avatar answered Nov 09 '22 09:11

shoosh


Provided that you know all the DLL functions in advance, one technique is to write your own wrapper DLL that will forward all function calls to the real DLL. This DLL doesn't have to be written in C/C++. All you need to do is to match the function calling convention of the original DLL.

like image 27
Ates Goral Avatar answered Nov 09 '22 09:11

Ates Goral


See Microsoft Detours for a library with a C/C++ API. It's a bit non-trivial to inject it in all other programs without triggering virus scanners/malware detectors. But your own process is fair game.

like image 3
MSalters Avatar answered Nov 09 '22 07:11

MSalters