Windows x86/ x64 Ring3层注入Dll总结

欢迎转载,转载请注明出处:http://www.cnblogs.com/uAreKongqi/p/6012353.html 

0x00.前言

  提到Dll的注入,立马能够想到的方法就有很多,比如利用远程线程、Apc等等,这里我对Ring3层的Dll注入学习做一个总结吧。

  我把注入的方法分成六类,分别是:1.创建新线程、2.设置线程上下背景文,修改寄存器、3.插入Apc队列、4.修改注册表、5.挂钩窗口消息、6.远程手动实现LoadLibrary。

  那么下面就开始学习之旅吧!

0x01.预备工作

  在涉及到注入的程序中,提升程序的权限自然是必不可少的,这里我提供了两个封装的函数,都可以用于提权。第一个是通过权限令牌来调整权限;第二个是通过ntdll.dll的导出的未文档化函数RtlAdjustPrivilege来调整权限。

// 传入参数 SE_DEBUG_NAME,提升到调试权限

BOOL GrantPriviledge(WCHAR* PriviledgeName)
{
    TOKEN_PRIVILEGES TokenPrivileges, OldPrivileges;
    DWORD             dwReturnLength = sizeof(OldPrivileges);
    HANDLE             TokenHandle = NULL;
    LUID             uID;

    // 打开权限令牌
    if (!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &TokenHandle))
    {
        if (GetLastError() != ERROR_NO_TOKEN)
        {
            return FALSE;
        }
        if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &TokenHandle))
        {
            return FALSE;
        }
    }

    if (!LookupPrivilegeValue(NULL, PriviledgeName, &uID))        // 通过权限名称查找uID
    {
        CloseHandle(TokenHandle);
        return FALSE;
    }

    TokenPrivileges.PrivilegeCount = 1;        // 要提升的权限个数
    TokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;    // 动态数组,数组大小根据Count的数目
    TokenPrivileges.Privileges[0].Luid = uID;

    // 在这里我们进行调整权限
    if (!AdjustTokenPrivileges(TokenHandle, FALSE, &TokenPrivileges, sizeof(TOKEN_PRIVILEGES), &OldPrivileges, &dwReturnLength))
    {
        CloseHandle(TokenHandle);
        return FALSE;
    }

    // 成功了
    CloseHandle(TokenHandle);
    return TRUE;
}
权限令牌
// 传入参数 SE_DEBUG_PRIVILEGE,提升到调试权限

#define SE_DEBUG_PRIVILEGE                (20L)

typedef
NTSTATUS(NTAPI * pfnRtlAdjustPrivilege)(
    UINT32 Privilege,
    BOOLEAN Enable,
    BOOLEAN Client,
    PBOOLEAN WasEnabled);

BOOL GrantPriviledge(IN UINT32 Priviledge)
{
    pfnRtlAdjustPrivilege    RtlAdjustPrivilege = NULL;
    BOOLEAN                    WasEnable = FALSE;

    RtlAdjustPrivilege = (pfnRtlAdjustPrivilege)GetProcAddress(GetModuleHandle(L"ntdll.dll"), "RtlAdjustPrivilege");
    if (RtlAdjustPrivilege == NULL)
    {
        return FALSE;
    }

    RtlAdjustPrivilege(Priviledge, TRUE, FALSE, &WasEnable);

    return TRUE;
}
RtlAdjustPrivilege

  紧接着,既然我们要对目标进程注入Dll,那么获得目标进程的Id是不可或缺的吧,因为OpenProcess是肯定会使用的,这里我也提供了两种通过目标进程映像名称获得进程Id的方法。第一种是最常见的使用TlHelp创建系统的进程快照;第二种是借助Psapi枚举系列函数,不过这个方法我实现的有缺憾,32位下不能得到64位进程的Id。

// 使用ToolHelp系列函数

#include <TlHelp32.h>

BOOL GetProcessIdByProcessImageName(IN PWCHAR wzProcessImageName, OUT PUINT32 ProcessId)
{
    HANDLE            ProcessSnapshotHandle = INVALID_HANDLE_VALUE;
    PROCESSENTRY32    ProcessEntry32 = { 0 };

    ProcessEntry32.dwSize = sizeof(PROCESSENTRY32);        // 初始化PROCESSENTRY32结构

    ProcessSnapshotHandle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);    // 给系统所有的进程快照
    if (ProcessSnapshotHandle == INVALID_HANDLE_VALUE)
    {
        return FALSE;
    }

    if (Process32First(ProcessSnapshotHandle, &ProcessEntry32))        // 找到第一个
    {
        do
        {
            if (lstrcmpi(ProcessEntry32.szExeFile, wzProcessImageName) == 0)        // 不区分大小写
            {
                *ProcessId = ProcessEntry32.th32ProcessID;
                break;
            }
        } while (Process32Next(ProcessSnapshotHandle, &ProcessEntry32));
    }

    CloseHandle(ProcessSnapshotHandle);
    ProcessSnapshotHandle = INVALID_HANDLE_VALUE;

    if (*ProcessId == 0)
    {
        return FALSE;
    }

    return TRUE;
}
TlHelp
// 使用Psapi系列枚举函数

#include <Psapi.h>

BOOL GetProcessIdByProcessImageName(IN PWCHAR wzProcessImageName, OUT PUINT32 ProcessId)
{
    DWORD    dwProcessesId[1024] = { 0 };
    DWORD    BytesReturned = 0;
    UINT32    ProcessCount = 0;

    // 获得当前操作系统中的所有进程Id,保存在dwProcessesId数组里
    if (!EnumProcesses(dwProcessesId, sizeof(dwProcessesId), &BytesReturned))
    {
        return FALSE;
    }

    ProcessCount = BytesReturned / sizeof(DWORD);

    // 遍历
    for (INT i = 0; i < ProcessCount; i++)
    {
        HMODULE    ModuleBase = NULL;
        WCHAR    wzModuleBaseName[MAX_PATH] = { 0 };
        HANDLE    ProcessHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessesId[i]);

        if (ProcessHandle == NULL)
        {
            continue;
        }

        if (EnumProcessModulesEx(ProcessHandle, &ModuleBase, sizeof(HMODULE), &BytesReturned, LIST_MODULES_ALL))
        {
            // 获得进程第一模块名称
            GetModuleBaseName(ProcessHandle, ModuleBase, wzModuleBaseName, MAX_PATH * sizeof(WCHAR));
        }
    
        CloseHandle(ProcessHandle);
        ProcessHandle = NULL;

        if (lstrcmpi(wzModuleBaseName, wzProcessImageName) == 0)        // 不区分大小写
        {
            *ProcessId = dwProcessesId[i];
            break;
        }
    }

    if (*ProcessId == 0)
    {
        return FALSE;
    }

    return TRUE;
}
Psapi

  然后在比如插入Apc队列、挂起线程等等操作中,需要对目标进程的线程操作,所以获得线程Id也有必要,同样的我也提供了两种通过进程Id获得线程Id的方法。第一个仍然是使用TlHelp创建系统的线程快照,把所有的线程存入vector模板里(供Apc注入使用);第二个是利用ZwQuerySystemInformation大法,枚举系统进程信息,这个方法我只返回了一个线程Id,已经够用了。

// 枚举指定进程Id的所有线程,压入模板中

#include <vector>
#include <TlHelp32.h>
using namespace std;

BOOL GetThreadIdByProcessId(IN UINT32 ProcessId, OUT vector<UINT32>& ThreadIdVector)
{
    HANDLE            ThreadSnapshotHandle = NULL;
    THREADENTRY32    ThreadEntry32 = { 0 };

    ThreadEntry32.dwSize = sizeof(THREADENTRY32);

    ThreadSnapshotHandle = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);        // 给系统所有的线程快照
    if (ThreadSnapshotHandle == INVALID_HANDLE_VALUE)
    {
        return FALSE;
    }

    if (Thread32First(ThreadSnapshotHandle, &ThreadEntry32))
    {
        do
        {
            if (ThreadEntry32.th32OwnerProcessID == ProcessId)
            {
                ThreadIdVector.emplace_back(ThreadEntry32.th32ThreadID);        // 把该进程的所有线程id压入模板
            }
        } while (Thread32Next(ThreadSnapshotHandle, &ThreadEntry32));
    }
    
    CloseHandle(ThreadSnapshotHandle);
    ThreadSnapshotHandle = NULL;
    return TRUE;
}
TlHelp
// ZwQuerySystemInformation+SystemProcessInformation

typedef
NTSTATUS(NTAPI * pfnZwQuerySystemInformation)(
    IN SYSTEM_INFORMATION_CLASS SystemInformationClass,
    OUT PVOID SystemInformation,
    IN UINT32 SystemInformationLength,
    OUT PUINT32 ReturnLength OPTIONAL);

