About hook and screen word Extraction

Source: Internet
Author: User

[Address Space]

In Win9x, the virtual address space of 2 GB to 4 GB is actually shared by all Win32 processes, the address space contains the shared Win32 DLL, memory ing file and VxD, Memory Manager, and file system code. In Win9x, this part is visible to every process, this is why the Win9x operating system is not robust enough.
In Win9x, the address space between 0 and 4 MB is reserved for the 16-bit operating system, and between 4 MB and 2 GB is the private address space of the Win32 process, because the address space of each process is relatively independent, that is to say, if the program wants to intercept API calls in other processes, it must break the process boundary wall, inject the code that intercepts API calls to other processes. This task is completed by the hook function (setwindowshookex.

 

[System hook]

All system hook functions must be in the dynamic library. In this way, when a process implicitly or explicitly calls a function in the dynamic library, the system maps the dynamic library to the virtual address space of the process, which makes the DLL a part of the process and runs it as the process, using the stack of the process, that is to say, the code in the dynamic link library is injected by the hook function into the address space of other GUI processes (non-Gui processes, the hook function is powerless). When the DLL containing the hook is injected into other processes, you can obtain the base address of each module (exe and DLL) mapped to the virtual memory of the process, for example:

Hmodule hmodule=getmodulehandle(“mypro.exe ");

In the MFC program, we can use the AfxGetInstanceHandle () function to obtain the base address of the module. The location where EXE and DLL are mapped to the virtual memory space is determined by their base address. Their base addresses are determined by the linker during the link. When you create a Win32 project, the VC ++ linker uses the default base address 0x00400000. You can use the base option of the linker to change the base address of the module. EXE is usually mapped to 0x00400000 of the virtual memory, and the DLL also has different base addresses, which are usually mapped to the same virtual address space of different processes.

The system maps the EXE and DLL to the virtual memory. Their memory structure is the same as the static file structure on the disk. That is, the format of the PE (portable executable) file. After obtaining the base address of the process module, we can enumerate the image_import_descriptor array of the module according to the PE file format, check whether the dynamic link library of the function to be intercepted is introduced in the process space. For example, to intercept "textouta", you must check whether "gdi32.dll" is introduced.

 

[PE file format]

The general structure of the PE file format is the file header. We don't have to worry about it. Starting from the end of the PE file optional Header, It is the description of each segment in the file, indicating that the subsequent part is the real segment data, in fact, we only care about one segment, that is, ". idata section, which contains all the information about the introduced functions and the RVA (relative virtual address) Address of IAT (import address table.

Speaking of this, the whole process of Intercepting Windows APIS is very clear. In fact, all processes always call a given API function by transferring a place in the PE file. This is the ". the IAT input address table in the idata section ). There are the function names and addresses of all other DLL called by this module. Function calls to other DLL actually jump to the input address table, and then to the real function entry of DLL from the input address table.

Specifically, we will access ". the DLL information introduced in the idata section, and then the image_thunk_data array is used to access the information of each function introduced in the DLL for the introduced DLL, find the jump address of the function we want to intercept, and change it to the address of our own function ...... The specific practices will be explained in detail in the key code below.

 

[Screen words]

After talking about so many principles, let's go back to the topic "word acquisition with the mouse screen. In addition to the interception of API functions, we also need to do some other work to implement the "Mouse screen to take words" function, simply put, A complete word extraction process can be summarized into the following steps:

1. Install the mouse hook and use the hook function to obtain the mouse message.

Used API function: setwindowshookex

2. Get the current position of the mouse, and send a re-draw message to the window under the mouse so that it can call the system function to re-draw the window.

Used API functions: windowfrompoint, screentoclient, invalidaterect

3. Intercept calls to system functions and obtain parameters, that is, the words we want to take.

For most Windows applications, to take words, we need to intercept the "textouta" function in "gdi32.dll.

We first write a mytextouta function like the textouta function, for example:

Bool winapi mytextouta (HDC, int nxstart, int nystart, lpcstr lpszstring, int cbstring)
{
// Output lpszstring here
// Then call the genuine textouta Function
}

Place this function in the dynamic connection library where the hook is installed, and then call the hookimportfunction function provided at the end to intercept the process's call to the textouta function and jump to our mytextouta function, capture the output string.

Hookimportfunction usage:

Hookfuncdesc HD;
Proc porigfuns;
HD. szfunc = "textouta ";
HD. pproc = (Proc) mytextouta;
Hookimportfunction (AfxGetInstanceHandle (), "gdi32.dll", & HD, porigfuns );

The source code of hookimportfunction is provided below:
//////////////////////////////////////// //// Begin ////////////////////////////////// /////////////////////////////
# Include <crtdbg. h>

// A macro that generates pointers is defined here.
# Define makeptr (cast, PTR, addvalue) (CAST) (DWORD) (PTR) + (DWORD) (addvalue ))

// Defines the hookfuncdesc structure. We use this structure as the parameter to pass it to the hookimportfunction function.
Typedef struct tag_hookfuncdesc
{
Lpcstr szfunc; // The Name Of The function to hook.
Proc pproc; // The procedure to blast in.
} Hookfuncdesc, * lphookfuncdesc;

// This function is used to monitor whether the current system is called the "checking" function.
Bool isnt ();

// This function gets the hmodule-that is, the import descriptor of the DLL module of the function to be intercepted (import descriptor)
Pimage_import_descriptor getnamedimportdescriptor (hmodule, lpcstr szimportmodule );

// Our main function
Bool hookimportfunction (hmodule, lpcstr szimportmodule,
Lphookfuncdesc pahookfunc, Proc * paorigfuncs)
{
//// // The code below checks the validity of parameters ////////// //////////////////
_ Assert (szimportmodule );
_ Assert (! Isbadreadptr (pahookfunc, sizeof (hookfuncdesc )));
# Ifdef _ debug
If (paorigfuncs) _ assert (! Isbadwriteptr (paorigfuncs, sizeof (Proc )));
_ Assert (pahookfunc. szfunc );
_ Assert (* pahookfunc. szfunc! = '/0 ');
_ Assert (! Isbadcodeptr (pahookfunc. pproc ));
# Endif
If (szimportmodule = NULL) | (isbadreadptr (pahookfunc, sizeof (hookfuncdesc ))))
{
_ Assert (false );
Setlasterrorex (error_invalid_parameter, sle_error );
Return false;
}
//////////////////////////////////////// //////////////////////////////////////

// Monitor whether the current module is on 2 GB virtual memory
// The address memory is shared by Win32 processes.
If (! Isnt () & (DWORD) hmodule> = 0x80000000 ))
{
_ Assert (false );
Setlasterrorex (error_invalid_handle, sle_error );
Return false;
}
// Clear
If (paorigfuncs) memset (paorigfuncs, null, sizeof (Proc ));

// Call the getnamedimportdescriptor () function to obtain the hmodule.
// Import descriptor of the DLL module where the intercepted function is located)
Pimage_import_descriptor pimportdesc = getnamedimportdescriptor (hmodule, szimportmodule );
If (pimportdesc = NULL)
Return false; // if it is null, the module is not introduced by the current process.

// Obtain the original thunk information from the DLL module, because the original information in the pimportdesc-> firstthunk array has
// All the introduced information is overwritten when the application introduces the DLL. Therefore, we need to obtain the pimportdesc-> originalfirstthunk
// Pointer to access information such as the introduced function name
Pimage_thunk_data porigthunk = makeptr (pimage_thunk_data, hmodule,
Pimportdesc-> originalfirstthunk );

// Obtain the pointer to the image_thunk_data array from pimportdesc-> firstthunk, because it is filled when the DLL is introduced.
// All the introduced information, so the actual interception is actually carried out here
Pimage_thunk_data prealthunk = makeptr (pimage_thunk_data, hmodule, pimportdesc-> firstthunk );

// Use the image_thunk_data array to find the function to be intercepted. This is the most important part!
While (porigthunk-> u1.function)
{
// Only search for the functions introduced by the function name rather than the serial number.
If (image_ordinal_flag! = (Porigthunk-> u1.ordinal & image_ordinal_flag ))
{
// Obtain the name of the function to be introduced.
Pimage_import_by_name pbyname = makeptr (pimage_import_by_name, hmodule,
Porigthunk-> u1.addressofdata );

// If the function name starts with null, skip and continue the next Function
If ('/0' = pbyname-> name [0])
Continue;

// Bdohook is used to check whether interception is successful
Bool bdohook = false;

// Check whether the current function is the function we need to intercept
If (pahookfunc. szfunc [0] = pbyname-> name [0]) &
(Strcmpi (pahookfunc. szfunc, (char *) pbyname-> name) = 0 ))
{
// Found!
If (pahookfunc. pproc)
Bdohook = true;
}
If (bdohook)
{
// We have found the function to be intercepted, so let's get started.
// The first thing we need to do is change the memory protection status of this virtual memory so that we can freely access it.
Memory_basic_information mbi_thunk;
Virtualquery (prealthunk, & mbi_thunk, sizeof (memory_basic_information ));
_ Assert (virtualprotect (mbi_thunk.baseaddress, mbi_thunk.regionsize,
Page_readwrite, & mbi_thunk.protect ));

// Save the correct jump address of the function we want to intercept
If (paorigfuncs)
Paorigfuncs = (Proc) prealthunk-> u1.function;

// Rewrite the function jump address in the image_thunk_data array to our own function address!
// In the future, all calls made by all processes to this system function will become calls to our own function.
Prealthunk-> u1.function = (pdword) pahookfunc. pproc;

// Operation completed! Change this virtual memory back to the original protection status
DWORD dwoldprotect;
_ Assert (virtualprotect (mbi_thunk.baseaddress, mbi_thunk.regionsize,
Mbi_thunk.protect, & dwoldprotect ));
Setlasterror (error_success );
Return true;
}
}
// Access the next element in the image_thunk_data Array
Porigthunk ++;
Prealthunk ++;
}
Return true;
}

