My hook Study Notes

Source: Internet
Author: User

About hook
 
I. Basic concepts:

Hook is a platform for message processing in windows. Applications can set sub-processes on the platform to monitor messages in a specified form, the monitored form can be created by other processes. When a message arrives, process it before the target form processing function. The hook mechanism allows the application to intercept and process window messages or specific events.

A hook is actually a program segment for message processing. It is called by the system and mounted to the system. When a specific message is sent, the hook program first captures the message before it reaches the target form, that is, the hook function obtains control of the message first. In this case, the hook function can process (Change) the message, continue to transmit the message without processing it, and forcibly end the message transmission.

Ii. execution mechanism:

1. Hook linked list and hook sub-process:

Each Hook has an associated pointer list, called a hook linked list, which is maintained by the system. The pointer to this list points to the specified callback function defined by the application and called by the hook sub-process, that is, each processing sub-process of the hook. When a message associated with the specified hook type occurs, the system passes the message to the hook sub-process. Some hook sub-processes can only monitor messages, modify messages, or stop message advances, so that these messages are not transmitted to the next hook sub-process or target form. Recently installed hooks are placed at the beginning of the chain, while the earliest installed hooks are placed at the end, that is, the later ones are added to gain control.

Windows does not require that the order in which the hook program is detached must be different from that in the installation sequence. Every time a hook is detached, Windows releases the memory it occupies and updates the entire hook linked list. Assume that the program has installed a hook, but it has ended before the hook has been uninstalled, the system will take the initiative to uninstall the hook for it.

A hook is a callback function defined by an application. It cannot be defined as a member function of a class, but can only be defined as a common C function. It is used to monitor the system or a specific type of events. These events can be associated with a specific thread or all threads in the system.

The hook procedure must follow the following syntax:
Lresult callback hookproc
(
Int ncode,
Wparam,
Lparam
);
Hookproc is the name defined by the application.

The number of ncode workers is the hook code, which is used by the hook sub-process to determine the task. The value of the number of hooks depends on the hook type. Each Hook has its own hook code feature character set.
The values of wparam and lparam counts depend on the hook code, but their typical values include information about sending or receiving messages.

2. Hook installation and release:

Use the API function setwindowshookex () to install the hook Program defined by an application to the hook list. The setwindowshookex function always installs the hook sub-program at the beginning of the hook chain. When a specified hook monitoring event occurs, the system calls the hook child program starting with the hook chain associated with the hook. The hook sub-process in each hook chain determines whether to pass the event to the next hook sub-process. The callnexthookex function must be called to transfer an event to the next hook sub-process.

Hhook setwindowshookex (
Int idhook, // hook type, that is, the type of the message it processes
Hookproc lpfn, // address pointer of the hook sub-program. Assume that the number of threads for dwthreadid is 0.
// Or the ID of a thread created by another process,
// The lpfn must point to the hook program in the DLL.
// In addition, The lpfn can point to a hook sub-program code of the current process.
// Hook function entry address. This function is called when the hook hooks messages.
Hinstance hmod, // handle of the application instance. Identifies the DLL that contains the Child Program referred to by lpfn.
// Assume that dwthreadid identifies a thread created by the current process,
// And the Child Code is in the current process. hmod must be null.
// It is very easy to set the instance handle of the application.
DWORD dwthreadid // The identifier of the Thread associated with the installed hook program.
// If the value is 0, the hook sub-program is associated with all threads, that is, the global hook.
);
If the function succeeds, the handle of the hook sub-program is returned. If the function fails, null is returned.

The hook sub-program is associated with the thread, which means that messages sent to the thread in a hook linked list are sent to the hook sub-program at the same time and processed by the hook sub-program first.

After the hook sub-program finishes processing the message, if you want to transfer the message, it must call the API function callnexthookex in another SDK to pass it, to run the next hook program referred to by the hook linked list. When this function succeeds, the return value of the next hook process in the hook chain is returned. The type of the returned value depends on the hook type. The prototype of this function is as follows:

Lresult callnexthookex
(
Hhook HHK;
Int ncode;
Wparam;
Lparam;
);

HHK is the handle of the current hook, Which is returned by the setwindowshookex () function.
Ncode is the event Code passed to the hook process.
Wparam and lparam are respectively the wparam values passed to the hook sub-program. Their meanings are related to the hook type.

The hook function can also directly return true to discard the message and prevent the message from being transmitted. Otherwise, other apps installed with hooks will not receive hook notifications and may produce incorrect results.

After using the hook, you must use unhookwindowshookex () to uninstall the hook. Otherwise, it may cause trouble. Release hooks is easier than release. unhookwindowshookex () only has one worker. The function prototype is as follows:

Unhookwindowshookex
(
Hhook HHK;
);
If the function is successful, true is returned. Otherwise, false is returned.

3. Some execution mechanisms:

In the Win16 environment, the global data of DLL is the same for every process that loads it. In the Win32 environment, the situation has changed, all the objects (including variables) created by the code in the DLL function are called by the thread or process. When a process loads a DLL, the operating system automatically maps the DLL address to the private space of the process, that is, the virtual address space of the process, also, copy the global data of the DLL to the process space. That is to say, the global data of the same DLL owned by each process has the same name, but its values are not necessarily the same, and they do not interfere with each other.
 
