版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_19683651/article/details/79176042
先创建一个被调试的pe程序,代码如下:
// test.cpp : Defines the entry point for the console application.
//
#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
调试进程代码如下:
// main.cpp : Defines the entry point for the console application.
//
#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, // 指向一个NULL结尾的、用来指定可执行模块的宽字节字符串
cWinDir, // 字符串
NULL, // 指向一个SECURITY_ATTRIBUTES结构体,这个结构体决定是否返回的句柄可以被子进程继承。
NULL, // 如果lpProcessAttributes参数为空(NULL),那么句柄不能被继承。<同上>
false, // 指示新进程是否从调用进程处继承了句柄。
DEBUG_PROCESS|DEBUG_ONLY_THIS_PROCESS,
// 指定附加的、用来控制优先类和进程的创建的标
// CREATE_NEW_CONSOLE 新控制台打开子进程
// CREATE_SUSPENDED 子进程创建后挂起,直到调用ResumeThread函数
NULL, // 指向一个新进程的环境块。如果此参数为空,新进程使用调用进程的环境
NULL, // 指定子进程的工作路径
&si, // 决定新进程的主窗体如何显示的STARTUPINFO结构体
&pi // 接收新进程的识别信息的PROCESS_INFORMATION结构体
)){
BYTE dwOldByte[10]={0xe8};
BYTE dwINT3code[]={0xcc};
BYTE ReadBuffer[MAX_PATH]={0};
bool whileDoFlag=true;
cout << "[Info] create process success" << endl;
//从被调试进程中读取数据,打印出来的结果和test.exe反汇编中0x41151E处的opcode
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;
}