BOOL GetThreadIdByProcessId(IN UINT32 ProcessId, OUT PUINT32 ThreadId)
{
    BOOL                        bOk = FALSE;
    NTSTATUS                    Status = 0;
    PVOID                        BufferData = NULL;
    PSYSTEM_PROCESS_INFO        spi = NULL;
    pfnZwQuerySystemInformation ZwQuerySystemInformation = NULL;

    ZwQuerySystemInformation = (pfnZwQuerySystemInformation)GetProcAddress(GetModuleHandle(L"ntdll.dll"), "ZwQuerySystemInformation");
    if (ZwQuerySystemInformation == NULL)
    {
        return FALSE;
    }

    BufferData = malloc(1024 * 1024);
    if (!BufferData)
    {
        return FALSE;
    }

    // 在QuerySystemInformation系列函数中,查询SystemProcessInformation时,必须提前申请好内存,不能先查询得到长度再重新调用
    Status = ZwQuerySystemInformation(SystemProcessInformation, BufferData, 1024 * 1024, NULL);
    if (!NT_SUCCESS(Status))
    {
        free(BufferData);
        return FALSE;
    }

    spi = (PSYSTEM_PROCESS_INFO)BufferData;

    // 遍历进程,找到我们的目标进程
    while (TRUE)
    {
        bOk = FALSE;
        if (spi->UniqueProcessId == (HANDLE)ProcessId)
        {
            bOk = TRUE;
            break;
        }
        else if (spi->NextEntryOffset)
        {
            spi = (PSYSTEM_PROCESS_INFO)((PUINT8)spi + spi->NextEntryOffset);
        }
        else
        {
            break;
        }
    }

    if (bOk)
    {
        for (INT i = 0; i < spi->NumberOfThreads; i++)
        {
            // 返出找到的线程Id
            *ThreadId = (UINT32)spi->Threads[i].ClientId.UniqueThread;
            break;
        }
    }

    if (BufferData != NULL)
    {
        free(BufferData);
    }

    return bOk;
}
ZwQuerySystemInformation

  嗯,目前为止,预备工作差不多完工,那我们就开始正题吧!

0x02.注入方法一 -- 创建新线程

  创建新线程,也就是在目标进程里,创建一个线程为我们服务,而创建线程的方法我找到的有三种:1.CreateRemoteThread;2.NtCreateThreadEx;3.RtlCreateUserThread。

  基本思路是:1.在目标进程内存空间申请内存;2.在刚申请的内存中写入Dll完整路径;3.创建新线程,去执行LoadLibrary,从而完成注入Dll。

  ps:这里直接使用从自己加载的kernel32模块导出表中获得LoadLibrary地址,是因为一般情况下,所有进程加载这类系统库在内存中的地址相同!

  因为只是创线程所使用的函数不一样,所以下面的代码随便放开一个创线程的步骤,屏蔽其他两个,都是可以成功的,这里我放开的是NtCreateThreadEx。

typedef NTSTATUS(NTAPI* pfnNtCreateThreadEx)
(
    OUT PHANDLE hThread,
    IN ACCESS_MASK DesiredAccess,
    IN PVOID ObjectAttributes,
    IN HANDLE ProcessHandle,
    IN PVOID lpStartAddress,
    IN PVOID lpParameter,
    IN ULONG Flags,
    IN SIZE_T StackZeroBits,
    IN SIZE_T SizeOfStackCommit,
    IN SIZE_T SizeOfStackReserve,
    OUT PVOID lpBytesBuffer);

#define NT_SUCCESS(x) ((x) >= 0)

typedef struct _CLIENT_ID {
    HANDLE UniqueProcess;
    HANDLE UniqueThread;
} CLIENT_ID, *PCLIENT_ID;

typedef NTSTATUS(NTAPI * pfnRtlCreateUserThread)(
    IN HANDLE ProcessHandle,
    IN PSECURITY_DESCRIPTOR SecurityDescriptor OPTIONAL,
    IN BOOLEAN CreateSuspended,
    IN ULONG StackZeroBits OPTIONAL,
    IN SIZE_T StackReserve OPTIONAL,
    IN SIZE_T StackCommit OPTIONAL,
    IN PTHREAD_START_ROUTINE StartAddress,
    IN PVOID Parameter OPTIONAL,
    OUT PHANDLE ThreadHandle OPTIONAL,
    OUT PCLIENT_ID ClientId OPTIONAL);


BOOL InjectDll(UINT32 ProcessId)
{
    HANDLE ProcessHandle = NULL;

    ProcessHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessId);

    // 在对方进程空间申请内存,存储Dll完整路径
    UINT32    DllFullPathLength = (strlen(DllFullPath) + 1);
    PVOID     DllFullPathBufferData = VirtualAllocEx(ProcessHandle, NULL, DllFullPathLength, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
    if (DllFullPathBufferData == NULL)
    {
        CloseHandle(ProcessHandle);
        return FALSE;
    }

    // 将DllFullPath写进刚刚申请的内存中
    SIZE_T    ReturnLength;
    BOOL bOk = WriteProcessMemory(ProcessHandle, DllFullPathBufferData, DllFullPath, strlen(DllFullPath) + 1, &ReturnLength);

    LPTHREAD_START_ROUTINE    LoadLibraryAddress = NULL;
    HMODULE                    Kernel32Module = GetModuleHandle(L"Kernel32");

    LoadLibraryAddress = (LPTHREAD_START_ROUTINE)GetProcAddress(Kernel32Module, "LoadLibraryA");


    pfnNtCreateThreadEx NtCreateThreadEx = (pfnNtCreateThreadEx)GetProcAddress(GetModuleHandle(L"ntdll.dll"), "NtCreateThreadEx");
    if (NtCreateThreadEx == NULL)
    {
        CloseHandle(ProcessHandle);
        return FALSE;
    }

    HANDLE ThreadHandle = NULL;
    // 0x1FFFFF #define THREAD_ALL_ACCESS         (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFFF)
    NtCreateThreadEx(&ThreadHandle, 0x1FFFFF, NULL, ProcessHandle, (LPTHREAD_START_ROUTINE)LoadLibraryAddress, DllFullPathBufferData, FALSE, NULL, NULL, NULL, NULL);

/*
pfnRtlCreateUserThread RtlCreateUserThread = (pfnRtlCreateUserThread)GetProcAddress(GetModuleHandle(L"ntdll.dll"), "RtlCreateUserThread");

    HANDLE ThreadHandle = NULL;
    NTSTATUS Status = RtlCreateUserThread(ProcessHandle, NULL, FALSE, 0, 0, 0, LoadLibraryAddress, DllFullPathBufferData, &ThreadHandle, NULL);    
*/

/*
HANDLE ThreadHandle = CreateRemoteThread(ProcessHandle, NULL, 0, LoadLibraryAddress, DllFullPathBufferData, 0, NULL);        // CreateRemoteThread 函数
*/


    if (ThreadHandle == NULL)
    {
        CloseHandle(ProcessHandle);
        return FALSE;
    }

    if (WaitForSingleObject(ThreadHandle, INFINITE) == WAIT_FAILED)
    {
        return FALSE;
    }

    CloseHandle(ProcessHandle);
    CloseHandle(ThreadHandle);

    return TRUE;
}

0x03.注入方法二 -- 设置线程上下背景文

  设置线程上下背景文的主要目的是让目标进程的某一线程转去执行我们的代码,然后再回来做他该做的事,而我们的代码,就是一串由汇编硬编码组成的ShellCode。

  这串ShellCode做了三件事:1.传入Dll完整路径参数;2.呼叫LoadLibrary函数地址;3.返回原先的Eip或Rip。

  这里我选用的呼叫指令是ff 15 和 ff 25,在32位下为跳转到15(25)指令后面字节码对应地址里面存放的地址,在64位下15(25)指令后面四字节存放的是偏移,该跳转为跳转到换算出来的地址里面存放的地址,这里我把偏移写成0,以便于计算。

#ifdef _WIN64
// 测试 64 位 dll被注,Bug已修复

/*
0:019> u 0x000002b5d5f80000
000002b5`d5f80000 4883ec28        sub     rsp,28h
000002b5`d5f80004 488d0d20000000  lea     rcx,[000002b5`d5f8002b]
000002b5`d5f8000b ff1512000000    call    qword ptr [000002b5`d5f80023]
000002b5`d5f80011 4883c428        add     rsp,28h
000002b5`d5f80015 ff2500000000    jmp     qword ptr [000002b5`d5f8001b]
*/

UINT8    ShellCode[0x100] = {
    0x48,0x83,0xEC,0x28,    // sub rsp ,28h

    0x48,0x8D,0x0d,            // [+4] lea rcx,
    0x00,0x00,0x00,0x00,    // [+7] DllNameOffset = [+43] - [+4] - 7

    // call 跳偏移,到地址,解*号
    0xff,0x15,                // [+11]
    0x00,0x00,0x00,0x00,    // [+13] 

    0x48,0x83,0xc4,0x28,    // [+17] add rsp,28h

    // jmp 跳偏移,到地址,解*号
    0xff,0x25,                // [+21]
    0x00,0x00,0x00,0x00,    // [+23] LoadLibraryAddressOffset

    // 存放原先的 rip
    0x00,0x00,0x00,0x00,    // [+27]
    0x00,0x00,0x00,0x00,    // [+31]

    // 跳板 loadlibrary地址
    0x00,0x00,0x00,0x00,    // [+35] 
    0x00,0x00,0x00,0x00,    // [+39]

// 存放dll完整路径
//    0x00,0x00,0x00,0x00,    // [+43]
//    0x00,0x00,0x00,0x00        // [+47]
//    ......
};
#else
// 测试 32 位 配合新写的Dll可重复注入

/*
0:005> u 0x00ca0000
00000000`00ca0000 60              pusha
00000000`00ca0001 9c              pushfq
00000000`00ca0002 681d00ca00      push    0CA001Dh
00000000`00ca0007 ff151900ca00    call    qword ptr [00000000`01940026]
00000000`00ca000d 9d              popfq
00000000`00ca000e 61              popa
00000000`00ca000f ff251500ca00    jmp     qword ptr [00000000`0194002a]

*/

UINT8    ShellCode[0x100] = {
    0x60,                    // [+0] pusha
    0x9c,                    // [+1] pushf
    0x68,                    // [+2] push
    0x00,0x00,0x00,0x00,    // [+3] ShellCode + 
    0xff,0x15,                // [+7] call    
    0x00,0x00,0x00,0x00,    // [+9] LoadLibrary Addr  Addr
    0x9d,                    // [+13] popf
    0x61,                    // [+14] popa
    0xff,0x25,                // [+15] jmp
    0x00,0x00,0x00,0x00,    // [+17] jmp  eip

    // eip 地址
    0x00,0x00,0x00,0x00,    // [+21]
    // LoadLibrary 地址
    0x00,0x00,0x00,0x00,    // [+25] 
    // DllFullPath 
    0x00,0x00,0x00,0x00        // [+29] 
};