// Implement the getnamedimportdescriptor Function
Pimage_import_descriptor getnamedimportdescriptor (hmodule, lpcstr szimportmodule)
{
// Check parameters
_ Assert (szimportmodule );
_ Assert (hmodule );
If (szimportmodule = NULL) | (hmodule = NULL ))
{
_ Assert (false );
Setlasterrorex (error_invalid_parameter, sle_error );
Return NULL;
}

// Obtain the DOS file header
Pimage_dos_header pdosheader = (pimage_dos_header) hmodule;

// Check whether the MZ file header is used
If (isbadreadptr (pdosheader, sizeof (image_dos_header) |
(Pdosheader-> e_magic! = Image_dos_signature ))
{
_ Assert (false );
Setlasterrorex (error_invalid_parameter, sle_error );
Return NULL;
}

// Obtain the PE File Header
Pimage_nt_headers pntheader = makeptr (pimage_nt_headers, pdosheader, pdosheader-> e_lfanew );

// Check whether the PE image file is used
If (isbadreadptr (pntheader, sizeof (image_nt_headers) |
(Pntheader-> signature! = Image_nt_signature ))
{
_ Assert (false );
Setlasterrorex (error_invalid_parameter, sle_error );
Return NULL;
}

// Check the import section of the PE file (that is,. idata Section)
If (pntheader-> optionalheader. datadirectory [image_directory_entry_import]. virtualaddress = 0)
Return NULL;

// Obtain the pointer of the introduced section (. idata section ).
Pimage_import_descriptor pimportdesc = makeptr (pimage_import_descriptor, pdosheader,
Pntheader-> optionalheader. datadirectory [image_directory_entry_import]. virtualaddress );

// Use the pimage_import_descriptor array to find the module where the function to be intercepted is located.
While (pimportdesc-> name)
{
Pstr szcurrmod = makeptr (pstr, pdosheader, pimportdesc-> name );
If (stricmp (szcurrmod, szimportmodule) = 0)
Break; // find it! Interrupt Loop
// The next element
Pimportdesc ++;
}

// If not found, the module we are looking for has not been introduced by the current process!
If (pimportdesc-> name = NULL)
Return NULL;

// Return the module Descriptor (import descriptor) found by the function)
Return pimportdesc;
}

// Implementation of the isnt () function
Bool isnt ()
{
Osversioninfo stosvi;
Memset (& stosvi, null, sizeof (osversioninfo ));
Stosvi. dwosversioninfosize = sizeof (osversioninfo );
Bool Bret = getversionex (& stosvi );
_ Assert (true = BRET );
If (false = BRET) return false;
Return (ver_platform_win32_nt = stosvi. dwplatformid );
}
//////////////////////////////////////// /// // End //////////////////////////////// //////////////////////////////////////

 

 

 

 

 

 

 

 

 

 

 

 

 

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.