PIMAGE_DOS_HEADER dosHeader; PIMAGE_NT_HEADERS pNTHeader; Pimage_import_descriptor importdesc; Pimage_import_by_name p_ibn; DWORD importsstartrva; Pword pd_iat, pd_into; Int count, index; Char * dll_name = NULL; Char * pc_dlltar = "kernel32.dll "; Char * pc_fnctar = "getprocaddress "; PMDL p_mdl; PDWORD MappedImTable; // Import the PVOID ImageBase variable in the IMAGE_INFO structure. DosHeader = (PIMAGE_DOS_HEADER) image_addr; // Macro, pointer operation PNTHeader = MakePtr (PIMAGE_NT_HEADERS, dosHeader, dosHeader-> e_lfanew ); // Identify whether the file is a standard PE file by using the Signature field of the PE File If (pNTHeader-> Signature! = IMAGE_NT_SIGNATURE) Return STATUS_INVALID_IMAGE_FORMAT; // RVA of the import segment ImportsStartRVA = pNTHeader-> OptionalHeader. DataDirectory [IMAGE_DIRECTORY_ENTRY_IMPORT]. VirtualAddress; If (! ImportsStartRVA) Return STATUS_INVALID_IMAGE_FORMAT; // Add the RVA of the import segment and the starting address (dosHeader) of the module in the memory. // Pointer to the first IMAGE_IMPORT_DESCRIPTOR ImportDesc = (PIMAGE_IMPORT_DESCRIPTOR) (importsStartRVA + (DWORD) dosHeader ); // Filter each image_import_descriptor For (COUNT = 0; importdesc [count]. characteristics! = 0; count ++) { // Obtain the DLL name of the import module. Dll_name = (char *) (importdesc [count]. Name + (DWORD) dosheader ); // Obtain IAT Pd_iat = (pdword) (DWORD) dosheader) + (DWORD) importdesc [count]. firstthunk ); // Obtain the pointer array pointing to the image_import_by_name Structure Pd_INTO = (PDWORD) (DWORD) dosHeader) + (DWORD) importDesc [count]. OriginalFirstThunk ); // Filter in IAT to find the specific dll and function to be hooked For (index = 0; pd_IAT [index]! = 0; index ++) { // If this is an import by ordinal // The high bit is set If (pd_INTO [index] & IMAGE_ORDINAL_FLAG )! = IMAGE_ORDINAL_FLAG) { // Obtain the function name Structure P_ibn = (pimage_import_by_name) (pd_into [Index] + (DWORD) dosheader )); // Compare the DLL name and function name to find the required If (_ stricmp (dll_name, pc_dlltar) = 0) & (strcmp (p_ibn-> Name, pc_fnctar) = 0 )) { // Use the trick you already learned to map a different // Virtual address to the same physical page so no permission problems // // Map the memory into our domain so we can change // Permissions on the MDL // Modify the Memory attribute to modify the IAT attribute // Modify memory attributes using the MDL method. This will be detailed in future articles. P_mdl = mmcreatemdl (null, & pd_iat [Index], 4 ); If (! P_mdl) Return status_unsuccessful; Mmbuildmdlfornonpagedpool (p_mdl ); // Change the flags of MDL P_mdl-> mdlflags = p_mdl-> mdlflags | mdl_mapped_to_system_va; MappedImTable = MmMapLocakedPages (p_mdl, KernelMode ); // Address of the "new function" // Point "GetProcAddress" to a defined function * MappedImTable = d_shareM; // Free MDL Mmunmaploackedpages (mappedimtable, p_mdl ); IoFreeMdl (p_mdl ); } } } Return STATUS_SUCCESS; } |