迎接转发,转发请注解出处: 

Windows x86/ x64 Ring3层注入Dll总结,x64ring3

0x01.前言

  提到Dll的注入,立马可以想到的措施就有成百上千,比如选取远程线程、Apc等等,那里我对Ring3层的Dll注入学习做一个计算吧。

  我把注入的点子分成六类,分别是:1.开立新线程、2.设置线程上下背景文,修改寄存器、3.布置Apc队列、4.改动注册表、5.关系窗口新闻、6.远程手动已毕LoadLibrary。

  那么上边就起来读书之旅吧!

0x02.预备工作

  在涉及到注入的次序中,提高程序的权柄自然是必需的,那里我提供了五个包裹的函数,都能够用来提权。第三个是经过权限令牌来调动权力;第四个是由此ntdll.dll的导出的未文档化函数RtlAdjustPrivilege来调整权力。

澳门金沙国际 1

// 传入参数 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;
}

权力令牌
澳门金沙国际 2

// 传入参数 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。

澳门金沙国际 3

// 使用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
澳门金沙国际 4

// 使用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,已经丰富了。

澳门金沙国际 5

// 枚举指定进程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
澳门金沙国际 6

// 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

  嗯,方今甘休,预备工作大约完工,这我们就起来正题吧!

0x03.注入方法一 — 成立新线程

  创立新线程,也就是在目标经过里,创造一个线程为大家服务,而创建线程的格局本身找到的有二种: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;
}

0x04.流入方法二 — 设置线程上下背景文

【澳门金沙国际】Windows x86/ x64 Ring3层注入Dll总计。  设置线程上下背景文的重大目标是让对象经过的某一线程转去执行我们的代码,然后再回来做他该做的事,而大家的代码,就是一串由汇编硬编码组成的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;
}

0x05.插入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;
}

0x06.修改注册表

  注册表注入算得上是大局Hook了啊,毕竟新成立的长河在加载User32.dll时,都会自动调用LoadLibrary去加载注册表中某个表项键值里写入的Dll路径。

  大家关心的这几个注册表项键是:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows
NT\CurrentVersion\Windows,大家要安装的键值是AppInit_DLLs =
“Dll完整路径”,LoadAppInit_Dlls = 1(让系统运用那几个注册表项) 

  ps:由于注入的Dll在过程创建的最初,所以在Dll中选用函数要充裕小心,因为部分库或者还没加载上。

 

int main()
{
    LSTATUS Status = 0;
    WCHAR*    wzSubKey = L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows";
    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;
}

 

0x07.挂钩窗口音信

  挂钩窗口音信使用了MS提供的一个API接口SetWindowsHookEx,他的做事原理是给带窗口的目的经过的某个线程的某个音讯挂钩上大家Dll导出的函数,一旦音信触发,则导出函数就会被调用。后面学习到的二种办法归根结蒂是调用了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;
}

// 动态库中导出函数
extern "C"
__declspec(dllexport)
VOID    Sub_1()                    // 导出函数
{
    MessageBox(0, 0, 0, 0);
}

0x08.远程手动完结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;
}

0x09.总结

  也许还有我一直不读书到的Ring3流入Dll的艺术,正所谓,路漫漫其修远兮,吾将上下而求索!

  奉上代码下载地址:

 

x86/ x64 Ring3层注入Dll总计,x64ring3
0x01.前言
提到Dll的流入,立马能够想到的法门就有广大,比如利用远程线程、Apc等等,那里我对Ri…

欢迎转发,转发请注脚出处: 

0x01.前言

0x00.前言

