Using the Detours Library hook API (the principle is to overwrite the first 5 bytes of a function)

Source: Internet
Author: User

First, the origin of Detours library and download:

The Detours library, similar to the origins of WTL, was developed by Galen Hunt and Doug Brubacher himself and was published in an article entitled Detours:binary Interception of Win32 Functions in July 99. 's paper. The rationale is to rewrite the first 5 bytes of the function (since the general function begins with three instructions that hold the stack environment in total 5 bytes: 8B FF 8B EC) is a jump instruction that jumps directly to the beginning of its function, thus enabling API interception. It was later supported by MS and provided the download space on its website:

Http://research.microsoft.com/research/downloads/Details/d36340fb-4d3c-4ddd-bf5b-1db25d03713d/Details.aspx

Currently the latest version is:detours Express 2.1.

Second, the use of detours preparation:

Detours Library is provided in the form of source code, which brings great convenience to our use. You can choose to compile it into a library, or you can add the source code directly to the project ... Forms of use. The method that the farmer takes is to compile into a library after use. The method of compiling the library is very simple, the download package has already produced the makefile, we just need to directly compile with the NMAKE tool under VC directly. In view of the previous time on the internet to see some friends on this also have doubts, farmers in this "waste" a bit of space, a detailed explanation of the compilation process (in parentheses for my example):

1. Run the installation package you downloaded and extract the files to disk

It is recommended that you copy the extracted src folder to the VC98 subdirectory of the VC's installation directory (D:/SDK/6.0/VC98). It's good to use libraries like I do, and later on:).

2. Compiling and setting up the development environment

In the SRC folder where you just copied the past, create a *.bat file that fills in the ". /bin/nmake "content and then save it. Run the batch file, congratulations: The library has been compiled, the only thing to do is to put the. Copy the/bin/detoured.dll to your system directory. Now your project contains the following documents to use the Detours Library for development:

#include <detours.h>

#pragma comment (lib, "Detours.lib")
#pragma comment (lib, "Detoured.lib")

There is no need to worry about a friend who has not copied the src file. BAT file, the path can be compiled with the full path. However, in addition to copying the. dll file, you have to copy the. lib,. h files to the VC directory, or set the include path to these files in your VC environment before you can use the VC for development. Look, do you want some trouble?

Another suggestion: Define a function pointer type in the Detours.h file, and you'll know it's handy when you use it:

typedef LONG (winapi* Detour) (pvoid*, PVOID);

Three, several important functions:

1, Detourattach & Detourdetach

These two functions are actually implemented API hooks (overwriting the first 5 bytes for a jump instruction), the previous implementation API interception, the latter to restore the original API when not needed.

The first parameter is a function that you have defined for saving the original system API, which is equivalent to the API when you are not hooked. Farmers are accustomed to the original API based on the "Sys" prefix to name;

The second parameter is the function that intercepts the API, and what you want to do "bad" is implemented in this function. Farmers are used to naming "Hook" prefixes based on the original API.

2, Detourcreateprocesswithdll

This function is used when intercepting API in DLL injection mode, it is actually encapsulating "CreateProcess", creating the process in "create_suspend" mode, then modifying IAT, putting Detoured.dll and your *. DLL into its import table, and then start the process. So its parameter is to add the path parameter of two DLL on the basis of ordinary CreateProcess, the last parameter is the function pointer of creating process, the default is createprocessa! It is important to note that if your program intercepts the function and calls the Detourcreateprocesswithdll function in Hookcreateprocessa, you must pass in Syscreateprocessa here. Otherwise your program will be called recursively, beware of your program crashing! As to why this is called? Oh, ask me why? :)

Of course, other APIs are also useful, but for developers, these three are the most important!

Iv. Examples of development:

There is a help document with the source code, which lists a number of examples: containing common APIs, class member functions, COM interfaces, dll-mode injection .... Contains most of our application areas.

Here is an example of intercepting the Createfilea function. This example moves all the created files to the specified directory (Halo, first time use, how can I not insert C + + code?). ):