Therefore, to share data among multiple processes in a Win32 environment, you must make necessary settings. When the hacker asks the process of the same DLL, the shared memory is implemented through the memory ing file technology. You can also separate the data to be shared, place it in an independent data segment, and set the attribute of the segment to share. These variables must be assigned with initial values. Otherwise, the compiler will place the variables without initial values in a data segment called uninitialized.

# The Pragma data_seg preprocessing command is used to set the shared data segment. For example:
# Pragma data_seg ("shareddataname ")
Hhook = NULL;
# Pragma data_seg ()
All the variables between # pragma data_seg ("shareddataname") and # pragma data_seg () will be seen and shared by all the processes that the producer asks about the DLL.

When a process implicitly or explicitly calls a function in a dynamic library, the system maps the dynamic library to the virtual address space of the process (hereinafter referred to as "address space "). This makes the DLL part of a process and runs as the process and uses the stack of the process.

4. System hooks and thread hooks:

The last number of hooks in the setwindowshookex () function determines whether the hook is a system hook or a thread hook.

The thread hook is used to monitor the event messages of a specified thread. The thread hooks are generally within the current thread or the thread derived from the current thread.

The system starts to monitor the event messages of all threads in the system. Since system hooks affect all applications in the system, hooks must be placed in an independent dynamic link library (DLL. The system automatically maps the DLL including the "hook callback function" to the address space of all processes affected by the hook function, which injects the DLL into those processes.

Notes:
(1) If a thread hook and a system hook are installed for the same event (such as a mouse message), the system automatically calls the thread hook and then calls the system hook.

(2) Multiple hooks can be installed for the same event message. These hooks form a hook chain. After the current hook processing is complete, the hook information should be passed to the next hook function.

(3) hooks, especially system hooks, consume message processing time and reduce system performance. Install the hooks only when necessary. Uninstall the hooks immediately after use.

Iii. Hook type

Each type of hook enables applications to monitor different types of system message processing mechanisms. The following describes all hook types that can be used.

1. wh_callwndproc and wh_callwndprocret hooks

Wh_callwndproc and wh_callwndprocret hooks enable you to monitor messages sent to the form process. The system calls the wh_callwndproc hook sub-process before the message is sent to the receiving form process, and calls the wh_callwndprocret hook sub-process after the message is processed in the form process.

The wh_callwndprocret hook transmits the pointer to the cwpretstruct structure, and then passes the pointer to the hook sub-program. The cwpretstruct structure includes the returned values from the form process for processing the message, and also includes the number of messages associated with the message.

2. wh_cbt hook

Before the following events, the system will call the wh_cbt hook sub-process. These events include:
1. Form 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-program determines whether the system agrees or prevents one of these operations.

3. wh_debug hook

Before the system calls the hook child program associated with other hooks, the system calls the wh_debug hook Child Program. You can use this hook to decide whether to agree to the System Call of the hook child program associated with other hooks.

4. wh_foregroundidle hook

When the foreground thread of the application is in the idle state, the wh_foregroundidle Hook can be used to run low-priority tasks. When the foreground thread of the application is almost overwhelmed, the system will call the wh_foregroundidle hook sub-thread.

5. wh_getmessage hook

The application uses the wh_getmessage hook to monitor messages returned from the getmessage or peekmessage function. 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. You can use this hook to play back consecutive mouse and keyboard events recorded by using the wh_journalrecord hook. Only when the wh_journalplayback Hook has been installed, normal mouse and keyboard events are invalid. The wh_journalplayback hook is a global hook and cannot be used as a thread-specific hook. Wh_journalplayback hook returns a timeout value, which indicates how long (in milliseconds) the system will wait before processing the current message from the playback hook ). This enables the hook to control the playback of real-time events. Wh_journalplayback is system-wide local hooks, which cannot be injected into whatever travel address is empty.

7. wh_journalrecord hook

The wh_journalrecord hook is used to monitor and record input events. Typically, you can use this hook to record consecutive mouse and keyboard events, and then use the wh_journalplayback hook to play back the events. The wh_journalrecord hook is a global hook and cannot be used as a thread-specific hook. Wh_journalrecord is system-wide local hooks, which cannot be injected into whatever travel address is empty.

8. wh_keyboard hook

In the application, wh_keyboard hook is used to monitor wm_keydown and wm_keyup messages, which are returned through getmessage or peekmessage function. You can use this hook to monitor 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 enable us to monitor menus, scroll bar, message box, and dialog box messages. In addition, we find that you can use Alt + TAB or Alt + ESC to switch the form. The wh_msgfilter Hook can only monitor messages transmitted to menus, scroll bars, message boxes, and messages transmitted to the dialog box created by the app with the hook child program installed. Wh_sysmsgfilter hook monitors all application messages.

Wh_msgfilter and wh_sysmsgfilter hooks allow us to filter messages during the pattern loop, which is equivalent to filtering messages in the primary message loop.

Call the callmsgfilter function to directly call the wh_msgfilter hook. By using this function, the application can use the same code to filter messages during the pattern loop, as in the main message loop.

13. wh_shell hook

Shell applications can use the wh_shell hook to receive important notifications. When the shell application is activated and the top-level form is created or destroyed, the system calls the wh_shell hook sub-process.
Wh_shell has 5 favorites:
1. Only top-level and unowned forms must be generated, used, 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 changes;
5. When the user presses Ctrl + ESC to run the Task Manager (or programs of the same level ).

By convention, shell applications do not receive wh_shell messages. Therefore, before the application can receive the wh_shell message, the application must call systemparametersinfo function to notify itself.

Rivershan was originally created in September 18, 2002

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.