0x00.前言

  提到Dll的注入,立马可以想到的办法就有成百上千,比如动用远程线程、Apc等等,这里我对Ring3层的Dll注入学习做一个总括吧。

  提到Dll的注入,立马可以想到的方法就有很多,比如动用远程线程、Apc等等,那里自己对Ring3层的Dll注入学习做一个统计吧。

  提到Dll的注入,立马可以想到的艺术就有好多,比如利用远程线程、Apc等等,那里我对Ring3层的Dll注入学习做一个总计吧。

  我把注入的点子分成六类,分别是:1.创造新线程、2.装置线程上下背景文,修改寄存器、3.插入Apc队列、4.修改注册表、5.沟通窗口信息、6.远程手动完成LoadLibrary。

  我把注入的格局分成六类,分别是:1.创办新线程、2.设置线程上下背景文,修改寄存器、3.计划Apc队列、4.改动注册表、5.调换窗口新闻、6.远程手动已毕LoadLibrary。

  我把注入的章程分成六类,分别是:1.创立新线程、2.安装线程上下背景文,修改寄存器、3.安顿Apc队列、4.修改注册表、5.互换窗口音讯、6.远程手动落成LoadLibrary。

  那么下边就起来读书之旅吧!

  那么上边就起来学习之旅吧!

  那么上边就开首上学之旅吧!

0x02.预备工作

0x01.预备工作

0x01.预备工作

  在关系到注入的次第中,进步程序的权能自然是少不了的,那里我提供了三个包装的函数,都可以用于提权。第四个是通过权限令牌来调整权力;第四个是经过ntdll.dll的导出的未文档化函数RtlAdjustPrivilege来调整权力。

  在事关到注入的主次中,升高程序的权杖自然是必备的,这里自己提供了三个包裹的函数,都得以用来提权。第二个是透过权限令牌来调动权力;第三个是由此ntdll.dll的导出的未文档化函数RtlAdjustPrivilege来调整权力。

  在提到到注入的顺序中,进步程序的权限自然是不可或缺的,这里自己提供了八个包装的函数,都可以用于提权。首个是通过权限令牌来调整权力;第一个是透过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;
}

澳门金沙国际 7澳门金沙国际 8

澳门金沙国际 9澳门金沙国际 10

  紧接着,既然我们要对目标经过注入Dll,那么获得目的经过的Id是必备的啊,因为OpenProcess是任天由命会使用的,那里自己也提供了三种通过目标经过印象名称得到进度Id的主意。第一种是最普遍的利用TlHelp创立系统的历程快照;第两种是凭借Psapi枚举体系函数,不过那个主意本身已毕的有不满,32位下无法获取64位进度的Id。

// 传入参数 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_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;
}
// 使用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;
}
// 使用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;
}

权力令牌

权限令牌

  然后在比如插入Apc队列、挂起线程等等操作中,须要对目标经过的线程操作,所以取得线程Id也有必不可少,同样的自身也提供了二种通过进度Id拿到线程Id的情势。首个依然是采取TlHelp创制系统的线程快照,把具备的线程存入vector模板里(供Apc注入使用);首个是选取ZwQuerySystemInformation大法,枚举系统经过信息,那么些措施本身只回去了一个线程Id,已经够用了。

澳门金沙国际 11澳门金沙国际 12

澳门金沙国际 13澳门金沙国际 14

// 枚举指定进程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;
}

// 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;
}
// 传入参数 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;
}
// 传入参数 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

RtlAdjustPrivilege

0x03.流入方法一 — 创制新线程

  紧接着,既然大家要对目的经过注入Dll,那么得到目的经过的Id是要求的吗,因为OpenProcess是必然会利用的,那里我也提供了两种通过目的经过映像名称得到过程Id的艺术。第一种是最常见的选取TlHelp创造系统的长河快照;第三种是依靠Psapi枚举种类函数,可是这些法子本身已毕的有遗憾,32位下不可能得到64位进程的Id。

  紧接着,既然大家要对目的经过注入Dll,那么得到目的经过的Id是必不可少的啊,因为OpenProcess是早晚会利用的,那里自己也提供了二种通过目标经过印象名称得到进程Id的法子。第一种是最普遍的行使TlHelp创设系统的长河快照;第三种是凭借Psapi枚举体系函数,不过这几个方法本身达成的有不满,32位下不能得到64位过程的Id。

  创制新线程,也就是在对象经过里,创造一个线程为大家服务,而创建线程的法子本身找到的有三种:1.CreateRemoteThread;2.NtCreateThreadEx;3.RtlCreateUserThread。