1. Define the function of saving the original function of the system Syscreateprocessa: (sounds a bit clumsy)

StaticHANDLE (winapi* Syscreatefilea)(LPCTSTR lpfilename,//pointer to name of the file
DWORD dwdesiredaccess,//Access (Read-write) mode
DWORD dwShareMode,//share mode
Lpsecurity_attributes lpsecurityattributes,//Pointer to security ATTRIBUTES
DWORD dwcreationdisposition,//How to create
DWORD dwflagsandattributes,//File attributes
HANDLE htemplatefile//HANDLE to file with attributes to copy
) = Createfilea;

2. Write your own function function:

HANDLE WINAPI Hookcreatefilea(LPCTSTR lpfilename,//pointer to name of the file
DWORD dwdesiredaccess,//Access (Read-write) mode
DWORD dwShareMode,//share mode
Lpsecurity_attributes lpsecurityattributes,//Pointer to security ATTRIBUTES
DWORD dwcreationdisposition,//How to create
DWORD dwflagsandattributes,//File attributes
HANDLE htemplatefile//HANDLE to file with attributes to copy
)
{
Char chdestfile[256];

strcpy (Chdestfile, lpFileName);
if (Strstr (lpFileName, "////.//") = NULL)//Spare device
{
Create the normal file all go to D drive, here is not considered to be "read" Access
Char *p = STRRCHR (lpFileName, &apos;//&apos;);
if (p++ = = NULL)
{
p = lpfilename;
}

sprintf (Chdestfile, "d://%s", p);
}

Create a file, note that you can no longer call Createfilea, or you will be called recursively! Instead, it should be syscreatefilea!!!!.
Return Syscreatefilea (Chdestfile, ...); The following parameters will be copied.
}

3, hooks, replace the system API with your own function:

Detourattach (& (pvoid&) Syscreatefilea, Hookcreatefilea);
You can use Detourdetach when recovering.

This runs your program and finds that all new files created with Createfilea are transferred to the D drive.

Five, several questions:

1, byte encoding:

Many of the Win32 functions have multibyte a and wide-character W editions, so there is no addition of a or w suffix, because the compiler has done this for us. However, if there are two versions, it is important to make it clear that you do not use CreateFile as a function of the collection of bytes, such as gold.

2. Application object:

This library is suitable for beginners to intercept most APIs under RING3. For those who are the reverse master, this is simply unworthy;

3. Release:

Since the library is not included in the MS SDK, it is packaged Detoured.dll with the program. Of course, if you are directly using the source code to compile the project will be exempt from this file;

4. Block DLL parameter settings:

Take the above CreateFile function, if I want to transfer the file name to the D disk if it matches the specific conditions, for example, when the file type is TXT file is transferred. We can write the letter "D" and the file type "TXT" to die directly inside the program. In this case, if there are other programs to put the "PDF" file on the F-disk is not to rewrite it again?

Don't assume that adding an interface will solve the problem. If so, congratulate you on entering the farmer's original astray:)! In fact, to pass this parameter into the essence is the inter-process communication problem. I take is filemapping, rewrite a bit of detours source. Of course, other interprocess communication methods are also possible.

5. Intercept DLL must export a function

Generally, it is possible to have an empty function. If you don't have any exported functions, your hard-to-write DLLs won't work, and you might spend a lot of time troubleshooting them. Just declare one as follows:

////////////////////////////////////////////////////////////////////////////////
Must at least one export function:
__declspec (dllexport) void Exportfunc (void)
{
}

Vi. PostScript

Country Yefu, Trance in the world. Should be the plow, trade into it.

30 stands, nothing is accomplished. He died and tossed and turned.

Write quiet heart, idle to think far. Leisurely my ancestors, self-love Tao Qian.

My book begins, if there is improper/wrong, please friends leave your precious pen and ink.

======================

The first edition has been written for a long time.

Reproduced in: http://blog.csdn.net/vcplayer/article/details/2681758

http://blog.csdn.net/chence19871/article/details/10372695

Using the Detours Library hook API (the principle is to overwrite the first 5 bytes of a function)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.