c++ - 导出函数转发给自己?

标签 c++ windows portable-executable

今天我在解析 Windows 可移植可执行文件结构时遇到了一个非常奇怪的问题。具体在导出表中。

在尝试解析 DLL 中导出函数的函数地址时,我发现自己遇到了堆栈溢出问题(因此这似乎是最合适的 QA 板)。

我编写了自己的 GetProcAddress 版本,它手动进行解析,而不是调用现有的 GetProcAddress 方法。请不要只告诉我使用现有的 GetProcAddress 方法,它不适合我目前的情况,我想从中学到一些东西。

对于我遇到的大多数情况,我的版本都运行良好并且没有遇到任何问题。然而,该函数已针对名为 API-MS-Win-Core-ProcessThreads-L1-1-0.dll 的 DLL 进行了测试(作为 Kernel32.dll 的递归解析的一部分>),这就是 StackOverflow 发生的时间。

我已将其缩小为从 API-MS-Win-Core-ProcessThreads-L1-1-0.dll 导出的以下函数:

CreateRemoteThreadEx

现在,这个导出函数实际上是一个转发导出。通常这不用担心;我已经编写了我的函数,以便它应该处理转发的导出。然而这个功能被转发给

api-ms-win-core-processthreads-l1-1-0.CreateRemoteThreadEx

有人看到这里的问题吗?单步执行代码,然后我的 GetProcAddress 函数调用 api-ms-win-core-processthreads-l1-1-0 上的 LoadLibrary,然后尝试递归查找 CreateRemoteThreadEx。然而,在下一次迭代中,CreateRemoteThreadEx 函数再次转发...到

api-ms-win-core-processthreads-l1-1-0.CreateRemoteThreadEx

StackOverflow 就这样开始了。经过更多调查后,我发现调用的结果

LoadLibraryA("api-ms-win-core-processthreads-l1-1-0");

返回与

相同的结果
LoadLibraryA("kernel32.dll");

我很难过。

这是我当前的代码:

#include <Windows.h>

#define MKPTR(p1,p2) ((DWORD_PTR)(p1) + (DWORD_PTR)(p2))

INT LookupExport(IMAGE_DOS_HEADER* pDosHd, DWORD* pNames, DWORD nNames, LPCSTR lpProcName)
{
    // Do a binary search on the name pointer table
    INT start = 0, 
        index = -1,
        middle = -1, 
        end = nNames - 1,
        cmp = 0;

    CHAR *pName;

    while (start <= end && index == -1)
    {
        middle = (start + end) >> 1;
        pName = (CHAR*)MKPTR(pDosHd, pNames[middle]);

        if ((cmp = strcmp(pName, lpProcName)) == 0)
            index = middle; // found
        else if (cmp < 0)
            start = middle + 1;
        else
            end = middle;
    }

    return index;
}

FARPROC InternalGetProcAddress(HMODULE hModule, LPCSTR lpProcName)
{
    BOOL ordinalSearch = HIWORD(lpProcName) == 0;
    WORD ordinal = 0;
    IMAGE_DOS_HEADER *pDosHd = (IMAGE_DOS_HEADER*)hModule;

    if (pDosHd->e_magic != IMAGE_DOS_SIGNATURE)
        return NULL;

    IMAGE_NT_HEADERS *pNtHd = (IMAGE_NT_HEADERS*)MKPTR(pDosHd, pDosHd->e_lfanew);
    if (pNtHd->Signature != IMAGE_NT_SIGNATURE)
        return NULL;

    IMAGE_DATA_DIRECTORY directory = pNtHd->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
    if (directory.Size == 0 || directory.VirtualAddress == 0)
        return NULL;

    IMAGE_EXPORT_DIRECTORY *pExports = (IMAGE_EXPORT_DIRECTORY*)MKPTR(pDosHd, directory.VirtualAddress);
    if (!ordinalSearch)
    {
        INT index = LookupExport(pDosHd, (DWORD*)MKPTR(pDosHd, pExports->AddressOfNames), pExports->NumberOfNames, lpProcName);
        if (index == -1)
            return NULL;
        ordinal = ((WORD*)MKPTR(pDosHd, pExports->AddressOfNameOrdinals))[index];
    }
    else
    {
        ordinal = LOWORD(lpProcName);
    }

    INT delta = pExports->Base - 1;
    DWORD dwAddress = ((DWORD*)MKPTR(pDosHd, pExports->AddressOfFunctions))[ordinal - delta];
    // Check whether forwarded:
    if (dwAddress >= directory.VirtualAddress && dwAddress < (directory.VirtualAddress + directory.Size))
    {
        CHAR pForward[256];
        strcpy(pForward, (CHAR*)MKPTR(pDosHd, dwAddress));
        CHAR *pFunction = strchr(pForward, '.');
        if (pFunction == NULL)
            return NULL;

        // break into seperate parts and recurse
        *pFunction++ = 0;
        return InternalGetProcAddress(LoadLibraryA(pForward), pFunction);
    }

    return (FARPROC)MKPTR(hModule, dwAddress);
}