#endif

  整个注入过程由这些步骤组成:在目标进程申请内存(可执行内存) ---> 填充ShellCode需要的地址码 ---> 将ShellCode写入申请的内存 ---> SuspendThread(挂起线程)--->GetThreadContext(获得线程上下背景文)---> 修改Context的Eip或Rip为ShellCode首地址 ---> SetThreadContext(设置刚修改过的Context)---> ResumeThread(恢复线程执行)。

BOOL Inject(IN UINT32 ProcessId, IN UINT32 ThreadId)
{
    BOOL        bOk = FALSE;
    CONTEXT        ThreadContext = { 0 };
    PVOID        BufferData = NULL;

    HANDLE        ThreadHandle = OpenThread(THREAD_ALL_ACCESS, FALSE, ThreadId);
    HANDLE        ProcessHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessId);


    // 首先挂起线程
    SuspendThread(ThreadHandle);


    ThreadContext.ContextFlags = CONTEXT_ALL;
    if (GetThreadContext(ThreadHandle, &ThreadContext) == FALSE)
    {
        CloseHandle(ThreadHandle);
        CloseHandle(ProcessHandle);
        return FALSE;
    }

    BufferData = VirtualAllocEx(ProcessHandle, NULL, sizeof(ShellCode), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
    if (BufferData != NULL)
    {

        if (LoadLibraryWAddress != NULL)
        {
#ifdef _WIN64

            // ShellCode + 43处 存放完整路径
            PUINT8    v1 = ShellCode + 43;
            memcpy(v1, DllFullPath, (wcslen(DllFullPath) + 1) * sizeof(WCHAR));
            UINT32    DllNameOffset = (UINT32)(((PUINT8)BufferData + 43) - ((PUINT8)BufferData + 4) - 7);
            *(PUINT32)(ShellCode + 7) = DllNameOffset;

            // ShellCode + 35处 放置 LoadLibrary 函数地址
            *(PUINT64)(ShellCode + 35) = (UINT64)LoadLibraryWAddress;
            UINT32    LoadLibraryAddressOffset = (UINT32)(((PUINT8)BufferData + 35) - ((PUINT8)BufferData + 11) - 6);
            *(PUINT32)(ShellCode + 13) = LoadLibraryAddressOffset;

            // 放置 rip 地址
            *(PUINT64)(ShellCode + 27) = ThreadContext.Rip;

            if (!WriteProcessMemory(ProcessHandle, BufferData, ShellCode, sizeof(ShellCode), NULL))
            {
                return FALSE;
            }
            ThreadContext.Rip = (UINT64)BufferData;

#else
            PUINT8    v1 = ShellCode + 29;

            memcpy((char*)v1, DllFullPath, (wcslen(DllFullPath) + 1) * sizeof(WCHAR));    //这里是要注入的DLL名字
            *(PUINT32)(ShellCode + 3) = (UINT32)BufferData + 29;

            *(PUINT32)(ShellCode + 25) = LoadLibraryWAddress;   //loadlibrary地址放入shellcode中
            *(PUINT32)(ShellCode + 9) = (UINT32)BufferData + 25;//修改call 之后的地址 为目标空间存放 loaddlladdr的地址
                                                                //////////////////////////////////
            *(PUINT32)(ShellCode + 21) = ThreadContext.Eip;
            *(PUINT32)(ShellCode + 17) = (UINT32)BufferData + 21;//修改jmp 之后为原来eip的地址
            if (!WriteProcessMemory(ProcessHandle, BufferData, ShellCode, sizeof(ShellCode), NULL))
            {
                printf("write Process Error\n");
                return FALSE;
            }
            ThreadContext.Eip = (UINT32)BufferData;

#endif            
            if (!SetThreadContext(ThreadHandle, &ThreadContext))
            {
                printf("set thread context error\n");
                return FALSE;
            }
            ResumeThread(ThreadHandle);


            printf("ShellCode 注入完成\r\n");
        }
    }

    CloseHandle(ThreadHandle);
    CloseHandle(ProcessHandle);
    return TRUE;
}

0x04.插入Apc队列

  Ring3层的Apc注入是不太稳定的,我的做法就是暴力的向目标进程的所有线程的UserMode Apc队列(线程有两个Apc队列:Kernel和User)上插入Apc对象,等待他去执行该Apc里注册的函数。而只有当线程处于alterable状态时,才会查看Apc队列是否有需要执行的注册函数。

  ps:正是因为不知道哪个线程会去处理Apc,所以感觉Ring3层Apc注入不如其他方法好使,不过Ring0层Apc注入还是比较稳定的。之前测试xp和win10都成功,win7下注explorer进程总是崩溃,后来捯饬半天,发现遍历线程的时候从后往前遍历着插入就不会崩溃Orz

int main()
{
    ......

    ThreadCount = ThreadIdVector.size();
    for (INT i = ThreadCount - 1; i >= 0; i--)
    {
        UINT32 ThreadId = ThreadIdVector[i];
        InjectDllByApc(ProcessId, ThreadId);
    }
    ......
}

BOOL InjectDllByApc(IN UINT32 ProcessId, IN UINT32 ThreadId)
{
    BOOL        bOk = 0;
    HANDLE        ThreadHandle = OpenThread(THREAD_ALL_ACCESS, FALSE, ThreadId);
    HANDLE        ProcessHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessId);
    UINT_PTR    LoadLibraryAddress = 0;
    SIZE_T        ReturnLength = 0;
    UINT32        DllFullPathLength = (strlen(DllFullPath) + 1);

    // 全局,申请一次内存
    if (DllFullPathBufferData == NULL)
    {
        //申请内存
        DllFullPathBufferData = VirtualAllocEx(ProcessHandle, NULL, DllFullPathLength, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
        if (DllFullPathBufferData == NULL)
        {
            CloseHandle(ProcessHandle);
            CloseHandle(ThreadHandle);
            return FALSE;
        }
    }

    // 避免之前写操作失败,每次重复写入

    bOk = WriteProcessMemory(ProcessHandle, DllFullPathBufferData, DllFullPath, strlen(DllFullPath) + 1,
        &ReturnLength);
    if (bOk == FALSE)
    {
        CloseHandle(ProcessHandle);
        CloseHandle(ThreadHandle);
        return FALSE;
    }

    LoadLibraryAddress = (UINT_PTR)GetProcAddress(GetModuleHandle(L"Kernel32.dll"), "LoadLibraryA");
    if (LoadLibraryAddress == NULL)
    {
        CloseHandle(ProcessHandle);
        CloseHandle(ThreadHandle);
        return FALSE;
    }

    __try
    {

        QueueUserAPC((PAPCFUNC)LoadLibraryAddress, ThreadHandle, (UINT_PTR)DllFullPathBufferData);

    }
    __except (EXCEPTION_CONTINUE_EXECUTION)
    {
    }


    CloseHandle(ProcessHandle);
    CloseHandle(ThreadHandle);

    return TRUE;
}

0x05.修改注册表

  注册表注入算得上是全局Hook了吧,毕竟新创建的进程在加载User32.dll时,都会自动调用LoadLibrary去加载注册表中某个表项键值里写入的Dll路径。

  我们关心的这个注册表项键是:

  x64下:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows

  x86下:HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows NT\CurrentVersion\Windows

  我们要设置的键值是AppInit_DLLs = “Dll完整路径”,LoadAppInit_Dlls = 1(让系统使用这个注册表项) 

  ps:由于注入的Dll在进程创建的早期,所以在Dll中使用函数要格外小心,因为有的库可能还没加载上。

int main()
{
    LSTATUS Status = 0;

#ifdef _WIN64
    WCHAR* wzSubKey = L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows";
#else
    WCHAR* wzSubKey = L"SOFTWARE\\WOW6432Node\\Microsoft\\Windows NT\\CurrentVersion\\Windows";
#endif // _WIN64


    HKEY    hKey = NULL;

    // 打开注册表
    Status = RegOpenKeyExW(HKEY_LOCAL_MACHINE,        // 要打开的主键
        wzSubKey,            // 要打开的子键名字地址
        0,                    // 保留,传0
        KEY_ALL_ACCESS,        // 打开的方式
        &hKey);                // 返回的子键句柄
    if (Status != ERROR_SUCCESS)
    {
        return 0;
    }

    WCHAR*    wzValueName = L"AppInit_DLLs";
    DWORD    dwValueType = 0;
    UINT8    ValueData[MAX_PATH] = { 0 };
    DWORD    dwReturnLength = 0;

    // 查询注册表
    Status = RegQueryValueExW(hKey,        // 子键句柄
        wzValueName,        // 待查询键值的名称
        NULL,                // 保留
        &dwValueType,        // 数据类型
        ValueData,            // 键值
        &dwReturnLength);


    WCHAR    wzDllFullPath[MAX_PATH] = { 0 };
    GetCurrentDirectoryW(MAX_PATH, wzDllFullPath);

#ifdef _WIN64
    wcscat_s(wzDllFullPath, L"\\x64NormalDll.dll");
#else
    wcscat_s(wzDllFullPath, L"\\x86NormalDll.dll");
#endif

    // 设置键值
    Status = RegSetValueExW(hKey,
        wzValueName,
        NULL,
        dwValueType,
        (CONST BYTE*)wzDllFullPath,
        (lstrlen(wzDllFullPath) + 1) * sizeof(WCHAR));
    if (Status != ERROR_SUCCESS)
    {
        return 0;
    }

    wzValueName = L"LoadAppInit_DLLs";
    DWORD    dwLoadAppInit = 1;

    // 查询注册表
    Status = RegQueryValueExW(hKey, wzValueName, NULL, &dwValueType, ValueData, &dwReturnLength);

    // 设置键值
    Status = RegSetValueExW(hKey, wzValueName, NULL, dwValueType, (CONST BYTE*)&dwLoadAppInit, sizeof(DWORD));
    if (Status != ERROR_SUCCESS)
    {
        return 0;
    }

    printf("Input Any Key To Resume\r\n");

    getchar();
    getchar();

    // 恢复键值
    dwLoadAppInit = 0;
    Status = RegQueryValueExW(hKey, wzValueName, NULL, &dwValueType, ValueData, &dwReturnLength);
    Status = RegSetValueExW(hKey, wzValueName, NULL, dwValueType, (CONST BYTE*)&dwLoadAppInit, sizeof(DWORD));

    wzValueName = L"AppInit_DLLs";
    ZeroMemory(wzDllFullPath, (lstrlen(wzDllFullPath) + 1) * sizeof(WCHAR));
    Status = RegQueryValueExW(hKey, wzValueName, NULL, &dwValueType, ValueData, &dwReturnLength);
    Status = RegSetValueExW(hKey, wzValueName, NULL, dwValueType, (CONST BYTE*)wzDllFullPath, 0);


    return 0;
}

 

