#include <stdafx.h>
#include <windows.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
typedef HANDLE (*open)(LPCTSTR,DWORD,DWORD,LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE);
typedef BOOL (*read)(HANDLE,LPVOID,DWORD,LPDWORD,LPOVERLAPPED);
typedef BOOL (*write)(HANDLE,LPVOID,DWORD,LPDWORD,LPOVERLAPPED);
typedef DWORD (*func)(void*);
#define ERRERS 1
#define PATHLEN 64
#define PROLOGUE 0x23
#define FUNCOFFSET 0x44
#define STRUCTLEN sizeof(INJCODE)
#define OPENPROCESSPROITY PROCESS_CREATE_THREAD|PROCESS_QUERY_INFORMATION|PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ
struct INJCODE
{
char filePath[PATHLEN];//+0x00
func func1;//+0x40
func func2;//+0x44
};
void MinorFunc()
{
__asm
{
int 0x03;
}
}
void AfterMinorFunc()
{}
DWORD MajorFunc(void* args)
{
INJCODE* injCode;
injCode = (INJCODE*)MajorFunc;
injCode--;
(injCode->func2)(NULL);
return 0;
}
#if 0
DWORD FuncV2(void* args)
{
INJCODE* injCode;
__asm
{
call CurEip;
CurEip:
pop eax;
//指向writeFunc的起始
sub eax,PROLOGUE;
//指向堆分配的INJCODE起始
sub eax,FUNCOFFSET;
mov injCode,eax;
}
return 0;
}
#endif
DWORD AfterMajorFunc(void* args)
{
return 0;
}
INJCODE* injCode;
int main()
{
DWORD pid,dwThreadId;
DWORD writtenNum,readNum;
INJCODE* injCode;
FILE* fp = fopen("c:\\pid.txt","r+");
assert(fp);
fscanf(fp,"%d",&pid);
fclose(fp);
HANDLE remoteProgHd = OpenProcess(OPENPROCESSPROITY,FALSE,pid);
//主函数和被调用函数的长度,首先存放MajorFunc,后面紧跟着MinorFunc
DWORD funcLen = ((DWORD)AfterMajorFunc-(DWORD)MajorFunc) + ((DWORD)AfterMinorFunc-(DWORD)MinorFunc);
injCode = (INJCODE*)VirtualAllocEx(remoteProgHd,NULL,sizeof(INJCODE)+funcLen,MEM_COMMIT,PAGE_EXECUTE_READWRITE);
//INJCODE!+0x40 func1所在,存放主函数指针
DWORD Func1Addr = ((DWORD)((char*)injCode)+0x40);
INJCODE!+0x44 func2所在,存放被调函数指针
DWORD Func2Addr = ((DWORD)((char*)injCode)+0x44);
DWORD MajorFuncBase = ((DWORD)((char*)injCode)+sizeof(INJCODE));
DWORD MinorFuncBase = ((DWORD)((char*)injCode)+sizeof(INJCODE)+((DWORD)AfterMajorFunc-(DWORD)MajorFunc));
WriteProcessMemory(remoteProgHd,((char*)injCode)+0x00,"c:\\1.txt",strlen("c:\\1.txt"),&writtenNum);
//injCode!func1=MajorFunc
WriteProcessMemory(remoteProgHd,(char*)Func1Addr,&MajorFuncBase,sizeof(DWORD),&writtenNum);
//injCode!func2=MinorFunc
WriteProcessMemory(remoteProgHd,(char*)Func2Addr,&MinorFuncBase,sizeof(DWORD),&writtenNum);
//复制函数到远程进程
WriteProcessMemory(remoteProgHd,(char*)MajorFuncBase,MajorFunc,((DWORD)AfterMajorFunc-(DWORD)MajorFunc),&writtenNum);
WriteProcessMemory(remoteProgHd,(char*)MinorFuncBase,MinorFunc,((DWORD)AfterMinorFunc-(DWORD)MinorFunc),&writtenNum);
HANDLE remoteThread = CreateRemoteThread(remoteProgHd,NULL,0,(LPTHREAD_START_ROUTINE)((char*)MajorFuncBase),NULL,0,&dwThreadId);
WaitForSingleObject(remoteThread, INFINITE);
return 0;
}