澳门金沙国际 15澳门金沙国际 16

澳门金沙国际 17澳门金沙国际 18

  基本思路是:1.在对象经过内存空间申请内存;2.在刚申请的内存中写入Dll完整路径;3.创制新线程,去实施LoadLibrary,从而做到注入Dll。

// 使用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;
}
// 使用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;
}

  ps:那里直接接纳从自己加载的kernel32模块导出表中得到LoadLibrary地址,是因为相似景况下,所有进度加载这类系统库在内存中的地址一样!

TlHelp

TlHelp

  因为只是创线程所使用的函数不雷同,所以上面的代码随便松手一个创线程的手续,屏蔽其余三个,都是足以成功的,那里自己推广的是NtCreateThreadEx。

澳门金沙国际 19澳门金沙国际 20

澳门金沙国际 21澳门金沙国际 22

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;
}
// 使用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系列枚举函数

#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;
}

0x04.流入方法二 —
设置线程上下背景文

Psapi

Psapi

  设置线程上下背景文的机要目标是让对象经过的某一线程转去执行我们的代码,然后再重临做她该做的事,而我辈的代码,就是一串由汇编硬编码组成的ShellCode。

  然后在诸如插入Apc队列、挂起线程等等操作中,须求对目的经过的线程操作,所以得到线程Id也有要求,同样的本身也提供了三种通过进度Id获得线程Id的措施。第四个照旧是行使TlHelp创造系统的线程快照,把持有的线程存入vector模板里(供Apc注入使用);第三个是使用ZwQuerySystemInformation大法,枚举系统经过音信,这几个点子本身只回去了一个线程Id,已经丰硕了。

  然后在诸如插入Apc队列、挂起线程等等操作中,须要对目的经过的线程操作,所以取得线程Id也有必不可少,同样的自我也提供了三种通过进程Id得到线程Id的方法。第三个依然是采纳TlHelp成立系统的线程快照,把装有的线程存入vector模板里(供Apc注入使用);首个是应用ZwQuerySystemInformation大法,枚举系统经过新闻,那几个办法本身只回去了一个线程Id,已经丰裕了。

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

澳门金沙国际 23澳门金沙国际 24

澳门金沙国际 25澳门金沙国际 26

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

// 枚举指定进程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;
}
// 枚举指定进程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;
}
#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

TlHelp

TlHelp

  整个注入进程由那几个步骤组成:在对象经过申请内存(可实施内存) —>
填充ShellCode须求的地址码 —> 将ShellCode写入申请的内存 —>
SuspendThread(挂起线程)—>GetThreadContext(获得线程上下背景文)—>
修改Context的Eip或Rip为ShellCode首地址 —>
SetThreadContext(设置刚修改过的Context)—>
ResumeThread(恢复生机线程执行)。

澳门金沙国际 27澳门金沙国际 28

澳门金沙国际 29澳门金沙国际 30

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;
}
// 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+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;
}

0x05.插入Apc队列

ZwQuerySystemInformation

ZwQuerySystemInformation

  Ring3层的Apc注入是不太平静的,我的做法就是武力的向目标经过的享有线程的UserMode
Apc队列(线程有三个Apc队列:Kernel和User)上插入Apc对象,等待她去实施该Apc里登记的函数。而唯有当线程处于alterable状态时,才会翻动Apc队列是或不是有须求实践的挂号函数。

  嗯,近来停止,预备工作几乎完工,那大家就初步正题吧!

  嗯,方今截至,预备工作大约竣事,那大家就起来正题吧!

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

0x02.流入方法一 —
创设新线程

0x02.注入方法一 —
创造新线程

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;
}

  创造新线程,也就是在对象经过里,创建一个线程为我们服务,而成立线程的方法本身找到的有二种:1.CreateRemoteThread;2.NtCreateThreadEx;3.RtlCreateUserThread。

  制造新线程,也就是在对象经过里,成立一个线程为我们服务,而创办线程的措施本身找到的有三种:1.CreateRemoteThread;2.NtCreateThreadEx;3.RtlCreateUserThread。