0x06.挂钩窗口消息

  挂钩窗口消息使用了MS提供的一个API接口SetWindowsHookEx。

  他的工作原理是给带窗口的目标进程的某个线程的某个消息挂钩上我们Dll导出的函数,一旦消息触发,则导出函数(处理该消息的钩子程序,调用约定需要时__stdcall)就会被调用,这时还需要调用。前面学习到的几种方法归根结底是调用了LoadLibrary,而这个方法并没有。

// 注入exe关键代码 给目标线程的指定消息上下钩,走进Dll导出函数
BOOL Inject(IN UINT32 ThreadId, OUT HHOOK& HookHandle)
{
    HMODULE    DllModule = LoadLibraryA(DllFullPath);
    FARPROC FunctionAddress = GetProcAddress(DllModule, "Sub_1");

    HookHandle = SetWindowsHookEx(WH_KEYBOARD, (HOOKPROC)FunctionAddress, DllModule, ThreadId);
    if (HookHandle == NULL)
    {
        return FALSE;
    }
    return TRUE;
}
// 动态库中导出函数

 // 调试发现,这里的调用约定要使用__stdcall,应该跟堆栈有关系
 LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
 {
  MessageBox(0, 0, 0, 0);

  return CallNextHookEx(NULL, nCode, wParam, lParam);
 }

0x07.远程手动实现LoadLibrary

  该方法学习自github上名叫ReflevtiveDllInjection,大体上分为两个部分,exe和dll,下面分别简述。

  exe:作为注入启动程序,在目标进程申请一块儿PAGE_EXECUTE_READWRITE内存,将Dll以文件格式直接写入目标进程内存空间中,然后获得导出函数"LoadDllByOEP"在文件中的偏移,使用CreateRemoteThread直接让目标进程去执行LoadDllByOEP函数。

  Dll:最关键导出 LoadDllByOEP 函数,在该函数里,首先通过目标进程加载模块ntdll.dll的导出表中获得NtFlushInstructionCache函数地址,在Kernel32.dll的导出表中获得LoadLibraryA、GetProcAddress、VirtualAlloc函数地址;然后在进程内存空间里重新申请内存,拷贝自己的PE结构到内存里,接着修正IAT和重定向块,最后调用模块OEP,完成了手动实现LoadLibrary!

  ps:写代码时参考《Windows PE权威指南》,对整个PE结构又有了新的认识。我有for循环强迫症。。这份代码就全贴上了。

// InjectDllByOEP.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <Windows.h>
#include <iostream>
#include <TlHelp32.h>

using namespace std;


BOOL GrantPriviledge(WCHAR* PriviledgeName);

UINT32 GetLoadDllByOEPOffsetInFile(PVOID DllBuffer);

UINT32 RVAToOffset(UINT32 RVA, PIMAGE_NT_HEADERS NtHeader);

BOOL GetProcessIdByProcessImageName(IN WCHAR* wzProcessImageName, OUT UINT32* TargetProcessId);

HANDLE WINAPI LoadRemoteDll(HANDLE ProcessHandle, PVOID ModuleFileBaseAddress, UINT32 ModuleFileSize, LPVOID lParam);

CHAR DllFullPath[MAX_PATH] = { 0 };

int main()
{
    // 首先提权一波
    if (GrantPriviledge(SE_DEBUG_NAME) == FALSE)
    {
        printf("GrantPriviledge Error\r\n");
    }

    // 接着通过进程名得到进程id
    UINT32    ProcessId = 0;

    GetCurrentDirectoryA(MAX_PATH, DllFullPath);

#ifdef _WIN64
//    GetProcessIdByProcessImageName(L"Taskmgr.exe", &ProcessId);
    GetProcessIdByProcessImageName(L"explorer.exe", &ProcessId);
    strcat_s(DllFullPath, "\\x64LoadRemoteDll.dll");
#else
    GetProcessIdByProcessImageName(L"notepad++.exe", &ProcessId);
    strcat_s(DllFullPath, "\\x86LoadRemoteDll.dll");
#endif

    // 获得dll句柄
    HANDLE FileHandle = CreateFileA(DllFullPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if (FileHandle == INVALID_HANDLE_VALUE)
    {
        printf("Open File Error\r\n");
        return 0;
    }

    // 获得dll文件长度
    UINT32    FileSize = GetFileSize(FileHandle, NULL);
    if (FileSize == INVALID_FILE_SIZE || FileSize == 0)
    {
        printf("Get File Size Error\r\n");
        CloseHandle(FileHandle);
        return 0;
    }

    // 申请内存,保存
    PVOID    FileData = HeapAlloc(GetProcessHeap(), 0, FileSize);
    if (FileData == NULL)
    {
        printf("HeapAlloc Error\r\n");
        CloseHandle(FileHandle);
        return 0;
    }

    DWORD ReturnLength = 0;
    BOOL bOk = ReadFile(FileHandle, FileData, FileSize, &ReturnLength, NULL);
    CloseHandle(FileHandle);
    if (bOk == FALSE)
    {
        printf("ReadFile Error\r\n");
        HeapFree(GetProcessHeap(), 0, FileData);
        return 0;
    }

    HANDLE ProcessHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessId);
    if (ProcessHandle == NULL)
    {
        printf("OpenProcess Error\r\n");
        HeapFree(GetProcessHeap(), 0, FileData);
        return 0;
    }

    // 执行Dll中的导出函数LoadDllByOEP,让目标进程实现LoadLibrary功能
    HANDLE ThreadHandle = LoadRemoteDll(ProcessHandle, FileData, FileSize, NULL);
    if (ThreadHandle == NULL)
    {
        goto _Clear;
    }

    WaitForSingleObject(ThreadHandle, INFINITE);

_Clear:

    if (FileData)
    {
        HeapFree(GetProcessHeap(), 0, FileData);
    }

    if (ProcessHandle)
    {
        CloseHandle(ProcessHandle);
    }

    return 0;
}


/************************************************************************
*  Name : LoadRemoteDll
*  Param: ProcessHandle            进程句柄    (IN)
*  Param: ModuleBaseAddress        模块基地址
*  Param: ModuleLength            模块在文件中的大小
*  Param: lParam                模块句柄
*  Ret  : HANDLE
*  将Dll以文件格式写入目标进程内存,并执行Dll的导出函数LoadDllByOEP
************************************************************************/

