Windows Detours library for the people

Submitted by abb on Mon, 10/18/2010 - 12:52

Microsoft Detours library can be used to attach a hook to system functions invoked by Windows programs. You can write an arbitrary code which will get invoked when a program tries, for example, send something over SSL, or get a current timestamp, and handle it as it pleases you instead of (or in addition to) passing it to standard Windows libraries.

Hopefully notes below will be useful for fellas who, like myself, are not skilled Windows developers, but occasionally get thrown into the Windows world and need to intercept a function call or two.

Getting Detours library to work:

* Download and install MS Visual Studio Express 2010 (http://www.microsoft.com/express/Downloads/)
* Download and install Detours library (http://research.microsoft.com/en-us/projects/detours/)
* Build Detours library. In cmd.exe (on Windows 7 it has to be running as an administrator):
- "\Program Files\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"
- cd "\Program Files\Microsoft Research\Detours Express 2.1"
- nmake
+ it will build libraries and sample programs and places it
under lib\ and bin\ directory
+ on my PC it fails to finish for some reason, but after it
builds lib\ and bin\withdll.exe, so it is ok

Creating project to use with Detours lib:

* In Visual Studio create a Win32 DLL project
* Add paths to Detours library: Project properties / Configuration properties
- C/C++ / Additional Include Directories: add \Program Files\Microsoft Research\Detours Express 2.1\include
- Linker / Additional Library Directories: add \Program Files\Microsoft Research\Detours Express 2.1\lib
* Create source code:
- Copy the content of sample\simple\simple.cpp into dllmain.cpp
- Add two lines to ddlmain.cpp
+ #pragma comment(lib, "detours.lib")
+ #pragma comment(lib, "detoured.lib")
- Customize the remaining code as you need

When you have your DLL, run it with withdll.exe (located under bin/ directory, built in the very beginning of this exercise).

Other useful resources:

* DLL Creation with MinGW (http://sig9.com/node/35)
* Redirecting HTTP traffic (http://portswigger.net/misc/)
* ProcessMonitor tool (http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx)

Many thanks to Axel Meerschaert for his help with making these things work.

Contacts

+32 (0) 2 215 53 58

Gremwell BVBA
Sint-Katherinastraat 24
1742 Ternat
Belgium
VAT: BE 0821.897.133.