最近想注入一个shell code,但是每次写shell code挺麻烦的,就想直接注入函数,但不知道函数的大小没法分配内存。于是想到了通过反汇编的方法获取函数占用内存的大小。
原理是从函数入口往下找到ret并统计指令的数量和大小。
关键代码:
[C++] 纯文本查看 复制代码 size_t GetFuncSIze(void * addr)
{
ZyanU8* data = reinterpret_cast<ZyanU8*>(addr);
// The runtime address (instruction pointer) was chosen arbitrarily here in order to better
// visualize relative addressing. In your actual program, set this to e.g. the memory address
// that the code being disassembled was read from.
ZyanU64 runtime_address = reinterpret_cast<ZyanU64>(data);
// Loop over the instructions in our buffer.
ZyanUSize offset = 0;
ZydisDisassembledInstruction instruction;
while (ZYAN_SUCCESS(ZydisDisassembleIntel(
/* machine_mode: */ ZYDIS_MACHINE_MODE_LONG_64,
/* runtime_address: */ runtime_address,
/* buffer: */ data + offset,
/* length: */ 15,
/* instruction: */ &instruction
))) {
printf("%016" PRIX64 " %s\n", runtime_address, instruction.text);
offset += instruction.info.length; //count instruction length
runtime_address += instruction.info.length;
if (instruction.info.opcode == 0xc3) //find ret, then break
{
return offset;
}
}
return 0;
}
下面的事情就简单了,把函数复制到一篇内存,执行即可。有两点注意:
1.DEBUG模式下函数有个jmp跳转,需要找到jump后的入口
2.函数调用是相对寻址,这里使用参数传入绝对地址
运行结果
代码:https://github.com/oakboat/GetFunctionSIze
|