HANDLE WINAPI LoadRemoteDll(HANDLE ProcessHandle, PVOID ModuleFileBaseAddress, UINT32 ModuleFileSize, LPVOID lParam)
{

    HANDLE    ThreadHandle = NULL;

    __try
    {
        if (ProcessHandle == NULL || ModuleFileBaseAddress == NULL || ModuleFileSize == 0)
        {
            return NULL;
        }

        // 导出函数相对于 ModuelBaseAddress 的 Offset
        UINT32    FunctionOffset = GetLoadDllByOEPOffsetInFile(ModuleFileBaseAddress);
        if (FunctionOffset == 0)
        {
            return NULL;
        }

        // 在目标进程申请内存
        PVOID    RemoteBufferData = VirtualAllocEx(ProcessHandle, NULL, ModuleFileSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
        if (RemoteBufferData == NULL)
        {
            return NULL;
        }
        
        // 把Dll文件写入目标进程内存空间
        BOOL    bOk = WriteProcessMemory(ProcessHandle, RemoteBufferData, ModuleFileBaseAddress, ModuleFileSize, NULL);
        if (bOk == FALSE)
        {
            return NULL;
        }

        // 以文件格式去执行 Dll 中的 LoadDllByOEP
        LPTHREAD_START_ROUTINE    RemoteThreadCallBack = (LPTHREAD_START_ROUTINE)((PUINT8)RemoteBufferData + FunctionOffset);

        ThreadHandle = CreateRemoteThread(ProcessHandle, NULL, 1024 * 1024, RemoteThreadCallBack, lParam, 0, NULL);

    }
    __except (EXCEPTION_EXECUTE_HANDLER)
    {
        ThreadHandle = NULL;
    }

    return ThreadHandle;
}


/************************************************************************
*  Name : LoadRemoteDll
*  Param: ProcessHandle            进程句柄
*  Ret  : HANDLE
*  获得LoadDllByOEP在Dll文件中的偏移量
************************************************************************/

UINT32 GetLoadDllByOEPOffsetInFile(PVOID DllBuffer)
{
    UINT_PTR            BaseAddress = (UINT_PTR)DllBuffer;
    PIMAGE_DOS_HEADER    DosHeader = NULL;
    PIMAGE_NT_HEADERS    NtHeader = NULL;

    DosHeader = (PIMAGE_DOS_HEADER)BaseAddress;
    NtHeader = (PIMAGE_NT_HEADERS)((PUINT8)BaseAddress + DosHeader->e_lfanew);

    /*
    #define IMAGE_NT_OPTIONAL_HDR32_MAGIC      0x10b
    #define IMAGE_NT_OPTIONAL_HDR64_MAGIC      0x20b
    #define IMAGE_ROM_OPTIONAL_HDR_MAGIC       0x107
    */

    if (NtHeader->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)    // pe32
    {
    }
    else if (NtHeader->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)    // pe64
    {
    }
    else
    {
        return 0;
    }

    UINT32                    ExportDirectoryRVA = NtHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
    PIMAGE_EXPORT_DIRECTORY    ExportDirectory = (PIMAGE_EXPORT_DIRECTORY)((PUINT8)BaseAddress + RVAToOffset(ExportDirectoryRVA, NtHeader));

    UINT32                    AddressOfNamesRVA = ExportDirectory->AddressOfNames;
    PUINT32                    AddressOfNames = (PUINT32)((PUINT8)BaseAddress + RVAToOffset(AddressOfNamesRVA, NtHeader));

    UINT32                    AddressOfFunctionsRVA = ExportDirectory->AddressOfFunctions;
    PUINT32                    AddressOfFunctions = (PUINT32)((PUINT8)BaseAddress + RVAToOffset(AddressOfFunctionsRVA, NtHeader));

    UINT32                    AddressOfNameOrdinalsRVA = ExportDirectory->AddressOfNameOrdinals;
    PUINT16                    AddressOfNameOrdinals = (PUINT16)((PUINT8)BaseAddress + RVAToOffset(AddressOfNameOrdinalsRVA, NtHeader));

    for (UINT32 i = 0; i < ExportDirectory->NumberOfFunctions; i++)
    {
        CHAR*    ExportFunctionName = (CHAR*)((PUINT8)BaseAddress + RVAToOffset(*AddressOfNames, NtHeader));

        if (strstr(ExportFunctionName, "LoadDllByOEP") != NULL)
        {
            UINT16    ExportFunctionOrdinals = AddressOfNameOrdinals[i];

            return RVAToOffset(AddressOfFunctions[ExportFunctionOrdinals], NtHeader);
        }
    }
    return 0;
}

/************************************************************************
*  Name : RVAToOffset
*  Param: RVA                内存中偏移
*  Param: NtHeader            Nt头
*  Ret  : UINT32
*  内存中偏移转换成文件中偏移
************************************************************************/

UINT32 RVAToOffset(UINT32 RVA, PIMAGE_NT_HEADERS NtHeader)
{
    UINT32                    i = 0;
    PIMAGE_SECTION_HEADER    SectionHeader = NULL;

    SectionHeader = IMAGE_FIRST_SECTION(NtHeader);

    if (RVA < SectionHeader[0].PointerToRawData)
    {
        return RVA;
    }

    for (i = 0; i < NtHeader->FileHeader.NumberOfSections; i++)
    {
        if (RVA >= SectionHeader[i].VirtualAddress && RVA < (SectionHeader[i].VirtualAddress + SectionHeader[i].SizeOfRawData))
        {
            return (RVA - SectionHeader[i].VirtualAddress + SectionHeader[i].PointerToRawData);
        }
    }

    return 0;
}

/************************************************************************
*  Name : GetProcessIdByProcessImageName
*  Param: wzProcessImageName        进程映像名称    (IN)
*  Param: TargetProcessId            进程Id            (OUT)
*  Ret  : BOOLEAN
*  使用ToolHelp系列函数通过进程映像名称获得进程Id
************************************************************************/

BOOL GetProcessIdByProcessImageName(IN WCHAR* wzProcessImageName, OUT UINT32* TargetProcessId)
{
    HANDLE            ProcessSnapshotHandle = NULL;
    PROCESSENTRY32    ProcessEntry32 = { 0 };

    ProcessEntry32.dwSize = sizeof(PROCESSENTRY32);        // 初始化PROCESSENTRY32结构

    ProcessSnapshotHandle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);    // 给系统所有的进程快照

    if (ProcessSnapshotHandle == INVALID_HANDLE_VALUE)
    {
        return FALSE;
    }

    Process32First(ProcessSnapshotHandle, &ProcessEntry32);        // 找到第一个
    do
    {
        if (lstrcmpi(ProcessEntry32.szExeFile, wzProcessImageName) == 0)        // 不区分大小写
        {
            *TargetProcessId = ProcessEntry32.th32ProcessID;
            break;
        }
    } while (Process32Next(ProcessSnapshotHandle, &ProcessEntry32));

    CloseHandle(ProcessSnapshotHandle);
    ProcessSnapshotHandle = NULL;
    return TRUE;
}


/************************************************************************
*  Name : GrantPriviledge
*  Param: PriviledgeName        想要提升的权限
*  Ret  : BOOLEAN
*  提升自己想要的权限
************************************************************************/

BOOL GrantPriviledge(WCHAR* PriviledgeName)
{
    TOKEN_PRIVILEGES TokenPrivileges, OldPrivileges;
    DWORD             dwReturnLength = sizeof(OldPrivileges);
    HANDLE             TokenHandle = NULL;
    LUID             uID;

    // 打开权限令牌
    if (!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &TokenHandle))
    {
        if (GetLastError() != ERROR_NO_TOKEN)
        {
            return FALSE;
        }
        if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &TokenHandle))
        {
            return FALSE;
        }
    }

    if (!LookupPrivilegeValue(NULL, PriviledgeName, &uID))        // 通过权限名称查找uID
    {
        CloseHandle(TokenHandle);
        return FALSE;
    }

    TokenPrivileges.PrivilegeCount = 1;        // 要提升的权限个数
    TokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;    // 动态数组,数组大小根据Count的数目
    TokenPrivileges.Privileges[0].Luid = uID;

    // 在这里我们进行调整权限
    if (!AdjustTokenPrivileges(TokenHandle, FALSE, &TokenPrivileges, sizeof(TOKEN_PRIVILEGES), &OldPrivileges, &dwReturnLength))
    {
        CloseHandle(TokenHandle);
        return FALSE;
    }

    // 成功了
    CloseHandle(TokenHandle);
    return TRUE;
}
// LoadRemoteDll.h

#include <Windows.h>
#include <intrin.h>


#ifdef LOADREMOTEDLL_EXPORTS
#define LOADREMOTEDLL_API __declspec(dllexport)
#else
#define LOADREMOTEDLL_API __declspec(dllimport)
#endif


#define KERNEL32DLL_HASH                0x6A4ABC5B
#define NTDLLDLL_HASH                    0x3CFA685D

#define LOADLIBRARYA_HASH                0xEC0E4E8E
#define GETPROCADDRESS_HASH                0x7C0DFCAA
#define VIRTUALALLOC_HASH                0x91AFCA54
#define NTFLUSHINSTRUCTIONCACHE_HASH    0x534C0AB8

#define IMAGE_REL_BASED_ARM_MOV32A        5
#define IMAGE_REL_BASED_ARM_MOV32T        7

#define HASH_KEY                        13

#pragma intrinsic( _rotr )

__forceinline UINT32 ror(UINT32 d)
{
    return _rotr(d, HASH_KEY);
}

__forceinline UINT32 hash(char * c)
{
    register UINT32 h = 0;
    do
    {
        h = ror(h);
        h += *c;
    } while (*++c);

    return h;
}

//////////////////////////////////////////////////////////////////////////

typedef struct _UNICODE_STRING
{
    USHORT                    Length;
    USHORT                    MaximumLength;
    PWSTR                    Buffer;
} UNICODE_STRING, *PUNICODE_STRING;


typedef struct _PEB_LDR_DATA_WIN7_X64
{
    UINT32    Length;
    UINT8   Initialized;
    UINT8   _PADDING0_[0x3];
    PVOID   SsHandle;
    LIST_ENTRY InLoadOrderModuleList;
    LIST_ENTRY InMemoryOrderModuleList;
    LIST_ENTRY InInitializationOrderModuleList;
    PVOID    EntryInProgress;
    UINT8   ShutdownInProgress;
    UINT8   _PADDING1_[0x7];
    PVOID   ShutdownThreadId;
}PEB_LDR_DATA_WIN7_X64, *PPEB_LDR_DATA_WIN7_X64;


typedef struct _PEB_LDR_DATA_WINXP_X86
{
    UINT32    Length;
    UINT8   Initialized;
    UINT8   _PADDING0_[0x3];
    PVOID   SsHandle;
    LIST_ENTRY InLoadOrderModuleList;
    LIST_ENTRY InMemoryOrderModuleList;
    LIST_ENTRY InInitializationOrderModuleList;
    PVOID    EntryInProgress;
}PEB_LDR_DATA_WINXP_X86, *PPEB_LDR_DATA_WINXP_X86;



#ifdef _WIN64
#define PPEB_LDR_DATA   PPEB_LDR_DATA_WIN7_X64
#define PEB_LDR_DATA    PEB_LDR_DATA_WIN7_X64
#else   
#define PPEB_LDR_DATA   PPEB_LDR_DATA_WINXP_X86
#define PEB_LDR_DATA    PEB_LDR_DATA_WINXP_X86
#endif

typedef struct _CURDIR
{
    UNICODE_STRING DosPath;
    HANDLE Handle;
} CURDIR, *PCURDIR;