0x06.改动注册表

  基本思路是:1.在对象经过内存空间申请内存;2.在刚申请的内存中写入Dll完整路径;3.创制新线程,去实施LoadLibrary,从而做到注入Dll。

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

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

  ps:那里一向动用从自己加载的kernel32模块导出表中得到LoadLibrary地址,是因为相似情状下,所有进度加载那类系统库在内存中的地址一样!

  ps:那里一贯动用从自己加载的kernel32模块导出表中得到LoadLibrary地址,是因为一般情况下,所有进程加载那类系统库在内存中的地址一样!

  大家关切的那几个注册表项键是:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows
NT\CurrentVersion\Windows,大家要设置的键值是AppInit_DLLs =
“Dll完整路径”,LoadAppInit_Dlls = 1(让系统选择这几个注册表项)

  因为只是创线程所使用的函数不雷同,所以下边的代码随便放手一个创线程的步子,屏蔽其余四个,都是足以成功的,那里自己推广的是NtCreateThreadEx。

  因为只是创线程所使用的函数不雷同,所以下边的代码随便松开一个创线程的步子,屏蔽其他多个,都是足以成功的,这里我推广的是NtCreateThreadEx。

  ps:由于注入的Dll在经过创建的初期,所以在Dll中使用函数要更加小心,因为有些库或者还没加载上。

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;
}
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;
}
int main()
{
LSTATUS Status = 0;
WCHAR* wzSubKey = L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows";
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;
}

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

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

0x07.挂钩窗口音讯

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

  设置线程上下背景文的严重性目标是让对象经过的某一线程转去执行大家的代码,然后再回去做她该做的事,而我辈的代码,就是一串由汇编硬编码组成的ShellCode。

  挂钩窗口新闻使用了MS提供的一个API接口SetWindowsHookEx,他的工作规律是给带窗口的目的经过的某部线程的某部新闻挂钩上大家Dll导出的函数,一旦新闻触发,则导出函数就会被调用。前边学习到的两种艺术追根究底是调用了LoadLibrary,而以此点子并没有。

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

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

// 注入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;
}
// 动态库中导出函数
extern "C"
__declspec(dllexport)
VOID Sub_1() // 导出函数
{
MessageBox(0, 0, 0, 0);
}

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

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

0x08.远程手动达成LoadLibrary

#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
#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

  该措施学习自github上称为ReflevtiveDllInjection,大体上分为四个部分,exe和dll,上边分别简述。

  整个注入进程由那么些步骤组成:在对象经过申请内存(可实施内存) —>
填充ShellCode需求的地址码 —> 将ShellCode写入申请的内存 —>
SuspendThread(挂起线程)—>GetThreadContext(得到线程上下背景文)—>
修改Context的Eip或Rip为ShellCode首地址 —>
SetThreadContext(设置刚修改过的Context)—>
ResumeThread(恢复生机线程执行)。

  整个注入进程由那么些手续组成:在目的经过申请内存(可进行内存) —>
填充ShellCode需求的地址码 —> 将ShellCode写入申请的内存 —>
SuspendThread(挂起线程)—>GetThreadContext(获得线程上下背景文)—>
修改Context的Eip或Rip为ShellCode首地址 —>
SetThreadContext(设置刚修改过的Context)—>
ResumeThread(苏醒线程执行)。

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

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;
}
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;
}

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

0x04.插入Apc队列

0x04.插入Apc队列

  ps:写代码时参考《Windows
PE权威指南》,对任何PE结构又有了新的认识。我有for循环性冷淡。。这份代码就全贴上了。

  Ring3层的Apc注入是不太平静的,我的做法就是暴力的向目的经过的享有线程的UserMode
