This article is posted from external
You have no intention of offending the website. If there is any infringement, please notify us in advance and this blog will promptly handle it.
This article attempts to explain the majority of hook content in the following sequence:
1. Windows Message Mechanism
2. Hook Introduction
3. hook chain
4. Hook Scope
5. Hook type
6. Callback Function
7. Install and uninstall hook
++
Message Mechanism in Windows
++
Windows uses message processing as its control mechanism.
Procedure. Both the system and application can generate messages. For each input event, for example
The user presses a key on the keyboard, moves the mouse, clicks the scroll bar on a control, and so on.
A series of messages are generated. In addition, changes to the system brought by applications, such as changes to font resources and Applications
Window changes, the system will respond to such changes through messages. The window through which the application generates a message to indicate the application
Complete a specific task or communicate with other application windows.
Each window has a processing program that processes messages sent by Windows system. It is called a window program. It is
A program script hidden behind the window contains the code for processing the event.
In Windows, a message number is specified for each message. For example, when a window changes to an active window
In fact, a wm_activate message from the Windows system is received. The message number is 6.
Activate event in the VB window. For Windows, such as open, activate, mousedown, and resize
In fact, it corresponds to the Message Processing Program in the window, which is invisible to users.
Similarly, the command button also has a message processing program whose response is like wm_lbuttondown.
And wm_rbuttondown, that is, the mousedown event of the activation command button.
Windows message processing mechanism to monitor various system event messages in applications
Hook Function. This hook function is similar to extending the interrupt driver,
Multiple reverse call functions can be attached to a hook to form a function chain. Various messages generated by the system are first sent
To various hook functions, the hook function monitors, modifies, and controls messages based on their respective functions, and then submits
Also control the permission or pass the message to the next hook function so that the window function is reached. Windows System
Although this method may slightly affect the system running efficiency, it is very common in many cases.
By using the hook function monitoring mechanism of keyboard events reasonably and effectively, unexpected good results can be achieved.
Result.
++
Hook Introduction
++
Hook is a message processing platform provided by windows.
A pre-started function that checks and modifies the information sent to the program before receiving information in the row.
It is a program segment for message processing. It is called by the system and mounted to the system. When a specific message is sent,
Before the target window is reached, the hook program first captures the message, that is, the hook function obtains control first. This
The hook function can process (Change) the message, or continue to transmit the message without processing it.
Message transmission can be forcibly ended.
Note: Installing the hook function will affect the system performance. System hook feature for monitoring "system scope events"
Not obvious. Because the system will call your hook function when processing all related events, your system will
It will obviously slow down. Therefore, use it with caution and uninstall it immediately after use. Also, because you can intercept other
Process message, so once your hook function has a problem, it will certainly affect other processes. Remember: Feature
Being powerful also means taking responsibility for use.
++
Hook chain
++
Windows provides 14 different types of hooks. Different hooks can process different types of hooks.
. For example, the wh_mouse hook is used to monitor mouse messages.
Windows maintains their respective hook linked lists for these hooks. Hook linked list is a string
The callback function queue defined by the application. When a certain type of message occurs,
Windows sends the message to the first function (the top of the hook chain) of this type of hook chain,
After the first function completes processing the message, the function transmits the message to the next function in the linked list, in turn down. For example
If a function in the chain does not send the message downward, the function following the chain table will not receive the message. (Pair
For some types of hooks, whether or not the functions in the hook chain transmit messages downward
All associated hook functions receive messages sent by the system. Some hook sub-processes can only monitor messages,
Or modify the message, or stop the message moving forward, to prevent the message from being transmitted to the next hook sub-process or
Destination window. Recently installed hooks are placed at the beginning of the chain, while the earliest installed hooks are placed at the end, that is, the suffix
First obtain control.
++
Hook Scope
++
There are two types of hooks: local and remote.
1. Local hooks only hook events of your own processes.
2. Remote hooks can also hook events that occur in other processes.
There are two remote hooks:
1. Based on the thread, it will capture events of a specific thread in other processes. In short
To observe the events that will occur in a specific thread in other processes.
2. System-wide event messages will be captured by all processes in the system.
++
Hook type
++
Windows has 14 hooks, each of which enables applications to monitor different types of hooks.
System message processing mechanism. The following describes the occurrence time of all available hook types. (These
Values can be found in the API browser)
1. wh_callwndproc and wh_callwndprocret hooks
Wh_callwndproc and wh_callwndprocret hooks allow you to monitor and send
Window Process message. The system calls wh_callwndproc before the message is sent to the receiving window.
Hook sub-process, and call wh_callwndprocret hook after the Window Process completes Message Processing
Sub-process.
Wh_callwndprocret hook transfers the pointer to the cwpretstruct structure, and then transfers it
Hook sub-process. The cwpretstruct structure contains the returned values from the window process for processing messages.
The message parameters associated with the message are also included.
2. wh_cbt hook
The system will call the wh_cbt hook sub-process before the following events, including:
1. Window events such as activation, creation, destruction, minimization, maximization, movement, and size change;
2. Complete system commands;
3. Move the mouse and keyboard events from the system message queue;
4. Set the input focus event;
5. Synchronize system message queue events.
The Return Value of the hook sub-process determines whether the system allows or prevents one of these operations.
3. wh_debug hook
The system calls
Wh_debug hook sub-process. You can use this hook to determine whether to allow system calls and other
The hook subprocess associated with the hook.
4. wh_foregroundidle hook
When the foreground thread of the application is idle, you can use wh_foregroundidle
Hook to execute tasks with lower priority. When the foreground thread of an application changes to idle, the system
The wh_foregroundidle hook sub-process is called.
5. wh_getmessage hook
The application uses the wh_getmessage hook to monitor the getmessage or peekmessage function.
Number of returned messages. You can use the wh_getmessage hook to monitor mouse and keyboard input, and
Other messages sent to the message queue.
6. wh_journalplayback hook
Wh_journalplayback hook enables applications to insert messages to system message queues. Yes
To use this hook to play back the continuous rat recorded by using the wh_journalrecord hook
Tag and Keyboard Events. As long as the wh_journalplayback Hook has been installed, the mouse and keyboard are normal.
The event is invalid. Wh_journalplayback hook is a global hook, which cannot be thread-specific
Hook. Wh_journalplayback hook returns a timeout value, which tells the system where
How long it takes (in milliseconds) to wait before the current message is played back ). This allows the hook to control the real
The playback of current events. Wh_journalplayback is system-wide local hooks and they are not
Inject to any travel address space.
7. wh_journalrecord hook
The wh_journalrecord hook is used to monitor and record input events. Typically, you can use this
Record consecutive mouse and keyboard events, and then use the wh_journalplayback hook
. The wh_journalrecord hook is a global hook and cannot be the same as a thread-specific hook.
. Wh_journalrecord is system-wide local hooks and they are not injected into any row
The address space.
8. wh_keyboard hook
In the application, wh_keyboard hook is used to monitor wm_keydown and
Wm_keyup messages, which are returned through the getmessage or peekmessage function. Enable
This hook is used to monitor the keyboard messages that are input to the message queue.
9. wh_keyboard_ll hook
Wh_keyboard_ll hook monitors keyboard messages that are input to the thread message queue.
10. wh_mouse hook
Wh_mouse hook monitors the mouse messages returned from the getmessage or peekmessage function.
Use this hook to monitor the mouse messages that are input to the message queue.
11. wh_mouse_ll hook
Wh_mouse_ll hook monitors the mouse messages that are input to the thread message queue.
12. wh_msgfilter and wh_sysmsgfilter hooks
Wh_msgfilter and wh_sysmsgfilter hooks allow us to monitor menus and scroll
Messages, message box, dialog box message, and found that the user uses Alt + TAB or Alt + ESC to switch the window.
Wh_msgfilter Hook can only monitor messages transmitted to menus, scroll bars, message boxes, and
Messages in the dialog box created by the application that has installed the hook sub-process. Wh_sysmsgfilter hook
Monitor all application messages.
Wh_msgfilter and wh_sysmsgfilter hooks allow us
Filter messages, which is equivalent to filtering messages in the main message loop.
Call the callmsgfilter function to directly call the wh_msgfilter hook. By using this
Applications can use the same code to filter messages during the pattern loop, as in the main message cycle
Ring.
13. wh_shell hook
Shell applications can use the wh_shell hook to receive important notifications. When the shell application is
The system calls the wh_shell hook sub-process when the top-level window is created or destroyed.
Wh_shell has a total of 5 minutes:
1. As long as a top-level and unowned window is generated, acted, or destroyed;
2. When taskbar needs to re-draw a button;
3. When the system needs to display the minimal form of a program about taskbar;
4. When the current keyboard layout status changes;
5. When the user presses Ctrl + ESC to execute Task Manager (or programs of the same level ).
By convention, shell applications do not receive wh_shell messages. Therefore
Before receiving the wh_shell message, the application must call the systemparametersinfo function to register
Ji.
++
Callback Function (Hook processing sub-process)
++
To intercept and process specific messages, you can use the setwindowshookex function (
Description of the Declarations and various parameters of these functions) install your own processing hooks in the hook chain of this type.
(Callback function ). Windows calls
Use the hook function. For example, if the hook you installed is of the wh_mouse type, only one mouse event occurs.
The hook function is called. No matter which type of hook you have installed, the hook function prototype is
The syntax is as follows:
Public Function myhook (byval ncode as long, byval wparam as long, byval lparam
As long) as long
'Processing code
End Function
Myhook can be named at will, and others cannot be changed. This function must be placed in the module section.
Parameter description:
Ncode specifies the information type passed in by the hook. The hook sub-process uses this parameter to determine the task. This
The value of the parameter depends on the hook type. Each Hook has its own hook code feature character set.
Wparam: Short integer parameter.
Lparam: Long Integer parameter.
The value of wparam and iparam varies with ncode. It represents a feature of a certain type of hook.
Fixed action. Their typical values include information about sending or receiving messages.
As for the specific meanings of the preceding parameters and returned values, different types of hooks are different, so you must
You must query the Win32 API guide to get detailed definitions of different types of hook parameters and the meanings of their return values.
. (If any of your friends have time and interest, please paste them out and send me a copy by the way. My email:
Wlclass163.com)
For example:
Wh_callwndproc
Ncode can only be hc_action, which indicates that a message is sent to a window.
If wparam is not 0, it indicates the message being sent.
Lparam pointer to the cwpstruct struct variable
Return Value: unused. 0 is returned.
Wh_mouse
Ncode is hc_action or hc_noremove
Wparam contains the mouse event message
Lparam pointer to the mousehookstruct struct variable
Return Value: If not processed, 0 is returned; otherwise, a non-0 value is returned.
++
Hook installation/uninstall
++
Now we know some basic theories. Next we will explain how to install and uninstall a hook.
◆ Installation hook
Use the setwindowshookex function (API function) to specify a hook type and its own hook
Whether the process is global or local hook, and the entry point of the hook process, you can easily install
Your own hook process.
Setwindowshookex always places your hook function at the top of the hook chain. You can use
The callnexthookex function transmits system messages to the next function in the hook chain.
[Note] for some types of hooks, the system will send messages to all hook functions of the class,
The callnexthookex statement in the hook function is ignored.
The global (Remote hook) hook function can intercept a specific message from all threads in the system.
To install a global Hook, you must create a DLL outside the application and seal the hook function
When installing the global Hook, the application must first obtain the handle of the DLL module. Set DLL
Pass the name to the loadlibrary function to obtain the handle of the DLL module.
The getprocaddress function obtains the address of the hook process. Finally, use setwindowshookex
The first address of the hook process is embedded in the corresponding hook chain. setwindowshookex transmits a module handle,
It is the entry point of the hook process, and the thread identifier is set to 0, pointing out that the hook process is the same as
There is a thread Association. If a local hook is installed, the hook function can be placed in the DLL or
It is placed in the module segment of the application.
We recommend that you use the global hook function only during debugging. The global hook function reduces system efficiency and
Conflicts with other applications that use this type of hook.
The VB declaration and parameter explanation of setwindowshookex function:
Public declare function setwindowshookex lib "USER32" alias "setwindowshookexa"
(Byval idhook as long, byval lpfn as long, byval hmod as long, byval dwthreadid
As long) as long
Description of setmediawhookex function parameters:
Idhook: Specifies the hook type (14 types of hooks mentioned above)
Lpfn: the address of the hook processing process. This is a callback fucnction (that is,
When a hook is attached, we need to define a function as a function.
To process its function. Because this parameter is the address of a function
Put the hook function in. Bas and pass it in as addressof hookfunc
Hmod: indicates the hinstance of. dll. If it is a local Hook, the value can be null (0 can be uploaded in VB ).
If it is a remote Hook, you can use getmodulehandle (". dll name.
Dwthreadid: Specifies the threadid (thread ID) for executing the hook.
(Thread) to do this, then pass 0, while VB local Hook can generally pass app. threadid into threadid
The ID of the thread you want to monitor after installing the hook function. This parameter determines whether the hook is partial.
Is the system scope. If the value is null, the hook will be interpreted as within the system range.
All processes and their threads can be monitored. If you specify a thread ID in your own process,
The hook is a local hook. If the thread ID is the ID of a thread in another process
A hook is a global remote hook. There are two special cases: wh_journalrecord and
Wh_journalplayback always indicates the hook of the local system range.
Because they do not need to be put in a DLL. Wh_sysmsgfilter is always within the system range
. In fact, it is similar to the wh_msgfilter hook. If you set the threadid parameter to 0
They are exactly the same.
Setmediawhookex function return value: If setwindowshookex () is successful, it returns a value,
Represents the handle of the current hook. Otherwise, null is returned. You must save the handle because
You also need it to uninstall the hook.
The VB declaration and parameter explanation of callnexthookex function:
Declare function callnexthookex lib "USER32" alias "callnexthookex" (byval hhook
As long, byval ncode as long, byval wparam as long, lparam as any) as long
The hhook value is the return value of setwindowshookex (). ncode, wparam, and lparam are callback functions.
.
Call the hook function with control in the hook sub-program. After processing the message, if you want to cancel
It must call another API function callnexthookex to pass it to execute
The next hook sub-process referred to by the hook linked list. If this function succeeds
Return value. The type of the returned value depends on the hook type.
◆ Uninstall hook
To uninstall a hook, you only need to use the unhookwindowshookex function to uninstall and create a hook.
.
Function declaration:
Declare function unhookwindowshookex lib "USER32" alias "unhookwindowshookex"
(Byval hhook as long) as long
Parameter description:
Hhook: it is the return value of setwindowshookex (). It tells you to write it down. Pai_^
Hook api is an eternal topic. Without hook, many technologies will be hard to implement and may not be implemented at all. The API mentioned here is a generalized API, which includes dos interruptions, Windows APIs, interrupt services, ifs and NDIS filtering, etc. For example, the familiar real-time translation software is implemented by using the hook textout () or exttextout () functions. Before the operating system uses these two functions to output text, replace the corresponding English with Chinese to achieve real-time translation. The same is true for filtering ifs and NDIS. Before Reading and Writing disks and sending and receiving data, the system will call the callback function provided by a third party to determine whether the operation can be released. Unlike normal hooks, the callback function is allowed by the operating system and installed through interfaces provided by the operating system.
Even if there is no hook, there will be no virus, because whether it is a DOS virus or a Windows virus, the hook system service is used to implement its own functions: the virus in DOS is infected by hook int 21 (file-type virus), and The Boot Sector (BOOT virus) is infected by hook INT 13 ); in Windows, viruses are infected by hook system APIs (including ring0 and ring3), Or ifs (the method used by CIH viruses. Therefore, we can say that "without hook, there will be no colorful Software world today ".
Because it involves patents, intellectual property rights, or trade secrets, Microsoft has never advocated hook its system APIs and provide other filtering interfaces such as IFs and NDIS, it is only available to meet the needs of anti-virus software and firewall. Therefore, in most cases, the hook api depends on its own strength.
The hook api has a principle that the original functions of the hooked API cannot be affected. It is like a doctor saving lives. If the virus in the patient's body is killed and the patient is dead, it makes no sense to save lives. If you hook the API, your goal is achieved, but the original function of the API is invalid, this is not the hook, but the replace, the normal function of the operating system will be affected, even crashes.
The hook api technology is not complex, that is, the technology that changes the program process. In CPU commands, there are several commands that can change the process of the program: JMP, call, Int, RET, retf, iret and other commands. Theoretically, you can hook any machine code that changes the API entry and exit, but the actual implementation is much more complicated because the following problems must be handled:
1. CPU instruction length. In a 32-bit system, the length of a JMP/call instruction is 5 bytes, therefore, you only need to replace the machine code with more than five bytes in the API (or replace the five-byte instruction ), otherwise, several commands after the changed machine code smaller than 5 bytes will be affected, and even program processes will be disrupted, resulting in unpredictable consequences;
2. parameter problems: to access the parameters of the original API, you must use EBP or ESP to reference the parameters. Therefore, you must be very clear about the value of EBP/ESP in your hook code;
3. timing: some hooks must start with the API, and some must end with the API, such as hook createfilaa (). If you hook the API at the end of the API, at this time, you can't write files, or even access files; hook Recv (). If you hook the file in the API header and haven't received the data, you can view Recv () of course, there is no data you want in the receiving buffer. After Recv () is executed normally, hook it at the end of Recv () and check the buffer zone of Recv, only the desired data is available;
4. context problems. Some hook codes cannot perform certain operations. Otherwise, the context of the original API is damaged and the original API becomes invalid;
5. For synchronization issues, use local variables instead of global variables in the hook code, which is also required by modular programs;
6. Note that the original functions of the replaced CPU commands must be simulated somewhere in the hook code.