如有任何见解,我们将不胜感激。

最佳答案

好吧,在听从@sergmat 的建议后,我查看了 API 集文档(感兴趣的人可以找到 here)。我现在修改了我的 GetProcAddress 代码以对 Api Set 表进行简单的查找。

#include <Windows.h>

#define MKPTR(p1,p2) ((DWORD_PTR)(p1) + (DWORD_PTR)(p2))

typedef struct _stripped_peb32 {
    BYTE    unused1[0x038];
    PVOID   ApiSet;
    BYTE    unused2[0x1AC];
} PEB32;

typedef struct _stripped_peb64 {
    BYTE    unused1[0x068];
    PVOID   ApiSet;
    BYTE    unused2[0x23C];
} PEB64;

typedef struct _PROCESS_BASIC_INFORMATION {
    PVOID       Reserved1;
    LPVOID      PebBaseAddress;
    PVOID       Reserved2[2];
    ULONG_PTR   UniqueProcessId;
    PVOID       Reserved3;
} PROCESS_BASIC_INFORMATION;

typedef struct _api_set_host {
    DWORD           ImportModuleName;
    WORD            ImportModuleNameLength;
    DWORD           HostModuleName;
    WORD            HostModuleNameLength;
} API_SET_HOST;

typedef struct _api_set_host_descriptor {
    DWORD           NumberOfHosts;
    API_SET_HOST    Hosts[1];
} API_SET_HOST_DESCRIPTOR;

typedef struct _api_set_entry {
    DWORD           Name;
    WORD            NameLength;
    DWORD           HostDescriptor;
} API_SET_ENTRY;

typedef struct _api_set_header {
    DWORD           unknown1;
    DWORD           NumberOfEntries;
    API_SET_ENTRY   Entries[1];
} API_SET_HEADER;

typedef NTSTATUS (__stdcall *fnNtQueryInformationProcess)(HANDLE ProcessHandle, DWORD ProcessInformationClass, PVOID ProcessInformation, ULONG ProcessInformationLength, PULONG ReturnLength);

API_SET_HEADER *GetApiSetHeader()
{
    fnNtQueryInformationProcess NtQueryInformationProcess = (fnNtQueryInformationProcess)GetProcAddress(LoadLibraryW(L"ntdll.dll"), "NtQueryInformationProcess");
    if (!NtQueryInformationProcess)
        return NULL;

    PROCESS_BASIC_INFORMATION info;
    if (NtQueryInformationProcess(GetCurrentProcess(), 0, &info, sizeof(info), NULL) != S_OK)
        return NULL;

#if defined(_WIN32)
    return (API_SET_HEADER*)(((PEB32*)info.PebBaseAddress)->ApiSet);
#elif defined(_WIN64)
    return (API_SET_HEADER*)(((PEB64*)info.PebBaseAddress)->ApiSet);
#else
    return NULL; // unsupported architecture
#endif
}

HMODULE ResolveImportMap(LPCSTR lpModuleName)
{
    API_SET_HEADER *pHeader = GetApiSetHeader();
    if (pHeader == NULL)
        return NULL;
    API_SET_ENTRY *pEntry = pHeader->Entries;
    API_SET_HOST_DESCRIPTOR* pDescriptor;
    wchar_t module[128];

    // First, normalize the LPCSTR, the API Set table doesn't have the API- prefix
    if (strnicmp("api-", lpModuleName, 4) == 0)
        lpModuleName += 4;

    // Next convert the LPCSTR to a unicode string for comparison and remove the extension (if found)
    mbstowcs(module, lpModuleName, sizeof(module) / sizeof(wchar_t));
    wchar_t *dot = wcsrchr(module, L'.');
    if (dot) *dot = L'\0';

    // Begin the lookup:
    // todo: implement a case-insensitive binary search, not much to be gained for the effort IMO as there's
    //          only 35 entries in the current version of Windows 7, but the option is there for performance nuts.
    for(unsigned long i = 0; i < pHeader->NumberOfEntries; ++i, ++pEntry)
    {
        // Check the top-level host map
        if (wcsnicmp(module, (const wchar_t*)MKPTR(pHeader, pEntry->Name), pEntry->NameLength) == 0)
        {
            pDescriptor = (API_SET_HOST_DESCRIPTOR*)MKPTR(pHeader, pEntry->HostDescriptor);
            // iterate backwards through the hosts to find the most important one (I think this is naive)
            for(unsigned long j = pDescriptor->NumberOfHosts; j > 0; --j)
            {
                if (pDescriptor->Hosts[j - 1].HostModuleNameLength)
                {
                    memcpy(module, (const void*)MKPTR(pHeader, pDescriptor->Hosts[j - 1].HostModuleName), pDescriptor->Hosts[j - 1].HostModuleNameLength);
                    module[pDescriptor->Hosts[j - 1].HostModuleNameLength / sizeof(wchar_t)] = L'\0';
                    return GetModuleHandleW(module); // All the modules should already be loaded, so use GetModuleHandle rather than LoadLibrary
                }
            }
        }
    }

    return NULL;
}