Apc队列(线程有五个Apc队列:Kernel和User)上插入Apc对象,等待她去实施该Apc里登记的函数。而只有当线程处于alterable状态时,才会翻动Apc队列是或不是有亟待进行的登记函数。

  Ring3层的Apc注入是不太平静的,我的做法就是武力的向目的经过的享有线程的UserMode
Apc队列(线程有四个Apc队列:Kernel和User)上插入Apc对象,等待她去实施该Apc里登记的函数。而唯有当线程处于alterable状态时,才会翻动Apc队列是还是不是有须求履行的登记函数。

// 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;
}

  ps:正是因为不掌握哪些线程会去处理Apc,所以感觉Ring3层Apc注入不如其余形式好使,可是Ring0层Apc注入或者比较稳定的。从前测试xp和win10都成功,win7下注explorer过程总是崩溃,后来捯饬半天,发现遍历线程的时候从后往前遍历着插入就不会崩溃Orz

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

0x09.总结

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;
}
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;
}

  也许还有自己尚未读书到的Ring3注入Dll的艺术,正所谓,路漫漫其修远兮,吾将上下而求索!

0x05.修改注册表

0x05.改动注册表

  奉上代码下载地址:

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

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

如上所述是小编给咱们介绍的Windows x86/ x64
Ring3层注入Dll统计,希望对大家所有支持!

  大家关注的那一个注册表项键是:

  大家关怀的这么些注册表项键是:

你可能感兴趣的篇章:

  • Windows Server 2003 Service Pack 2 for x86 & x64
    正式版发布

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

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

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

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

  大家要设置的键值是AppInit_DLLs =
“Dll完整路径”,LoadAppInit_Dlls = 1(让系统运用那些注册表项) 

  大家要安装的键值是AppInit_DLLs =
“Dll完整路径”,LoadAppInit_Dlls = 1(让系统运用那个注册表项) 

  ps:由于注入的Dll在进度创设的早期,所以在Dll中采纳函数要极度小心,因为部分库或者还没加载上。

  ps:由于注入的Dll在进度创立的初期,所以在Dll中运用函数要格外小心,因为有些库或者还没加载上。

int main()
{
    LSTATUS Status = 0;
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

#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;
}
    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.交换窗口音信

0x06.联系窗口新闻

澳门金沙国际 ,  挂钩窗口音信使用了MS提供的一个API接口SetWindowsHookEx。

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

  他的劳作规律是给带窗口的指标经过的某部线程的某部新闻挂钩上大家Dll导出的函数,一旦信息触发,则导出函数(处理该音信的钩子程序,调用约定需求时__stdcall)就会被调用,这时还须要调用。前面学习到的两种格局归根到底是调用了LoadLibrary,而以此点子并从未。

  他的干活原理是给带窗口的对象经过的某个线程的某部新闻挂钩上大家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;
}

// 动态库中导出函数
// 注入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);

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

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

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

0x07.远程手动达成LoadLibrary

0x07.远程手动已毕LoadLibrary

  该方式学习自github上称为ReflevtiveDllInjection,大体上分为七个部分,exe和dll,下边分别简述。

  该方艺术学习自github上称之为ReflevtiveDllInjection,大体上分为五个部分,exe和dll,上面分别简述。

  exe:作为注入启动程序,在目的经过申请一块儿PAGE_EXECUTE_READWRITE内存,将Dll以文件格式直接写入目的经过内存空间中,然后拿走导出函数”LoadDllByOEP”在文件中的偏移,使用CreateRemoteThread间接让对象经过去实践LoadDllByOEP函数。

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

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

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

  ps:写代码时参考《Windows
PE权威指南》,对总体PE结构又有了新的认识。我有for循环性障碍。。那份代码就全贴上了。

  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;
}
// 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.总结

0x08.总结

  也许还有本人从未上学到的Ring3流入Dll的措施,正所谓,路漫漫其修远兮,吾将上下而求索!

  也许还有自己没有读书到的Ring3流入Dll的法子,正所谓,路漫漫其修远兮,吾将上下而求索!

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

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

 

 

相关文章