获得KERNEL32.DLL模块地址以及函数的地址

通过PEB获得

DWORD getKernel32BaseAddrByPEB()
{
    PVOID pPeb = NULL;
    PVOID pLdr = NULL;
    PVOID pFlink = NULL;
    PVOID ptemp = NULL;
    PVOID BaseAddr = NULL;
    PVOID pFullName = NULL;
    __asm
    {
        mov eax, fs:[0x30]
        mov pPeb, eax
    }
    pLdr = (PVOID)*((PDWORD)((DWORD)pPeb + 0x0c));
    pFlink = (PVOID)*((PDWORD)((DWORD)pLdr + 0x14));//第一个
    ptemp = pFlink;
    //第3个就是kernel32
    ptemp = (PVOID)*((PDWORD)ptemp);//第二个
    ptemp = (PVOID)*((PDWORD)ptemp);//第三个
    BaseAddr = (PVOID)*((PDWORD)((DWORD)ptemp + 0x10));
    pFullName = (PVOID)*((PDWORD)((DWORD)ptemp + 0x20));

    wprintf(L"FullDllName is %s\n", pFullName);
    printf("BaseAddress is %x\n", BaseAddr);
    return (DWORD)BaseAddr;
}

获得函数地址

DWORD myGetProcessAddr(DWORD hModuleBaseAddr, PCSTR lpApi)
{
    PIMAGE_DOS_HEADER pDosHeader = NULL;
    PIMAGE_NT_HEADERS pNtHeader = NULL;

    PIMAGE_EXPORT_DIRECTORY pExportDir = NULL;

    DWORD ret = 0;
    PDWORD AddrOfName = NULL;
    PDWORD AddrOfFunction = NULL;
    PWORD AddrOfOrder = NULL;
    DWORD count = 0;
    WORD order = 0;
    PSTR pName = NULL;

    pDosHeader = (PIMAGE_DOS_HEADER)hModuleBaseAddr;
    pNtHeader = (PIMAGE_NT_HEADERS)((DWORD)pDosHeader + pDosHeader->e_lfanew);
    //导出表描述
    pExportDir = (PIMAGE_EXPORT_DIRECTORY)(hModuleBaseAddr +pNtHeader->OptionalHeader.DataDirectory[0].VirtualAddress);
    //名字表地址
    AddrOfName = (PDWORD)(hModuleBaseAddr + pExportDir->AddressOfNames);
    //函数表
    AddrOfFunction = (PDWORD)(hModuleBaseAddr + pExportDir->AddressOfFunctions);
    //序号表
    AddrOfOrder = (PWORD)(hModuleBaseAddr + pExportDir->AddressOfNameOrdinals);

    for (int i = 0; i < pExportDir->NumberOfNames;i++)
    {
        //这是偏移,需要加上模块基址
        pName = (PSTR)(*AddrOfName+hModuleBaseAddr);
        printf("%s\n", pName);
        //如果相等
        if (strcmp(pName, lpApi) == 0)
        {
            order = *(AddrOfOrder + count)+pExportDir->Base-1;
            ret = *(AddrOfFunction + order)+hModuleBaseAddr;
            return ret;
        }
        count++;
        AddrOfName++;
    }

    return ret;
}

你可能感兴趣的:(PE,WINDOWS,API)