typedef struct _RTL_USER_PROCESS_PARAMETERS_WINXP_X86 {
    UINT32 MaximumLength;
    UINT32 Length;
    UINT32 Flags;
    UINT32 DebugFlags;
    HANDLE ConsoleHandle;
    UINT32 ConsoleFlags;
    HANDLE StandardInput;
    HANDLE StandardOutput;
    HANDLE StandardError;
    CURDIR CurrentDirectory;        // ProcessParameters
    UNICODE_STRING DllPath;         // ProcessParameters
    UNICODE_STRING ImagePathName;   // ProcessParameters
    UNICODE_STRING CommandLine;     // ProcessParameters
    PVOID   Environment;
    UINT32    StartingX;
    UINT32    StartingY;
    UINT32    CountX;
    UINT32    CountY;
    UINT32    CountCharsX;
    UINT32    CountCharsY;
    UINT32    FillAttribute;
    UINT32    WindowFlags;
    UINT32    ShowWindowFlags;
    UNICODE_STRING    WindowTitle;
    UNICODE_STRING    DesktopInfo;
    UNICODE_STRING    ShellInfo;
    UNICODE_STRING    RuntimeData;
    UINT32    CurrentDirectores[8];
}RTL_USER_PROCESS_PARAMETERS_WINXP_X86, *PRTL_USER_PROCESS_PARAMETERS_WINXP_X86;


typedef struct _RTL_USER_PROCESS_PARAMETERS_WIN7_X64 {
    UINT32 MaximumLength;
    UINT32 Length;
    UINT32 Flags;
    UINT32 DebugFlags;
    HANDLE ConsoleHandle;
    UINT32  ConsoleFlags;
    HANDLE StandardInput;
    HANDLE StandardOutput;
    HANDLE StandardError;
    CURDIR CurrentDirectory;        // ProcessParameters
    UNICODE_STRING DllPath;         // ProcessParameters
    UNICODE_STRING ImagePathName;   // ProcessParameters
    UNICODE_STRING CommandLine;     // ProcessParameters
    PVOID   Environment;
    UINT32    StartingX;
    UINT32    StartingY;
    UINT32    CountX;
    UINT32    CountY;
    UINT32    CountCharsX;
    UINT32    CountCharsY;
    UINT32    FillAttribute;
    UINT32    WindowFlags;
    UINT32    ShowWindowFlags;
    UNICODE_STRING    WindowTitle;
    UNICODE_STRING    DesktopInfo;
    UNICODE_STRING    ShellInfo;
    UNICODE_STRING    RuntimeData;
    UINT32    CurrentDirectores[8];
    UINT64  EnvironmentSize;
    UINT64  EnvironmentVersion;
}RTL_USER_PROCESS_PARAMETERS_WIN7_X64, *PRTL_USER_PROCESS_PARAMETERS_WIN7_X64;


#ifdef _WIN64
#define PRTL_USER_PROCESS_PARAMETERS    PRTL_USER_PROCESS_PARAMETERS_WIN7_X64
#define RTL_USER_PROCESS_PARAMETERS        RTL_USER_PROCESS_PARAMETERS_WIN7_X64
#else   
#define PRTL_USER_PROCESS_PARAMETERS    PRTL_USER_PROCESS_PARAMETERS_WINXP_X86
#define RTL_USER_PROCESS_PARAMETERS        RTL_USER_PROCESS_PARAMETERS_WINXP_X86
#endif


#define GDI_HANDLE_BUFFER_SIZE32 34
#define GDI_HANDLE_BUFFER_SIZE64 60
#ifndef _WIN64
#define GDI_HANDLE_BUFFER_SIZE GDI_HANDLE_BUFFER_SIZE32
#else
#define GDI_HANDLE_BUFFER_SIZE GDI_HANDLE_BUFFER_SIZE64
#endif

typedef UINT32 GDI_HANDLE_BUFFER[GDI_HANDLE_BUFFER_SIZE];

// PEB结构
typedef struct _PEB
{
    BOOLEAN InheritedAddressSpace;
    BOOLEAN ReadImageFileExecOptions;
    BOOLEAN BeingDebugged;
    union
    {
        BOOLEAN BitField;
        struct
        {
            BOOLEAN ImageUsesLargePages : 1;
            BOOLEAN IsProtectedProcess : 1;
            BOOLEAN IsLegacyProcess : 1;
            BOOLEAN IsImageDynamicallyRelocated : 1;
            BOOLEAN SkipPatchingUser32Forwarders : 1;
            BOOLEAN IsPackagedProcess : 1;
            BOOLEAN IsAppContainer : 1;
            BOOLEAN SpareBits : 1;
        };
    };
    HANDLE Mutant;
    PVOID ImageBaseAddress;
    PPEB_LDR_DATA Ldr;
    PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
    PVOID SubSystemData;
    PVOID ProcessHeap;
    PRTL_CRITICAL_SECTION FastPebLock;
    PVOID AtlThunkSListPtr;
    PVOID IFEOKey;
    union
    {
        UINT32 CrossProcessFlags;
        struct
        {
            UINT32 ProcessInJob : 1;
            UINT32 ProcessInitializing : 1;
            UINT32 ProcessUsingVEH : 1;
            UINT32 ProcessUsingVCH : 1;
            UINT32 ProcessUsingFTH : 1;
            UINT32 ReservedBits0 : 27;
        };
        UINT32 EnvironmentUpdateCount;
    };
    union
    {
        PVOID KernelCallbackTable;
        PVOID UserSharedInfoPtr;
    };
    UINT32 SystemReserved[1];
    UINT32 AtlThunkSListPtr32;
    PVOID ApiSetMap;
    UINT32 TlsExpansionCounter;
    PVOID TlsBitmap;
    UINT32 TlsBitmapBits[2];
    PVOID ReadOnlySharedMemoryBase;
    PVOID HotpatchInformation;
    PVOID* ReadOnlyStaticServerData;
    PVOID AnsiCodePageData;
    PVOID OemCodePageData;
    PVOID UnicodeCaseTableData;
    UINT32 NumberOfProcessors;
    UINT32 NtGlobalFlag;
    LARGE_INTEGER CriticalSectionTimeout;
    SIZE_T HeapSegmentReserve;
    SIZE_T HeapSegmentCommit;
    SIZE_T HeapDeCommitTotalFreeThreshold;
    SIZE_T HeapDeCommitFreeBlockThreshold;
    UINT32 NumberOfHeaps;
    UINT32 MaximumNumberOfHeaps;
    PVOID* ProcessHeaps;
    PVOID GdiSharedHandleTable;
    PVOID ProcessStarterHelper;
    UINT32 GdiDCAttributeList;
    PRTL_CRITICAL_SECTION LoaderLock;
    UINT32 OSMajorVersion;
    UINT32 OSMinorVersion;
    UINT16 OSBuildNumber;
    UINT16 OSCSDVersion;
    UINT32 OSPlatformId;
    UINT32 ImageSubsystem;
    UINT32 ImageSubsystemMajorVersion;
    UINT32 ImageSubsystemMinorVersion;
    UINT_PTR ImageProcessAffinityMask;
    GDI_HANDLE_BUFFER GdiHandleBuffer;
    PVOID PostProcessInitRoutine;
    PVOID TlsExpansionBitmap;
    UINT32 TlsExpansionBitmapBits[32];
    UINT32 SessionId;
    ULARGE_INTEGER AppCompatFlags;
    ULARGE_INTEGER AppCompatFlagsUser;
    PVOID pShimData;
    PVOID AppCompatInfo;
    UNICODE_STRING CSDVersion;
    PVOID ActivationContextData;
    PVOID ProcessAssemblyStorageMap;
    PVOID SystemDefaultActivationContextData;
    PVOID SystemAssemblyStorageMap;
    SIZE_T MinimumStackCommit;
    PVOID* FlsCallback;
    LIST_ENTRY FlsListHead;
    PVOID FlsBitmap;
    UINT32 FlsBitmapBits[FLS_MAXIMUM_AVAILABLE / (sizeof(UINT32) * 8)];
    UINT32 FlsHighIndex;
    PVOID WerRegistrationData;
    PVOID WerShipAssertPtr;
    PVOID pContextData;
    PVOID pImageHeaderHash;
    union
    {
        UINT32 TracingFlags;
        struct
        {
            UINT32 HeapTracingEnabled : 1;
            UINT32 CritSecTracingEnabled : 1;
            UINT32 LibLoaderTracingEnabled : 1;
            UINT32 SpareTracingBits : 29;
        };
    };
    UINT64 CsrServerReadOnlySharedMemoryBase;
} PEB, *PPEB;


// Ldr 三根链表结构
typedef struct _LDR_DATA_TABLE_ENTRY {
    LIST_ENTRY InLoadOrderLinks;
    LIST_ENTRY InMemoryOrderLinks;
    LIST_ENTRY InInitializationOrderLinks;
    PVOID DllBase;
    PVOID EntryPoint;
    UINT32 SizeOfImage;
    UNICODE_STRING FullDllName;
    UNICODE_STRING BaseDllName;
    UINT32 Flags;
    UINT16 LoadCount;
    UINT16 TlsIndex;
    union {
        LIST_ENTRY HashLinks;
        struct {
            PVOID SectionPointer;
            UINT32 CheckSum;
        };
    };
    union {
        struct {
            UINT32 TimeDateStamp;
        };
        struct {
            PVOID LoadedImports;
        };
    };
    struct _ACTIVATION_CONTEXT * EntryPointActivationContext;

    PVOID PatchInformation;

} LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY;

typedef const struct _LDR_DATA_TABLE_ENTRY *PCLDR_DATA_TABLE_ENTRY;


LOADREMOTEDLL_API UINT_PTR WINAPI LoadDllByOEP(PVOID lParam);
// LoadRemoteDll.cpp

// LoadRemoteDll.cpp : 定义 DLL 应用程序的导出函数。
//

#include "stdafx.h"
#include "LoadRemoteDll.h"

#pragma intrinsic(_ReturnAddress)

