Hook Technology 2_DETOUR+API Interception technology

Source: Internet
Author: User
Tags api manual

Recently, the company to do a remote Desktop control software, which uses the API hook technology, because not previously contacted such technology, just at the beginning of the time to follow the "Windows core programming" introduced in the modified IAT table method to implement the API hook, But the process of creating a third-party tool in a project, which can be injected into the existing project, but the third-party tool I do not have the source code, because of the time rush to this method of the hook understanding is not deep, found that this method can not achieve the injection of createproccess initiation process, Have the world class and colleagues to eat, to him to talk about this aspect of the problem, he happened to have done this kind of project, he recommended to me Microsoft's detours library, after the weekend to search the relevant information on the Internet, found that this library really can meet my needs, the following information is I search copies from the Internet, Feel this article for beginners understand detours library has a lot of help, so save up. The most straightforward purpose of intercepting function execution is to add functionality to the function, modify the return value, or add additional code for debugging and performance testing, or intercept the input and output of the function for research and hack use. By accessing the source code, we can easily use the method of rebuilding (rebuilding) operating system or application to insert new function or function extension among them. However, in today's commercial development world, and in systems with only binary code releases, researchers have little chance of getting the source code. This paper mainly discusses the API interception technology based on the Windows binary PE file (detour). For the Linux platform, doing this will be very simple, as the original operating system designer introduced Ld_preload. If you set the ld_preload=mylib.so, the application will view the mylib.so symbol table first when loading the DLL, and will take precedence over the symbols in mylib.so when relocation. If you have a printf () in mylib.so, then this printf will replace LIBC's printf. In mylib.so, this printf can directly access the printf function pointer in libc.so to get the real printf entry address. In this way, all the DLL API hooks in the loader load DLL when it has been completed, very natural, and platform-related parts are all handed to loader to deal with.
First, Detour Development library:
? Brief introduction
Detours is a tool library that intercepts arbitrary Win32 function calls on the x86 platform. Interrupt code can be loaded dynamically at run time. The detours uses an unconditional transfer instruction to replace the first few instructions of the target function, transferring the control flow to a user-provided intercept function. Some of the instructions in the objective function are stored in a function called "trampoline" (English meaning trampoline, acrobatics), where I think it is appropriate to translate the partial clone/copy of the target function. These directives include the replaced code in the target function and an unconditional branch that jumps back to the target function. The Intercept function can replace the target function, or extend the function by invoking the target function as a subroutine by executing the "trampoline" function.
The detours is inserted at execution time. The code of the target function in memory is not modified on the hard disk, so it makes it easier to intercept the execution of the binary functions at a good granularity. For example, a Function procedure in a DLL that is loaded when an application executes can be inserted into a intercept code (detoured), while the DLL can be executed by other applications as normal (that is, it is executed in a way that is not intercepted because the DLL binaries are not modified. So interception occurs without affecting other process space loading this DLL). Unlike DLL relink or static redirection, this interrupt technique used in the Detours library ensures that methods in the application or system code are not affected by the positioning of the target function.
If other people try to modify the binary code in order to debug or use other system detection methods internally, detours will be a universally available development package. As far as I know, detours is the first development package that can be preserved on any platform as a subroutine that can be called by "trampoline". Instead of invoking the original target code as a trivial subroutine, the previous system logically pre-intercepts the interception code into the target code. Our unique "trampoline" design is critical to extending the binary code of existing software.
For the purpose of using the basic function intercept function, detours also provides the ability to edit any DLL import table to add an arbitrary data section table to the existing binary code, injecting a DLL into a new process or an already running process. Once the DLL is injected into a process, the dynamic library can intercept any Win32 function, whether it is in the application or in the system library.
? Basic principle
1. Memory management of the WIN32 process
As is known to all, WINDOWS NT implements virtual memory, each WIN32 process has 4GB of virtual storage space, about the WIN32 process of the virtual storage structure and its operation details please refer to the WIN32 API manual, the following only points related to detours:
(1) The instructions to be executed by the process are also placed in the virtual storage space
(2) You can use the Queryprotectex function to change the permissions of the page that holds the instruction to a readable writable executable, and then overwrite its contents to modify the running program
(3) You can use VirtualAllocEx to assign a virtual memory to another running process from one process, then use the Queryprotectex function to change the permissions of the page to a readable writable executable, and write the instruction to be executed in the form of a binary machine code. To inject arbitrary code into a running process.
2. How to intercept the WIN32 API
The detours defines three concepts:
(1) The target function: The function to intercept, usually the Windows API.
(2) Trampoline function: A partial replica of the target function. Because detours will overwrite the target function, the first 5 bytes of the target function are copied and saved, while the process of the target function is still preserved, while the other is convenient for later recovery.
(3) Detour function: A function to replace the target function.
Detours Add the JMP address_of_ detour_ function Directive (5 bytes) at the beginning of the target function to direct the call to the target function to its own detour function, adding 5 bytes at the beginning of the target function to JMP Address_of_ Target _ function+ 5 A total of 10 bytes as trampoline function. Please refer to Figure 1 and figure 2 below.
(Figure 1:detour The process of the function) (Figure 2:detour Function call procedure) Description:
? Target function:
The function body (binary) of the objective function is at least 5 bytes in the system. According to Microsoft's instructions document the function body of the trampoline function is a copy of the first 5 bytes plus an unconditional jump instruction (if there is no special processing indivisible instructions), then the first 5 bytes must be the complete instruction, that is, the 5th byte and the 6th byte is an inseparable instruction, Doing so causes the trampoline function to execute incorrectly, and a complete instruction is rigidly separated, causing the program to crash. For the 5th and 6th bytes are indivisible instructions need to adjust the number of bytes copied to the acrobatic function (trampoline), this value can be seen in the assembly code of the target function. This function is a modified version of the target function and cannot be called directly in the Detour function, and it needs to be called by the trampoline function to reach the indirect call.
? Trampoline function:
This function is assigned 32 bytes by default, and the contents of the function are the first 5 bytes of the copied target function, plus a jmp address_of_ target _ function+5 instruction, a total of 10 bytes.
This function is only for your detour function call, after executing the first 5 bytes of instruction and then absolutely jumping to the 6th byte of the target function to continue executing the original function function.
? Detour function:
This function is a mock version of the interception API that the user needs, the invocation method, the number of parameters must match the target function. If the target function is __stdcall, then the Detour function declaration must also be __stdcall, and the number and type of arguments must be the same, or the program will crash. This function is called when the program calls the first instruction of the target function (unconditionally jumping over), and if you want to continue calling the target function in this function, you must call the trampoline function (the trampoline function will unconditionally jump to the target after executing the first 5 bytes of the target function) After 5 bytes of the function continues to execute), the target function can no longer be called directly, otherwise it will go into infinite recursion (the target function jumps to the Detour function, and the Detour function jumps to the recursive function of the target, because the target function in the memory of the first 5 bytes has been modified to absolute jump). The execution result of the target function can be obtained after the call to the trampoline function, which is useful for analyzing the target function, and can be modified and then passed back to the application.
Detour provides two ways to inject detour functions into a running application and inject detour functions on the basis of binary files. This chapter mainly discusses the second mode of work. The development package provided by detours can add a section table called Detour in the binary EXE file, as shown in 3, the main purpose is to implement the PE loader loading application automatically when you write the Detours DLL, in the Detours The detour of the target function is completed in the DllMain in the DLL.
(Figure 3) Two, the detours provides the interception API related interface
The API interface provided by detours can be called as a shared DLL to an external program or as a static LIB link to your program.
The trampoline function can be created dynamically or statically, and if the target function itself is a link symbol, using the static trampoline function will be very simple. If the target function cannot be visible at link time, then the dynamic trampoline function can be used.
? To use the static trampoline function to intercept the target function, the application must use the trampoline when generating the
Detour_trampoline macros. Detour_trampoline has two input parameters: Trampoline's prototype and the name of the target function.
Note that for the correct interception model, including the target function, the trampoline function, and the Intercept function must be the exact same invocation form, including the parameter format and the calling convention. It is the responsibility of the Intercept function to copy the correct parameters when calling the target function through the trampoline function. Since the target function is just a callable branch of the Intercept function (The Intercept function can call the trampoline function or not), this responsibility is almost a subconscious behavior.
Using the same calling convention ensures that the values in the register are saved correctly and that the call stack is correctly set up and destroyed when the function calls the target function.
You can use the Detourfunctionwithtrampoline function to intercept the target function. This function has two parameters: the trampoline function and the pointer to the Intercept function. Because the target function has been added to the trampoline function, all of them do not need to be specifically specified in the parameters.
? We can use the Detourfunction function to create a dynamic trampoline function, which consists of two parameters: a pointer to the target function and a pointer to the Intercept function. Detourfunction assigns a new trampoline function and inserts the appropriate interception code into the target function.
When the target function is not very easy to use, the Detourfindfunction function can find the function, whether it is an exported function in the DLL, or it can be found through the debug symbols of the binary target function.
Detourfindfunction accepts two parameters: the name of the library and the name of the function. If the Detourfindfunction function finds the specified function, returns a pointer to the function, otherwise a null pointer is returned. Detourfindfunction will first use the Win32 function LoadLibrary and GetProcAddress to locate the function, if the function is not found in the DLL's export table, Detourfindfunction will use the Imagehlp library to search for valid debug symbols (the debug symbols here refer to the debug symbols provided by Windows itself, which need to be installed separately, please refer to the User diagnostic support information for Windows). The function pointer returned by Detourfindfunction can be used to pass to detourfunction to generate a dynamic trampoline function.
We can call Detourremovetrampoline to get rid of the interception of a target function.
Note that since the function in detours modifies the address space of the application, it is the responsibility of the programmer to ensure that no other thread executes in the process space when the Intercept function is added or the Intercept function is removed. A simple way to ensure that this is a single-threaded execution is to call the function in DllMain when loading the detours library.
Iii. using detours to implement two methods of intercepting API
Create an MFC dialog box project, add a call to the MessageBoxA function in the Click event of the OK button of the dialog box, the compiled program name Messageboxapp, the effect. (Fig. 4)
? Static methods
Build a DLL project named Apihook, described here in the visual c++6.0 development environment, to intercept the ASCII version of the MessageBoxA function. In the DLL's engineering join:
Detour_trampoline (int WINAPI Real_messagebox (HWND hwnd,
LPCSTR Lptext,
LPCSTR Lpcaption,
UINT utype),:: MessageBoxA);
Generate a static MessageBoxA trampoline function that joins the Detour function of the target function in the DLL project:
int WINAPI Messagebox_mine (HWND hwnd,
LPCSTR Lptext,
LPCSTR Lpcaption,
UINT Utype)
{
CString tmp= Lptext;
tmp+= "intercepted by Detour";
Return Real_messagebox (Hwnd,tmp,lpcaption,utype);
Return:: MessageBoxA (Hwnd,tmp,lpcaption,utype); Error
}
In the DLL entry function, in the load DLL event, add:
Detourfunctionwithtrampoline ((pbyte) Real_messagebox, (pbyte) messagebox_mine);
In the DLL entry function, in the Unload DLL event, add:
Detourremove ((pbyte) Real_messagebox, (pbyte) messagebox_mine);
? Dynamic methods
Build a DLL project named Apihook, described here in the visual c++6.0 development environment, to intercept the ASCII version of the MessageBoxA function. In the DLL's engineering join:
Declaring a function prototype like MessageBoxA
typedef INT (WINAPI * messageboxsys) (HWND hwnd,
LPCSTR Lptext,
LPCSTR Lpcaption,
UINT Utype);
Target function pointer
Messageboxsys Systemmessagebox=null;
Trampoline function pointer
Messageboxsys Real_messagebox=null;
Add the Detour function of the target function to the DLL project:
int WINAPI Messagebox_mine (HWND hwnd,
LPCSTR Lptext,
LPCSTR Lpcaption,
UINT Utype)
{
CString tmp= Lptext;
tmp+= "intercepted by Detour";
Return Real_messagebox (Hwnd,tmp,lpcaption,utype);
Return:: MessageBoxA (Hwnd,tmp,lpcaption,utype); Error
}
In the DLL entry function, in the load DLL event, add:
systemmessagebox= (Messageboxsys) detourfindfunction ("User32.dll", "MessageBoxA");
if (systemmessagebox==null)
{
return fasle;
}
real_messagebox= (Messageboxsys) detourfunction ((pbyte) Systemmessagebox, (pbyte) messagebox_mine);
In the DLL entry function, in the Unload DLL event, add:
Detourremove ((pbyte) Real_messagebox, (pbyte) messagebox_mine);
? Rewrite binary executable file
Rewrite the binary executable with detours's own SetDll.exe to include a new Detours PE section table in the program that needs to be intercepted. For this article, a new batch file is called SetDll.exe.
@echo off
If not exist MessageBoxApp.exe (
echo please extract the files to the MessageBoxApp.exe installation directory and execute the patch
) Else (
Setdll/d:apihook.dll MessageBoxApp.exe
)
Pause
After the call using Depends.exe (one of the tools of the Microsoft VC6.0 Development Kit) to observe the changes before and after MessageBoxApp.exe, you can see that Setdll has rewritten MessageBoxApp.exe
Success, joined the dependency on ApiHook.dll. (Before executing SetDll.exe) (after executing SetDll.exe)
After performing the SetDll.exe rewrite of the MessageBoxApp.exe, click OK to see the results as follows:
At this point, MessageBoxApp.exe's call to the MessageBoxA function has been intercepted, and the contents of the popup dialog box have been clearly explained.

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.