INT LookupExport(IMAGE_DOS_HEADER* pDosHd, DWORD* pNames, DWORD nNames, LPCSTR lpProcName)
{
    // Do a binary search on the name pointer table
    INT start = 0, 
        index = -1,
        middle = -1, 
        end = nNames - 1,
        cmp = 0;

    CHAR *pName;

    while (start <= end && index == -1)
    {
        middle = (start + end) >> 1;
        pName = (CHAR*)MKPTR(pDosHd, pNames[middle]);

        if ((cmp = strcmp(pName, lpProcName)) == 0)
            index = middle; 
        else if (cmp < 0)
            start = middle + 1;
        else
            end = middle;
    }

    return index;
}

FARPROC InternalGetProcAddress(HMODULE hModule, LPCSTR lpProcName)
{
    if (hModule == NULL)
        return NULL;

    BOOL ordinalSearch = HIWORD(lpProcName) == 0;
    WORD ordinal = 0;
    IMAGE_DOS_HEADER *pDosHd = (IMAGE_DOS_HEADER*)hModule;

    if (pDosHd->e_magic != IMAGE_DOS_SIGNATURE)
        return NULL;

    IMAGE_NT_HEADERS *pNtHd = (IMAGE_NT_HEADERS*)MKPTR(pDosHd, pDosHd->e_lfanew);
    if (pNtHd->Signature != IMAGE_NT_SIGNATURE)
        return NULL;

    IMAGE_DATA_DIRECTORY directory = pNtHd->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
    if (directory.Size == 0 || directory.VirtualAddress == 0)
        return NULL;

    IMAGE_EXPORT_DIRECTORY *pExports = (IMAGE_EXPORT_DIRECTORY*)MKPTR(pDosHd, directory.VirtualAddress);
    if (!ordinalSearch)
    {
        INT index = LookupExport(pDosHd, (DWORD*)MKPTR(pDosHd, pExports->AddressOfNames), pExports->NumberOfNames, lpProcName);
        if (index == -1)
            return NULL;
        ordinal = ((WORD*)MKPTR(pDosHd, pExports->AddressOfNameOrdinals))[index];
    }
    else
    {
        ordinal = LOWORD(lpProcName);
    }

    INT ordbase = pExports->Base - 1;
    DWORD dwAddress = ((DWORD*)MKPTR(pDosHd, pExports->AddressOfFunctions))[ordinal - ordbase];
    // Check whether forwarded:
    if (dwAddress >= directory.VirtualAddress && dwAddress < (directory.VirtualAddress + directory.Size))
    {
        CHAR pForward[256];
        strcpy(pForward, (CHAR*)MKPTR(pDosHd, dwAddress));
        CHAR *pFunction = strchr(pForward, '.');
        if (pFunction == NULL)
            return NULL;

        // break into seperate parts and recurse
        *pFunction++ = 0;
        // check if ordinal-forwarded
        if (*pFunction == '#')
            pFunction = (PSTR)(unsigned short)(atoi(++pFunction));

        HMODULE hDestination = LoadLibraryA(pForward);

        // detect an infinite loop, the forward declaration requests the same module handle with 
        // the same function lookup, this could be an Api Set (Windows7+)
        if (hDestination == hModule && (ordinalSearch ? LOWORD(pFunction) == LOWORD(lpProcName) : strcmp(pFunction, lpProcName) == 0))
            hDestination = ResolveImportMap(pForward); // ResolveImportMap will return NULL if not an API Set and so avoid infinite recursion

        return InternalGetProcAddress(hDestination, pFunction);
    }

    return (FARPROC)MKPTR(hModule, dwAddress);
}

关于c++ - 导出函数转发给自己?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14766019/

相关文章:

工厂函数返回元组的 C++11 模式

c++ - 样本 SDL 程序给出一个空窗口

c# - ClickOnce 开始菜单图标

c++ - IFileOperation::DeleteItems 在 Windows 8 上不要求确认(与 Windows 7 不同)

windows - Perl:获取二进制支持的最低操作系统

java - Linux:无需安装即可运行 Python

c++ - 类模板特化中模板参数的默认值

C++,如果我需要它,我是否应该#include *和*它包含的其他东西?

c++ - 如何保护进程不被杀死?

c++ - 为什么 PE 部分会在运行之间发生变化?