__declspec(noinline)
UINT_PTR caller()
{
    return (UINT_PTR)_ReturnAddress();        // #include <intrin.h>
}

typedef
HMODULE
(WINAPI * pfnLoadLibraryA)(LPCSTR lpLibFileName);

typedef
FARPROC
(WINAPI * pfnGetProcAddress)(HMODULE hModule, LPCSTR lpProcName);

typedef
LPVOID
(WINAPI * pfnVirtualAlloc)(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect);

typedef
LONG    // NTSTATUS
(NTAPI * pfnNtFlushInstructionCache)(HANDLE ProcessHandle, PVOID BaseAddress, SIZE_T Length);

typedef
BOOL
(APIENTRY * pfnDllMain)(HMODULE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved);


LOADREMOTEDLL_API UINT_PTR WINAPI LoadDllByOEP(PVOID lParam)
{

    UINT_PTR            LibraryAddress = 0;

    PIMAGE_DOS_HEADER    DosHeader = NULL;
    PIMAGE_NT_HEADERS    NtHeader = NULL;

    pfnLoadLibraryA                LoadLibraryAAddress = NULL;
    pfnGetProcAddress            GetProcAddressAddress = NULL;
    pfnVirtualAlloc                VirtualAllocAddress = NULL;
    pfnNtFlushInstructionCache    NtFlushInstructionCacheAddress = NULL;


    LibraryAddress = caller();        // 获得下一步指令的地址,其实就是为了获得当前指令地址,为后面寻找PE头提供起点
    DosHeader = (PIMAGE_DOS_HEADER)LibraryAddress;

    while (TRUE)
    {
        if (DosHeader->e_magic == IMAGE_DOS_SIGNATURE &&
            DosHeader->e_lfanew >= sizeof(IMAGE_DOS_HEADER) &&
            DosHeader->e_lfanew < 1024)
        {
            NtHeader = (PIMAGE_NT_HEADERS)((PUINT8)LibraryAddress + DosHeader->e_lfanew);
            if (NtHeader->Signature == IMAGE_NT_SIGNATURE)
            {
                break;
            }
        }
        LibraryAddress--;
        DosHeader = (PIMAGE_DOS_HEADER)LibraryAddress;
    }

    // 获得PEB
#ifdef _WIN64
    PPEB Peb = (PPEB)__readgsqword(0x60);
#else
    PPEB Peb = (PPEB)__readfsdword(0x30);
#endif

    PPEB_LDR_DATA Ldr = Peb->Ldr;

    // 1.从Dll导出表中获取函数地址

    for (PLIST_ENTRY TravelListEntry = (PLIST_ENTRY)Ldr->InLoadOrderModuleList.Flink;
        TravelListEntry != &Ldr->InLoadOrderModuleList;        // 空头节点
        TravelListEntry = TravelListEntry->Flink)

    {
        PLDR_DATA_TABLE_ENTRY    LdrDataTableEntry = (PLDR_DATA_TABLE_ENTRY)TravelListEntry;

        UINT32    FunctionCount = 0;

        //        WCHAR*    DllName = (WCHAR*)LdrDataTableEntry->BaseDllName.Buffer;

        UINT_PTR    DllName = (UINT_PTR)LdrDataTableEntry->BaseDllName.Buffer;

        UINT32    DllLength = LdrDataTableEntry->BaseDllName.Length;

        UINT_PTR    DllBaseAddress = (UINT_PTR)LdrDataTableEntry->DllBase;

        DosHeader = (PIMAGE_DOS_HEADER)DllBaseAddress;
        NtHeader = (PIMAGE_NT_HEADERS)((PUINT8)DllBaseAddress + DosHeader->e_lfanew);

        IMAGE_DATA_DIRECTORY    ExportDataDirectory = (IMAGE_DATA_DIRECTORY)(NtHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]);
        PIMAGE_EXPORT_DIRECTORY    ExportDirectory = (PIMAGE_EXPORT_DIRECTORY)((PUINT8)DllBaseAddress + ExportDataDirectory.VirtualAddress);
        PUINT32                    AddressOfFunctions = (PUINT32)((PUINT8)DllBaseAddress + ExportDirectory->AddressOfFunctions);
        PUINT32                    AddressOfNames = (PUINT32)((PUINT8)DllBaseAddress + ExportDirectory->AddressOfNames);
        PUINT16                    AddressOfNameOrdinals = (PUINT16)((PUINT8)DllBaseAddress + ExportDirectory->AddressOfNameOrdinals);

        UINT16                    Ordinal = 0;
        UINT_PTR                ExportFunctionAddress = 0;

        UINT32                    HashValue = 0;

        // 将Dll名称转换成Hash值
        do
        {
            HashValue = ror((UINT32)HashValue);

            if (*((PUINT8)DllName) >= 'a')
            {
                HashValue += *((PUINT8)DllName) - 0x20;
            }
            else
            {
                HashValue += *((PUINT8)DllName);
            }
            DllName++;
        } while (--DllLength);



        if (HashValue == KERNEL32DLL_HASH)
        {
            FunctionCount = 3;

            for (INT i = 0; i < ExportDirectory->NumberOfFunctions; i++)
            {
                if (FunctionCount == 0)
                {
                    break;
                }

                CHAR* szExportFunctionName = (CHAR*)((PUINT8)DllBaseAddress + AddressOfNames[i]);

                HashValue = hash(szExportFunctionName);

                if (HashValue == LOADLIBRARYA_HASH)
                {
                    Ordinal = AddressOfNameOrdinals[i];
                    LoadLibraryAAddress = (pfnLoadLibraryA)((PUINT8)DllBaseAddress + AddressOfFunctions[Ordinal]);
                    FunctionCount--;
                }
                else if (HashValue == GETPROCADDRESS_HASH)
                {
                    Ordinal = AddressOfNameOrdinals[i];
                    GetProcAddressAddress = (pfnGetProcAddress)((PUINT8)DllBaseAddress + AddressOfFunctions[Ordinal]);
                    FunctionCount--;
                }
                else if (HashValue == VIRTUALALLOC_HASH)
                {
                    Ordinal = AddressOfNameOrdinals[i];
                    VirtualAllocAddress = (pfnVirtualAlloc)((PUINT8)DllBaseAddress + AddressOfFunctions[Ordinal]);
                    FunctionCount--;
                }
            }
        }
        else if (HashValue == NTDLLDLL_HASH)
        {
            FunctionCount = 1;

            for (INT i = 0; i < ExportDirectory->NumberOfFunctions; i++)
            {
                if (FunctionCount == 0)
                {
                    break;
                }

                CHAR* szExportFunctionName = (CHAR*)((PUINT8)DllBaseAddress + AddressOfNames[i]);

                HashValue = hash(szExportFunctionName);

                if (HashValue == NTFLUSHINSTRUCTIONCACHE_HASH)
                {
                    Ordinal = AddressOfNameOrdinals[i];
                    NtFlushInstructionCacheAddress = (pfnNtFlushInstructionCache)((PUINT8)DllBaseAddress + AddressOfFunctions[Ordinal]);
                    FunctionCount--;
                }
            }
        }


        if (LoadLibraryAAddress != NULL &&
            GetProcAddressAddress != NULL &&
            VirtualAllocAddress != NULL &&
            NtFlushInstructionCacheAddress != NULL)
        {
            break;
        }
    }

    // 2.申请内存,重新加载我们的Dll

    // 再次更新DosHeader和NtHeader
    DosHeader = (PIMAGE_DOS_HEADER)LibraryAddress;
    NtHeader = (PIMAGE_NT_HEADERS)((PUINT8)LibraryAddress + DosHeader->e_lfanew);

    // 重新申请内存(SizeOfImage就是PE在内存中的大小)

    /*    _asm
    {
    int 3;
    }
    */
    // 这个自己重新申请的头指针不敢随便移动,使用一个变量来替代
    UINT_PTR NewBaseAddress = (UINT_PTR)VirtualAllocAddress(NULL, NtHeader->OptionalHeader.SizeOfImage, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
    UINT_PTR OldPtr = LibraryAddress;
    UINT_PTR BasePtr = NewBaseAddress;


    // 2.1首先拷贝头 + 节表
    UINT32    SizeOfHeaders = NtHeader->OptionalHeader.SizeOfHeaders;
    while (SizeOfHeaders--)
    {
        *(PUINT8)BasePtr++ = *(PUINT8)OldPtr++;
    }
    //    memcpy((PVOID)NewBaseAddress, (PVOID)LibraryAddress, NtHeader->OptionalHeader.SizeOfHeaders);

    /*
    PIMAGE_SECTION_HEADER    SectionHeader = (PIMAGE_SECTION_HEADER)((PUINT8)&NtHeader->OptionalHeader + NtHeader->FileHeader.SizeOfOptionalHeader);
    UINT32                    NumberOfSections = NtHeader->FileHeader.NumberOfSections;
    while (NumberOfSections--)
    {
        UINT_PTR    NewSectionAddress = (UINT_PTR)((PUINT8)NewBaseAddress + SectionHeader->VirtualAddress);
        UINT_PTR    OldSectionAddress = (UINT_PTR)((PUINT8)LibraryAddress + SectionHeader->PointerToRawData);
        UINT32 SizeOfRawData = SectionHeader->SizeOfRawData;
        while (SizeOfRawData--)
        {
            *(PUINT8)NewSectionAddress++ = *(PUINT8)OldSectionAddress++;
        }
        SectionHeader = (PIMAGE_SECTION_HEADER)((PUINT8)SectionHeader + sizeof(IMAGE_SECTION_HEADER));
    }
    */

    // 2.2拷贝节区
    PIMAGE_SECTION_HEADER    SectionHeader = IMAGE_FIRST_SECTION(NtHeader);
    for (INT i = 0; i < NtHeader->FileHeader.NumberOfSections; i++)
    {
        if (SectionHeader[i].VirtualAddress == 0 || SectionHeader[i].SizeOfRawData == 0)    // 节块里面没有数据
        {
            continue;
        }

        // 定位该节块在内存中的位置
        UINT_PTR    NewSectionAddress = (UINT_PTR)((PUINT8)NewBaseAddress + SectionHeader[i].VirtualAddress);
        UINT_PTR    OldSectionAddress = (UINT_PTR)((PUINT8)LibraryAddress + SectionHeader[i].PointerToRawData);
        // 复制节块数据到虚拟内存
        UINT32 SizeOfRawData = SectionHeader[i].SizeOfRawData;
        while (SizeOfRawData--)
        {
            *(PUINT8)NewSectionAddress++ = *(PUINT8)OldSectionAddress++;
        }
        //memcpy(SectionAddress, (PVOID)((PUINT8)LibraryAddress + SectionHeader[i].PointerToRawData), SectionHeader[i].SizeOfRawData);
    }
    
    // 2.3修正导入表(IAT)
    IMAGE_DATA_DIRECTORY        ImportDataDirectory = (IMAGE_DATA_DIRECTORY)(NtHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]);
    PIMAGE_IMPORT_DESCRIPTOR    ImportDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)((PUINT8)NewBaseAddress + ImportDataDirectory.VirtualAddress);

    /*    
    _asm
    {
        int 3;
    }
    */
