tags:

views:

1710

answers:

5

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?
A: 

On Linux, this can be done with the LD_PRELOAD environment variable. Set this variable to point at a shared library that contains a symbol you'd like to override, then launch your app.

dicroce
A: 

Could you offer some more details? Who languages are used, etc?

GregUzelac
+1  A: 

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.

Ates Goral
Okay... But, how to force the running processes to call my dll instead of the original one?
Daniel Silveira
If you place your wrapper DLL in the same folder as the executable, the executable should pick your DLL instead of the one under Windows/System32 etc.
Ates Goral
+4  A: 

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.

shoosh
Isn't this a huge security risk? Doesn't it basically give any one the ability to do anything in an app?
Micah
I tried to modify code of a function but this fire an access violation fault. Is there any details that should be fixed before ?
Emmanuel Caradec
+1  A: 

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 virusscanners/malware detectors. But your own process is fair game.

MSalters