欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  网络运营

Windows x86/ x64 Ring3层注入Dll总结

程序员文章站 2022-04-06 20:24:33
0x01.前言   提到dll的注入,立马能够想到的方法就有很多,比如利用远程线程、apc等等,这里我对ring3层的dll注入学习做一个总结吧。   我把注入的方法分...

0x01.前言

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

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

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

0x02.预备工作

  在涉及到注入的程序中,提升程序的权限自然是必不可少的,这里我提供了两个封装的函数,都可以用于提权。第一个是通过权限令牌来调整权限;第二个是通过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;
}

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

// 使用toolhelp系列函数
#include <tlhelp32.h>
bool getprocessidbyprocessimagename(in pwchar wzprocessimagename, out puint32 processid)
{
handle processsnapshothandle = invalid_handle_value;
processentry32 processentry32 = { 0 };
processentry32.dwsize = sizeof(processentry32); // 初始化processentry32结构
processsnapshothandle = createtoolhelp32snapshot(th32cs_snapprocess, 0); // 给系统所有的进程快照
if (processsnapshothandle == invalid_handle_value)
{
return false;
}
if (process32first(processsnapshothandle, &processentry32)) // 找到第一个
{
do
{
if (lstrcmpi(processentry32.szexefile, wzprocessimagename) == 0) // 不区分大小写
{
*processid = processentry32.th32processid;
break;
}
} while (process32next(processsnapshothandle, &processentry32));
}
closehandle(processsnapshothandle);
processsnapshothandle = invalid_handle_value;
if (*processid == 0)
{
return false;
}
return true;
}
// 使用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,已经够用了。

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

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

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.注入方法二 -- 设置线程上下背景文

  设置线程上下背景文的主要目的是让目标进程的某一线程转去执行我们的代码,然后再回来做他该做的事,而我们的代码,就是一串由汇编硬编码组成的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的方法,正所谓,路漫漫其修远兮,吾将上下而求索!

  奉上代码下载地址:https://github.com/youarekongqi/injectcollection.git

以上所述是小编给大家介绍的windows x86/ x64 ring3层注入dll总结,希望对大家有所帮助!