/*
    while (ImportDescriptor->Characteristics != 0)
    {
        PIMAGE_THUNK_DATA    FirstThunk = (PIMAGE_THUNK_DATA)((PUINT8)NewBaseAddress + ImportDescriptor->FirstThunk);
        PIMAGE_THUNK_DATA    OriginalFirstThunk = (PIMAGE_THUNK_DATA)((PUINT8)NewBaseAddress + ImportDescriptor->OriginalFirstThunk);

        // 获取导入模块名称
        //    char    szModuleName[MAX_PATH] = { 0 };

        PCHAR    ModuleName = (PCHAR)((PUINT8)NewBaseAddress + ImportDescriptor->Name);

        HMODULE    Dll = LoadLibraryAAddress(ModuleName);

        UINT_PTR            FunctionAddress = 0;

        for (INT i = 0; OriginalFirstThunk[i].u1.Function != 0; i++)
        {
            if (IMAGE_SNAP_BY_ORDINAL(OriginalFirstThunk[i].u1.Ordinal))
            {
                FunctionAddress = (UINT_PTR)GetProcAddressAddress(Dll, MAKEINTRESOURCEA((IMAGE_ORDINAL(OriginalFirstThunk[i].u1.Ordinal))));
            }
            else
            {
                PIMAGE_IMPORT_BY_NAME    ImageImportByName = (PIMAGE_IMPORT_BY_NAME)((PUINT8)NewBaseAddress + OriginalFirstThunk[i].u1.AddressOfData);
                FunctionAddress = (UINT_PTR)GetProcAddressAddress(Dll, (CHAR*)ImageImportByName->Name);        // 通过函数名称得到函数地址
            }
            FirstThunk[i].u1.Function = FunctionAddress;
        }
        ImportDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)((PUINT8)ImportDescriptor + sizeof(IMAGE_IMPORT_DESCRIPTOR));
    }

*/
    
    for (INT i = 0; ImportDescriptor[i].Name != NULL; i++)
    {
        // 加载导入动态库
        HMODULE    Dll = LoadLibraryAAddress((const CHAR*)((PUINT8)NewBaseAddress + ImportDescriptor[i].Name));

        PIMAGE_THUNK_DATA    OriginalFirstThunk = (PIMAGE_THUNK_DATA)((PUINT8)NewBaseAddress + ImportDescriptor[i].OriginalFirstThunk);
        PIMAGE_THUNK_DATA    FirstThunk = (PIMAGE_THUNK_DATA)((PUINT8)NewBaseAddress + ImportDescriptor[i].FirstThunk);
        UINT_PTR            FunctionAddress = 0;

        // 遍历每个导入模块的函数
        for (INT j = 0; OriginalFirstThunk[j].u1.Function; j++)
        {
            if (&OriginalFirstThunk[j] && IMAGE_SNAP_BY_ORDINAL(OriginalFirstThunk[j].u1.Ordinal))
            {
                // 序号导入---->这里直接从Dll的导出表中找到函数地址
                //    FunctionAddress = (UINT_PTR)GetProcAddressAddress(Dll, MAKEINTRESOURCEA((IMAGE_ORDINAL(OriginalFirstThunk[j].u1.Ordinal))));        // 除去最高位即为序号

                DosHeader = (PIMAGE_DOS_HEADER)Dll;
                NtHeader = (PIMAGE_NT_HEADERS)((PUINT8)Dll + DosHeader->e_lfanew);

                PIMAGE_EXPORT_DIRECTORY ExportDirectory = (PIMAGE_EXPORT_DIRECTORY)((PUINT8)Dll + NtHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);

                // 导出函数地址RVA数组
                PUINT32    AddressOfFunctions = (PUINT32)((PUINT8)Dll + ExportDirectory->AddressOfFunctions);

                UINT16    Ordinal = IMAGE_ORDINAL(OriginalFirstThunk[j].u1.Ordinal - ExportDirectory->Base);        // 导出函数编号 - Base(导出函数编号的起始值) = 导出函数在函数地址表中序号

                FunctionAddress = (UINT_PTR)((PUINT8)Dll + AddressOfFunctions[Ordinal]);
            }
            else
            {
                // 名称导入
                PIMAGE_IMPORT_BY_NAME    ImageImportByName = (PIMAGE_IMPORT_BY_NAME)((PUINT8)NewBaseAddress + OriginalFirstThunk[j].u1.AddressOfData);
                FunctionAddress = (UINT_PTR)GetProcAddressAddress(Dll, (CHAR*)ImageImportByName->Name);        // 通过函数名称得到函数地址
            }
            // 更新IAT
            FirstThunk[j].u1.Function = FunctionAddress;
        }
    }



    // 2.4修正重定向表
    DosHeader = (PIMAGE_DOS_HEADER)LibraryAddress;
    NtHeader = (PIMAGE_NT_HEADERS)((PUINT8)LibraryAddress + DosHeader->e_lfanew);

    //    UINT_PTR Delta = NewBaseAddress - NtHeader->OptionalHeader.ImageBase;

    IMAGE_DATA_DIRECTORY    BaseRelocDataDirectory = (IMAGE_DATA_DIRECTORY)(NtHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]);

    // 有无重定向表
    if (BaseRelocDataDirectory.Size != 0)
    {
        PIMAGE_BASE_RELOCATION    BaseRelocation = (PIMAGE_BASE_RELOCATION)((PUINT8)NewBaseAddress + BaseRelocDataDirectory.VirtualAddress);

        while (BaseRelocation->SizeOfBlock != 0)
        {
            typedef struct _IMAGE_RELOC
            {
                UINT16    Offset : 12;        // 低12位---偏移
                UINT16    Type : 4;            // 高4位---类型
            } IMAGE_RELOC, *PIMAGE_RELOC;

            // 定位到重定位块
            PIMAGE_RELOC RelocationBlock = (PIMAGE_RELOC)((PUINT8)BaseRelocation + sizeof(IMAGE_BASE_RELOCATION));
            // 计算需要修正的重定向位项的数目
            UINT32    NumberOfRelocations = (BaseRelocation->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(UINT16);

            for (INT i = 0; i < NumberOfRelocations; i++)
            {
                if (RelocationBlock[i].Type == IMAGE_REL_BASED_DIR64)
                {
                    // 64 位
                    PUINT64    Address = (PUINT64)((PUINT8)NewBaseAddress + BaseRelocation->VirtualAddress + RelocationBlock[i].Offset);
                    UINT64    Delta = (UINT64)NewBaseAddress - NtHeader->OptionalHeader.ImageBase;
                    *Address += Delta;

                }
                else if (RelocationBlock[i].Type == IMAGE_REL_BASED_HIGHLOW)
                {
                    // 32 位
                    PUINT32    Address = (PUINT32)((PUINT8)NewBaseAddress + BaseRelocation->VirtualAddress + (RelocationBlock[i].Offset));
                    UINT32    Delta = (UINT32)NewBaseAddress - NtHeader->OptionalHeader.ImageBase;
                    *Address += Delta;
                }
            }
            // 转到下一张重定向表
            BaseRelocation = (PIMAGE_BASE_RELOCATION)((PUINT8)BaseRelocation + BaseRelocation->SizeOfBlock);
        }
    }

    // 3.获得模块OEP

    UINT_PTR AddressOfEntryPoint = (UINT_PTR)((PUINT8)NewBaseAddress + NtHeader->OptionalHeader.AddressOfEntryPoint);

    NtFlushInstructionCacheAddress(INVALID_HANDLE_VALUE, NULL, 0);

    // 调用通过OEP去调用DllMain
    ((pfnDllMain)AddressOfEntryPoint)((HMODULE)NewBaseAddress, DLL_PROCESS_ATTACH, lParam);

    /*    _asm
    {
    int 3;
    }
    */
    return AddressOfEntryPoint;
}
// dllmain.cpp : 定义 DLL 应用程序的入口点。
#include "stdafx.h"

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    {
        MessageBoxA(0, 0, 0, 0);
        break;
    }
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

0x08.总结

  也许还有我没有学习到的Ring3注入Dll的方法,正所谓,路漫漫其修远兮,吾将上下而求索!

  奉上代码下载地址:https://github.com/YouArekongqi/InjectCollection.git

 

posted @ 2016-10-30 02:52  天边的黑雪  阅读(6334)  评论(2编辑  收藏  举报