先创建一个被调试的pe程序,代码如下:
#include "stdafx.h"
#include <iostream>
using namespace std ;
void print(){
cout <<"hello\n" ;
}
int _tmain(int argc, _TCHAR* argv[])
{
print();
cin .get();
return 0 ;
}
反汇编,找到地址0x41151E
调试进程代码如下:
#include "stdafx.h"
#include <iostream>
using namespace std ;
#include <Windows.h>
#define BREAK_POINT1 0x41151E
void print_byte_array(BYTE* arr,int len){
for (int i=0 ;i<len;i++){
printf ("%X" ,*(arr+i));
}
printf ("\n" );
}
int _tmain(int argc, _TCHAR* argv[])
{
wchar_t cWinDir[MAX_PATH];
GetCurrentDirectory(MAX_PATH, cWinDir);
wcscat(cWinDir, _T("\\test.exe" ));
printf ("[Process Path] %S\n" ,cWinDir);
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof (si));
ZeroMemory(&pi, sizeof (pi));
if (CreateProcess(
NULL,
cWinDir,
NULL,
NULL,
false ,
DEBUG_PROCESS|DEBUG_ONLY_THIS_PROCESS,
NULL,
NULL,
&si,
&pi
)){
BYTE dwOldByte[10 ]={0xe8 };
BYTE dwINT3code[]={0xcc };
BYTE ReadBuffer[MAX_PATH]={0 };
bool whileDoFlag=true ;
cout << "[Info] create process success" << endl;
ReadProcessMemory(pi.hProcess,(LPCVOID)BREAK_POINT1 ,&dwOldByte,10 ,NULL);
printf ("[Info] " );
print_byte_array(dwOldByte,sizeof (dwOldByte)/sizeof (BYTE));
DEBUG_EVENT DBEvent;
CONTEXT Regs;
DWORD dwState,Oldpp;
Regs.ContextFlags = CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS;
while (whileDoFlag){
WaitForDebugEvent(&DBEvent,INFINITE);
dwState = DBG_EXCEPTION_NOT_HANDLED;
switch (DBEvent.dwDebugEventCode){
case CREATE_PROCESS_DEBUG_EVENT:
ReadProcessMemory(pi.hProcess,(LPCVOID)BREAK_POINT1,&dwOldByte,10 ,NULL);
WriteProcessMemory(pi.hProcess,(LPVOID)BREAK_POINT1,&dwINT3code,1 ,NULL);
dwState = DBG_CONTINUE;
break ;
case EXIT_PROCESS_DEBUG_EVENT:
whileDoFlag=false ;
break ;
case EXCEPTION_DEBUG_EVENT:
switch (DBEvent.u.Exception.ExceptionRecord.ExceptionCode){
case EXCEPTION_BREAKPOINT:{
GetThreadContext(pi.hThread,&Regs);
if (Regs.Eip==BREAK_POINT1+1 ){
Regs.Eip--;
WriteProcessMemory(pi.hProcess,(LPVOID)BREAK_POINT1,&dwOldByte,1 ,0 );
ReadProcessMemory(pi.hProcess,(LPVOID)Regs.Ebp,&ReadBuffer,1 ,0 );
cout <<ReadBuffer<<endl;
SetThreadContext(pi.hThread,&Regs);
}
dwState=DBG_CONTINUE;
break ;
}
}
break ;
}
ContinueDebugEvent(pi.dwProcessId,pi.dwThreadId,dwState);
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
else {
cerr << "[Error] failed to create process" << endl;
}
cin .get();
return 0 ;
}