Ejemplo n.º 1
0
static BOOL tgt_process_active_close_process(struct dbg_process* pcs, BOOL kill)
{
    if (pcs == dbg_curr_process)
    {
        /* remove all set breakpoints in debuggee code */
        break_set_xpoints(FALSE);
        /* needed for single stepping (ugly).
         * should this be handled inside the server ???
         */
        be_cpu->single_step(&dbg_context, FALSE);
        if (dbg_curr_thread->in_exception)
        {
            SetThreadContext(dbg_curr_thread->handle, &dbg_context);
            ContinueDebugEvent(dbg_curr_pid, dbg_curr_tid, DBG_CONTINUE);
        }
    }
    if (kill)
    {
        TerminateProcess(pcs->handle, 0);
    }
    else
    {
        if (!DebugActiveProcessStop(pcs->pid)) return FALSE;
    }
    SymCleanup(pcs->handle);
    dbg_del_process(pcs);

    return TRUE;
}
Ejemplo n.º 2
0
BOOL My_DebugActiveProcessStop()
{
	DWORD dwProcessId=NULL;
	BOOL returnVal_Real = NULL;
	BOOL returnVal_Intercepted = NULL;

	DWORD error_Real = 0;
	DWORD error_Intercepted = 0;
	disableInterception();
	returnVal_Real = DebugActiveProcessStop (dwProcessId);
	error_Real = GetLastError();
	enableInterception();
	returnVal_Intercepted = DebugActiveProcessStop (dwProcessId);
	error_Intercepted = GetLastError();
	return ((returnVal_Real == returnVal_Intercepted) && (error_Real == error_Intercepted));
}
Ejemplo n.º 3
0
void CNBUTOJCore::ClearUp(const char *exe, const char *output, PROCESS_INFORMATION ProcInfo)
{
    string tmp;

    DebugActiveProcessStop(ProcInfo.dwProcessId);
    TerminateProcess(ProcInfo.hProcess, 0);
    CloseHandle(ProcInfo.hThread);
    CloseHandle(ProcInfo.hProcess);

    while(FileExists(exe))
    {
        tmp = string("del ") + exe;
        system(tmp.c_str());
    }

    while(FileExists(output))
    {
        tmp = string("del ") + output;
        system(tmp.c_str());
    }

    /** 删除FPC的什么什么 */
    string ofile = exe;
    ofile = ofile.substr(0, ofile.length() - 3) + ".o";
    while(FileExists(ofile.c_str()))
    {
        tmp = string("del ") + ofile.c_str();
        system(tmp.c_str());
    }

}
Ejemplo n.º 4
0
/* Detach from all inferiors.  */
static int
win32_detach (void)
{
  winapi_DebugActiveProcessStop DebugActiveProcessStop = NULL;
  winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit = NULL;
#ifdef _WIN32_WCE
  HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
#else
  HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
#endif
  DebugActiveProcessStop = GETPROCADDRESS (dll, DebugActiveProcessStop);
  DebugSetProcessKillOnExit = GETPROCADDRESS (dll, DebugSetProcessKillOnExit);

  if (DebugSetProcessKillOnExit == NULL
      || DebugActiveProcessStop == NULL)
    return -1;

  {
    struct thread_resume resume;
    resume.thread = -1;
    resume.step = 0;
    resume.sig = 0;
    resume.leave_stopped = 0;
    win32_resume (&resume);
  }

  if (!DebugActiveProcessStop (current_process_id))
    return -1;

  DebugSetProcessKillOnExit (FALSE);

  win32_clear_inferiors ();
  return 0;
}
Ejemplo n.º 5
0
Archivo: debug.c Proyecto: Disar/Kha
HL_API bool hl_debug_stop( int pid ) {
#	if defined(HL_WIN)
	BOOL b = DebugActiveProcessStop(pid);
	CleanHandles();
	return (bool)b;
#	elif defined(USE_PTRACE)
	return ptrace(PTRACE_DETACH,pid,0,0) >= 0;
#	else
	return false;
#	endif
}
Ejemplo n.º 6
0
void DbgSessionDelete (dbgSession* session) {
	if (!session)
		return;
	if (session->process.id.pid)
		DebugActiveProcessStop (session->process.id.pid);
	if (session->process.thread)
		CloseHandle ((HANDLE)session->process.thread);
	if (session->process.process)
		CloseHandle ((HANDLE)session->process.process);
	DbgSessionDeleteProc (session);
}
Ejemplo n.º 7
0
ErrorCode Process::detach() {
  prepareForDetach();

  BOOL result = DebugActiveProcessStop(_pid);
  if (!result)
    return Platform::TranslateError();

  cleanup();
  _flags &= ~kFlagAttachedProcess;

  return kSuccess;
}
Ejemplo n.º 8
0
	BOOL detach()
	{
		if (DebugActiveProcessStop(pid))
		{
			std::cout << "[*] detach, EXIT." << std::endl;
			return true;
		}
		else
		{
			std::cout << "[!] detach() error" << std::endl;
			return false;
		}
	}
Ejemplo n.º 9
0
void spwanAndHook_(char *dlltoinject,opt *options){
	STARTUPINFO         sInfo;
	PROCESS_INFORMATION pInfo;

	printf("[Info] Launching process: %s\n",options->cmdline);
	ZeroMemory(&sInfo, sizeof(sInfo));
	sInfo.cb = sizeof(sInfo);
	ZeroMemory(&pInfo, sizeof(pInfo));

	if (CreateProcess(options->cmdline, NULL, NULL, NULL, FALSE, DEBUG_ONLY_THIS_PROCESS/*CREATE_SUSPENDED*/, NULL, NULL, &sInfo, &pInfo))
	{
		char cmd[512];
		printf("[info] New pid: %d\n",pInfo.dwProcessId);
		sprintf(cmd,"EXECUTING \"%s\" HOOKING PID %d",options->cmdline,pInfo.dwProcessId);
		logger(options->ini,"injector",cmd,strlen(cmd));

		DEBUG_EVENT             debugEvent;

		do{
//			printf(">> %x\n",debugEvent.dwDebugEventCode);
		    if(!WaitForDebugEvent(&debugEvent, 1000)) break;
		    if(debugEvent.dwDebugEventCode == LOAD_DLL_DEBUG_EVENT)
		    {
//				SuspendThread(debugEvent.u.CreateProcessInfo.hThread);
//				printf("Injecting!\n");
				injecta(pInfo.dwProcessId,dlltoinject,options);
				Sleep(1000);
//				ResumeThread(debugEvent.u.CreateProcessInfo.hThread);
				DebugSetProcessKillOnExit(FALSE);
		        DebugActiveProcessStop(debugEvent.dwProcessId);
				break;
		    }
		    ContinueDebugEvent(debugEvent.dwProcessId, debugEvent.dwThreadId, DBG_CONTINUE);
		} while(1);

		/*
		if(WaitForInputIdle((void*)pInfo.hProcess,5)==WAIT_FAILED) printf("[info] Wait failed, console app? :p");
		if(options->waitKeyPress){
			printf("Press [intro] to resume process..\n");
			getchar();
		}*/
//		injecta(pInfo.dwProcessId,dlltoinject,options);
//		ResumeThread((void*)pInfo.hThread);
//		WaitForInputIdle((void*)pInfo.dwProcessId,INFINITE);
//		Sleep(100);
	    CloseHandle(pInfo.hThread);
	    CloseHandle(pInfo.hProcess);
	}else{
		printf("[Error] Unable to create the process (path not found?)\n");
	}
}
Ejemplo n.º 10
0
bool CNBUTOJCore::_ErrExit(const HANDLE hProcess, const DWORD dwProcessID, CodeState &cs, NState state, __int64 exe_time, SIZE_T exe_memory, const char *code)
{
    DebugActiveProcessStop(dwProcessID);
    TerminateProcess(hProcess, 4);
    cs.state = state;
    //cs.exe_time = exe_time;
    cs.exe_time = _GetRunTime(hProcess);
    cs.exe_memory = exe_memory;
    if(strlen(code) != 0)
    {
        strcpy(cs.err_code, code);
    }

    return false;
}
Ejemplo n.º 11
0
bool CDebugger::Detach() {
    cout << "\n[+] Detach debugger!" << endl;

    for (auto dwProcessId : m_vProcessIds) {
        cout << "[+] Detach pid: " << dwProcessId << endl;
        DebugActiveProcessStop(dwProcessId);

        // Terminate process
        HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessId);
        TerminateProcess(hProcess, 0);
    }

    m_bActive = false;
    return m_bActive;
}
Ejemplo n.º 12
0
BOOL WindowsDebugger::debugger_detach()
{
	if( !this->bAttachedToProcess ) {
		dprintflvl( 2, "Not attached to a process" );
		return FALSE;
	}

	if( DebugActiveProcessStop( this->nProcessId ) == NULL ) {
		WinError::winerror_print_last_error( __FUNCTION__ );
		dprintflvl( 2, "Unable to detach" );
		return FALSE;
	}

	this->bAttachedToProcess = FALSE;
	return TRUE;

}
Ejemplo n.º 13
0
/*
 * Release the process.  Frees the process control structure.
 * flags:
 *	PRELEASE_KILL	Terminate the process with SIGKILL.
 */
void Prelease(struct ps_prochandle *P, int flags)
{
    if (flags & PRELEASE_KILL)
        TerminateProcess(P->phandle, 1);
    else {
        if (P->flags & PGRAB_RDONLY) {
            SymCleanup(P->phandle);
            freemodules(P);
            free(P);
            return;
        }
        CloseHandle(P->event);
        DebugActiveProcessStop(P->pid);
    }
    SymCleanup(P->phandle);
    pthread_mutex_destroy(&P->mutex);
    pthread_cond_destroy(&P->cond);
    freemodules(P);
    free(P);
}
Ejemplo n.º 14
0
/* Detach from inferior PID.  */
static int
win32_detach (int pid)
{
  struct process_info *process;
  winapi_DebugActiveProcessStop DebugActiveProcessStop = NULL;
  winapi_DebugSetProcessKillOnExit DebugSetProcessKillOnExit = NULL;
#ifdef _WIN32_WCE
  HMODULE dll = GetModuleHandle (_T("COREDLL.DLL"));
#else
  HMODULE dll = GetModuleHandle (_T("KERNEL32.DLL"));
#endif
  DebugActiveProcessStop = GETPROCADDRESS (dll, DebugActiveProcessStop);
  DebugSetProcessKillOnExit = GETPROCADDRESS (dll, DebugSetProcessKillOnExit);

  if (DebugSetProcessKillOnExit == NULL
      || DebugActiveProcessStop == NULL)
    return -1;

  {
    struct thread_resume resume;
    resume.thread = minus_one_ptid;
    resume.kind = resume_continue;
    resume.sig = 0;
    win32_resume (&resume, 1);
  }

  if (!DebugActiveProcessStop (current_process_id))
    return -1;

  DebugSetProcessKillOnExit (FALSE);
  process = find_process_pid (pid);
  remove_process (process);

  win32_clear_inferiors ();
  return 0;
}
Ejemplo n.º 15
0
/* exit codes: 0 = ok, 1 = invocation error, 3 = internal error */
int main()
{
    int argc;
    int creationFlags;
    wchar_t **argv;
    wchar_t *env = 0;
    STARTUPINFOW si;
    PROCESS_INFORMATION pi;
    DEBUG_EVENT dbev;
    enum RunMode mode = Run;
    HANDLE image = NULL;

    argv = CommandLineToArgvW(GetCommandLine(), &argc);

    if (argc != ArgCount) {
        fprintf(stderr, "This is an internal helper of Qt Creator. Do not run it manually.\n");
        return 1;
    }

    /* convert message to OEM codepage */
    WideCharToMultiByte(CP_OEMCP, 0, argv[ArgMsg], -1, sleepMsg, sizeof(sleepMsg), NULL, NULL);

    /* Connect to the master, i.e. Creator. */
    if (!(qtcFd = _wfopen(argv[ArgSocket], L"w"))) {
        fprintf(stderr, "Cannot connect creator comm pipe %S: %s\n",
                argv[ArgSocket], strerror(errno));
        doExit(1);
    }

    if (*argv[ArgDir] && !SetCurrentDirectoryW(argv[ArgDir])) {
        /* Only expected error: no such file or direcotry */
        sendMsg("err:chdir %d\n", GetLastError());
        return 1;
    }

    if (*argv[ArgEnv]) {
        FILE *envFd;
        long size;
        if (!(envFd = _wfopen(argv[ArgEnv], L"rb"))) {
            fprintf(stderr, "Cannot read creator env file %S: %s\n",
                    argv[ArgEnv], strerror(errno));
            doExit(1);
        }
        fseek(envFd, 0, SEEK_END);
        size = ftell(envFd);
        rewind(envFd);
        env = malloc(size);
        if (fread(env, 1, size, envFd) != size) {
            perror("Failed to read env file");
            doExit(1);
        }
        fclose(envFd);
    }

    ZeroMemory(&pi, sizeof(pi));
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);

    creationFlags = CREATE_UNICODE_ENVIRONMENT;
    if (!wcscmp(argv[ArgAction], L"debug")) {
        mode = Debug;
    } else if (!wcscmp(argv[ArgAction], L"suspend")) {
        mode = Suspend;
    }

    switch (mode) {
    case Debug:
        creationFlags |= DEBUG_ONLY_THIS_PROCESS;
        break;
    case Suspend:
        creationFlags |= CREATE_SUSPENDED;
        break;
    default:
        break;
    }
    if (!CreateProcessW(0, argv[ArgCmdLine], 0, 0, FALSE, creationFlags, env, 0, &si, &pi)) {
        /* Only expected error: no such file or direcotry, i.e. executable not found */
        sendMsg("err:exec %d\n", GetLastError());
        doExit(1);
    }

    /* This is somewhat convoluted. What we actually want is creating a
       suspended process and letting gdb attach to it. Unfortunately,
       the Windows kernel runs amok when we attempt this.
       So instead we start a debugged process, eat all the initial
       debug events, suspend the process and detach from it. If gdb
       tries to attach *now*, everything goes smoothly. Yay. */
    if (mode == Debug) {
        do {
            if (!WaitForDebugEvent (&dbev, INFINITE))
                systemError("Cannot fetch debug event, error %d\n");
            if (dbev.dwDebugEventCode == CREATE_PROCESS_DEBUG_EVENT)
                image = dbev.u.CreateProcessInfo.hFile;
            if (dbev.dwDebugEventCode == EXCEPTION_DEBUG_EVENT) {
                /* The first exception to be delivered is a trap
                   which indicates completion of startup. */
                if (SuspendThread(pi.hThread) == (DWORD)-1)
                    systemError("Cannot suspend debugee, error %d\n");
            }
            if (!ContinueDebugEvent(dbev.dwProcessId, dbev.dwThreadId, DBG_CONTINUE))
                systemError("Cannot continue debug event, error %d\n");
        } while (dbev.dwDebugEventCode != EXCEPTION_DEBUG_EVENT);
        if (!DebugActiveProcessStop(dbev.dwProcessId))
            systemError("Cannot detach from debugee, error %d\n");
        if (image)
            CloseHandle(image);
    }

    SetConsoleCtrlHandler(ctrlHandler, TRUE);

    sendMsg("thread %d\n", pi.dwThreadId);
    sendMsg("pid %d\n", pi.dwProcessId);

    if (WaitForSingleObject(pi.hProcess, INFINITE) == WAIT_FAILED)
        systemError("Wait for debugee failed, error %d\n");
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
    free(env);
    doExit(0);
    return 0;
}
Ejemplo n.º 16
0
DWORD WINAPI DebugThread(LPVOID arg)
{
	DEBUG_EVENT evt;
	DWORD dwContinue;
	DWORD dwBPAddress = 0x44D471;
	DWORD dwBPEnd = 0x44D47C;
	DWORD dwDataRead = 0x443848;
	DWORD dwDataSucceed = 0x44384D;
	BYTE bBPAddr = 0;
	BYTE bBPEnd = 0;
	BYTE bDataRead = 0;
	BYTE bDataSucceed = 0;
	DWORD dwRead;

	DWORD dwDataLength = 0;	//[ESP + 0x10] at 0x443848
	char szName[16];		//[ESP + 0x0C] at 0x44384D
	char szHeader[8];		//[ESP + 0x08] at 0x44384D This value should "BSE 1.0\0"

	BOOL bFlag = FALSE;
	BOOL bFlag2 = FALSE;
	BOOL bAlpha = FALSE;

	CONTEXT lcContext;
	HANDLE hThread = NULL;
	HANDLE hProcess = NULL;

	LPVOID ptr, ptr2;
	BYTE *pBMPData;
	DWORD dwLength;
	BYTE *pData;

	Image *result;
//	SYSTEMTIME time;
	WCHAR str[64];

	unsigned short width;
	unsigned short height;

	szName[0] = 0;

	if (DebugActiveProcess(dwProcessID))
		SetEvent(hAttachSucceeded);

	SetEvent(hDebugInit);

	DebugSetProcessKillOnExit(FALSE);

	while (TRUE)
	{
		if (WaitForSingleObject(hDebugEnd, 0) == WAIT_OBJECT_0)
			break;

		dwContinue = DBG_CONTINUE;

		if (WaitForDebugEvent(&evt, 10))
		{
			switch (evt.dwDebugEventCode)
			{
				case CREATE_PROCESS_DEBUG_EVENT:
					bDataRead = SetSoftwareBreakpoint(evt.u.CreateProcessInfo.hProcess, dwDataRead);

					hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, evt.dwProcessId);

					CloseHandle(evt.u.CreateProcessInfo.hFile);
					break;
				case CREATE_THREAD_DEBUG_EVENT:
					break;
				case LOAD_DLL_DEBUG_EVENT:
					CloseHandle(evt.u.LoadDll.hFile);
					break;
				case EXCEPTION_DEBUG_EVENT:
					if (evt.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT)
					{
						if (evt.u.Exception.ExceptionRecord.ExceptionAddress == (PVOID)dwBPAddress)
						{
						//	if (bFlag)
						//	{
							//	MessageBeep(0);
								bAlpha = FALSE;

								hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, evt.dwThreadId);

								lcContext.ContextFlags = CONTEXT_ALL;
								GetThreadContext(hThread, &lcContext);

								ptr = (LPVOID)(lcContext.Eax + 0x08);
								ReadProcessMemory(hProcess, ptr, &pBMPData, 4, &dwRead);

								ReadProcessMemory(hProcess, (LPVOID)pBMPData, &width, 2, &dwRead);
								ReadProcessMemory(hProcess, (LPVOID)(pBMPData + 2), &height, 2, &dwRead);
								dwLength = width * height * 4;

								pData = (BYTE *)calloc(dwLength, sizeof(BYTE));
								if (pData)
								{
									wsprintf(str, L"[%dx%d] %S", width, height, szName);
									
									if (SendMessage(hListLayer, LB_FINDSTRINGEXACT, -1, (LPARAM)str) == LB_ERR)
									{
										SendMessage(hListLayer, LB_INSERTSTRING, 0, (LPARAM)str);

										ReadProcessMemory(hProcess, (LPVOID)(pBMPData + 0x10), pData, dwLength, &dwRead);
										result = (Image *)calloc(1, sizeof(Image));

										result->width = width;
										result->height = height;
										result->data = (PIXEL *)pData;

										//Is this bitmap has no alpha channel (all alpha channel == 0)
										for (int i = 0; i < width * height; i++)
											if (result->data[i].a != 0x00)
											{
												bAlpha = TRUE;
												break;
											}

										//Set alpha channel
										if (!bAlpha)
											for (int i = 0; i < width * height; i++)
												result->data[i].a = 0xFF;

										//Insert Decoded Image to List
										SendMessage(hListLayer, LB_SETITEMDATA, 0, (LPARAM)result);
									}
								}

								MoveEIPBack(hThread);
								bBPEnd = SetSoftwareBreakpoint(hProcess, dwBPEnd);
								ResetSoftwareBreakpoint(hProcess, dwBPAddress, bBPAddr);

								CloseHandle(hThread);
						//	}
						//	else
								bFlag = TRUE;
						}
						else if (evt.u.Exception.ExceptionRecord.ExceptionAddress == (PVOID)dwBPEnd)
						{
						//	if (bFlag2)
						//	{
								hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, evt.dwThreadId);

								MoveEIPBack(hThread);
								bDataRead = SetSoftwareBreakpoint(hProcess, dwDataRead);
								ResetSoftwareBreakpoint(hProcess, dwBPEnd, bBPEnd);

								CloseHandle(hThread);
						//	}
						//	else
								bFlag2 = TRUE;
						}
						else if (evt.u.Exception.ExceptionRecord.ExceptionAddress == (PVOID)dwDataRead)
						{
							hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, evt.dwThreadId);

							lcContext.ContextFlags = CONTEXT_ALL;
							GetThreadContext(hThread, &lcContext);

							ptr = (LPVOID)(lcContext.Esp + 0x10);
							ReadProcessMemory(hProcess, ptr, &dwDataLength, 4, &dwRead);

							MoveEIPBack(hThread);
							bDataSucceed = SetSoftwareBreakpoint(hProcess, dwDataSucceed);
							ResetSoftwareBreakpoint(hProcess, dwDataRead, bDataRead);

							CloseHandle(hThread);
						}
						else if (evt.u.Exception.ExceptionRecord.ExceptionAddress == (PVOID)dwDataSucceed)
						{
							hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, evt.dwThreadId);

							MoveEIPBack(hThread);

							if (dwDataLength)
							{
								lcContext.ContextFlags = CONTEXT_ALL;
								GetThreadContext(hThread, &lcContext);

								if (lcContext.Eax == dwDataLength)
								{
									ptr = (LPVOID)(lcContext.Esp + 0x08);
									ReadProcessMemory(hProcess, ptr, &ptr2, 4, &dwRead);
									ReadProcessMemory(hProcess, ptr2, &szHeader, 8, &dwRead);

									if (strncmp(szHeader, "BSE 1.0\0", 8) == 0)
									{
										//Read Succeed
										ptr = (LPVOID)(lcContext.Esp + 0x0C);
										ReadProcessMemory(hProcess, ptr, &ptr2, 4, &dwRead);
										ReadProcessMemory(hProcess, ptr2, &szName, 16, &dwRead);

										bBPAddr = SetSoftwareBreakpoint(hProcess, dwBPAddress);
									}
									else
										bDataRead = SetSoftwareBreakpoint(hProcess, dwDataRead);
								}
								else
									bDataRead = SetSoftwareBreakpoint(hProcess, dwDataRead);
							}
							else
								bDataRead = SetSoftwareBreakpoint(hProcess, dwDataRead);

							ResetSoftwareBreakpoint(hProcess, dwDataSucceed, bDataSucceed);

							CloseHandle(hThread);
						}
					}
					else if (evt.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_SINGLE_STEP)
					{
					}
					else
						dwContinue = DBG_EXCEPTION_NOT_HANDLED;
					break;
				case EXIT_PROCESS_DEBUG_EVENT:
					SetEvent(hDebugEnd);
					break;
				default:
					dwContinue = DBG_EXCEPTION_NOT_HANDLED;
					break;
			}

			ContinueDebugEvent(evt.dwProcessId, evt.dwThreadId, dwContinue);
		}
	}
	if (bDataRead)
		ResetSoftwareBreakpoint(hProcess, dwDataRead, bDataRead);
	if (bDataSucceed)
		ResetSoftwareBreakpoint(hProcess, dwDataSucceed, bDataSucceed);
	if (bBPAddr)
		ResetSoftwareBreakpoint(hProcess, dwBPAddress, bBPAddr);
	if (bBPEnd)
		ResetSoftwareBreakpoint(hProcess, dwBPEnd, bBPEnd);

	if (hProcess)
		CloseHandle(hProcess);

	DebugActiveProcessStop(dwProcessID);

	return 0;
}
Ejemplo n.º 17
0
void resume(DWORD processId)
{
	DebugActiveProcessStop(processId);
}
Ejemplo n.º 18
0
	bool debugthread::stopdebug()
	{
	DebugActiveProcessStop(pars.pi.dwProcessId);
	return true;
	}
Ejemplo n.º 19
0
void DebuggerThread::run()
{
	if ( !DebugActiveProcess( debugger->processId ) )
		return;

	DebugSetProcessKillOnExit( FALSE );
	HANDLE hImageFile = NULL;
	//bool go = false;
	//HANDLE target_thread = 0;

	while( !commit_suicide )
	{
		DEBUG_EVENT dbgEvent;
		if ( !WaitForDebugEvent( &dbgEvent, 100 ) )
		{
			//if ( go )
			//{
			//	DWORD t0 = GetTickCount();
			//	CONTEXT threadcontext;
			//	threadcontext.ContextFlags = CONTEXT_i386 | CONTEXT_CONTROL;

			//	HRESULT result = SuspendThread(target_thread);

			//	if(result == 0xffffffff)
			//		__asm int 3

			//	SetThreadPriority( target_thread, THREAD_PRIORITY_TIME_CRITICAL );
			//	result = GetThreadContext(target_thread, &threadcontext);
			//	SetThreadPriority( target_thread, THREAD_PRIORITY_NORMAL );

			//	ResumeThread(target_thread);
			//	
			//	DWORD t1 = GetTickCount();
			//	char buf[256];
			//	sprintf(buf, "%08x - %ims\n", t1, t1 - t0);
			//	OutputDebugString(buf);
			//}
	
			DWORD err = GetLastError();
			continue;
		}

		WaitForSingleObject( hMutex, INFINITE );
		switch (dbgEvent.dwDebugEventCode) 
		{ 
		case EXCEPTION_DEBUG_EVENT:
			SetEvent( readyEvent );
			//go = true;
			break;

		case CREATE_THREAD_DEBUG_EVENT: 
			debugger->hThreads.push_back( ThreadInfo( dbgEvent.dwThreadId, dbgEvent.u.CreateThread.hThread ) );
			break;

		case CREATE_PROCESS_DEBUG_EVENT:
			debugger->hProcess = dbgEvent.u.CreateProcessInfo.hProcess;
			hImageFile = dbgEvent.u.CreateProcessInfo.hFile;
			debugger->hThreads.push_back( ThreadInfo( dbgEvent.dwThreadId, dbgEvent.u.CreateProcessInfo.hThread ) );
			//target_thread = dbgEvent.u.CreateProcessInfo.hThread;
			break;

		case EXIT_THREAD_DEBUG_EVENT: 
			// Display the thread's exit code. 
			break;

		case EXIT_PROCESS_DEBUG_EVENT: 
			// Display the process's exit code. 
			break;

		case LOAD_DLL_DEBUG_EVENT: 
			// Read the debugging information included in the newly 
			// loaded DLL. Be sure to close the handle to the loaded DLL 
			// with CloseHandle.
			break;

		case UNLOAD_DLL_DEBUG_EVENT: 
			// Display a message that the DLL has been unloaded. 
			break;

		case OUTPUT_DEBUG_STRING_EVENT: 
			// Display the output debugging string. 
			break;

		} 

		ReleaseMutex( hMutex );
		ContinueDebugEvent( dbgEvent.dwProcessId, dbgEvent.dwThreadId, DBG_EXCEPTION_NOT_HANDLED );
	}

	if ( hImageFile )
		CloseHandle( hImageFile );

	DebugActiveProcessStop( debugger->processId );
}
Ejemplo n.º 20
0
	bool Debugger::Detach()
	{
		return !!DebugActiveProcessStop(_mainProcess.dwProcessId);
	}
Ejemplo n.º 21
0
// cette fonction teste si l'entrée fait planter le programme
DWORD FuzzwinAlgorithm::debugTarget(CInput *pNewInput) 
{
    // Execution de la cible en mode debug pour récupérer la cause et l'emplacement de l'erreur
    // source http://msdn.microsoft.com/en-us/library/windows/desktop/ms681675(v=vs.85).aspx
    STARTUPINFO         si; 
    PROCESS_INFORMATION pi;
    DEBUG_EVENT         e;
    
    ZeroMemory(&si, sizeof(si));
    ZeroMemory(&pi, sizeof(pi));
    ZeroMemory(&e,  sizeof(e));
    si.cb = sizeof(si);
    
    std::string cmdLineDebug(this->getCmdLineDebug(pNewInput));	
    DWORD returnCode    = 0; 
    DWORD exceptionCode = 0;
    bool  continueDebug  = true; // variable de sortie de boucle infinie
        
    BOOL bSuccess = CreateProcess(
        nullptr,            // passage des arguments par ligne de commande
        (LPSTR) cmdLineDebug.c_str(),
        nullptr, nullptr,   // attributs de processus et de thread par défaut
        FALSE,              // pas d'héritage des handles
        DEBUG_PROCESS | CREATE_NO_WINDOW, // mode DEBUG, pas de fenetres
        nullptr, nullptr,   // Environnement et repertoire de travail par défaut
        &si, &pi);          // Infos en entrée et en sortie
    
    if (!bSuccess)
    {
        this->logTimeStamp();
        this->log("    Erreur createProcess Debug");
        this->logEndOfLine();
        return 0; // fin de la procédure prématurément
    }

    // activation du "timer" pour stopper le debuggage au bout du temps spécifié
    if (_hTimer)
    {
        // transformation secondes => intervalles de 100 nanosecondes ( x (-10 000 000))
        LARGE_INTEGER liDueTime;
        liDueTime.QuadPart = _maxExecutionTime * (-10000000LL);

        if (!SetWaitableTimer(_hTimer,
            &liDueTime, // temps d'attente
            0,          // pas de périodicité
            &FuzzwinAlgorithm::timerExpired,    // fonction appelée lors de l'expiration
            &pi.hProcess, // argument passé : handle du processus en cours de debuggage
            0)) // peu importe le 'resume'
        {
            this->logTimeStamp();
            this->log("    Erreur Lancement du timer !!");
            this->logEndOfLine();
            return 0;
        }
    }

    /**********************/
    /* DEBUT DU DEBUGGAGE */
    /**********************/

    while (continueDebug)	
    {
        WaitForDebugEvent(&e, INFINITE);
        switch (e.dwDebugEventCode) 
        { 
        
        // Exception rencontrée
        case EXCEPTION_DEBUG_EVENT:
            
            // récupération du code d'exception rencontré
            exceptionCode = e.u.Exception.ExceptionRecord.ExceptionCode;
            // cas particulier : breakpoint de début d'exécution du programme
            if (EXCEPTION_BREAKPOINT == exceptionCode) 
            {
                // acquitter
                ContinueDebugEvent(e.dwProcessId, e.dwThreadId, DBG_CONTINUE); 
                break;
            }
            else // véritable exception rencontrée
            { 
                PVOID exceptionAddr = e.u.Exception.ExceptionRecord.ExceptionAddress;
                char details[64];

                sprintf(&details[0], " Adresse 0x%p - Code %08X", exceptionAddr, exceptionCode);
                
                this->logEndOfLine();
                this->log(std::string(60, '*'));
                this->logEndOfLine();

                this->logTimeStamp();
                this->log(" @@@ ERREUR @@@ Fichier " + pNewInput->getFileName());      
                this->logEndOfLine();

                this->logTimeStamp();
                this->log(&details[0]);
                this->logEndOfLine();

                this->log(std::string(60, '*'));
                this->logEndOfLine();
                this->logEndOfLine();

                // enregistrement de l'erreur dans le fichier des fautes
                // ouverture en mode "app(end)"
                std::ofstream fault(_faultFile, std::ios::app);
                fault << pNewInput->getFilePath();
                fault << " Exception n° " << std::hex << exceptionCode << std::dec << std::endl;
                fault.close();

                // enregistrer le code d'erreur dans l'objet
                pNewInput->setExceptionCode(exceptionCode);

                // actions spécifiques cmdline/gui à mener lors de la découverte d'une faute
                this->faultFound();

                // Fermeture du processus
                TerminateProcess(pi.hProcess, 0);
                
                // acquitter
                //ContinueDebugEvent(e.dwProcessId, e.dwThreadId, DBG_CONTINUE); 

                // arret du debug
                DebugActiveProcessStop(pi.dwProcessId);
                // fermeture des handles du programme débuggé
                CloseHandle(pi.hProcess); 
                CloseHandle(pi.hThread);
                // retour du code d'erreur 
                returnCode = exceptionCode;
                continueDebug = false;
            }
            break;

        case EXIT_PROCESS_DEBUG_EVENT: // = fin du programme (normale ou provoquée par expiration du timer)
            this->logVerbose(" (OK)");
            this->logVerboseEndOfLine();

            // acquitter
            ContinueDebugEvent(e.dwProcessId, e.dwThreadId, DBG_CONTINUE); 

            // fermeture des handles du programme débuggé
            CloseHandle(pi.hProcess); 
            CloseHandle(pi.hThread);

            // quitter la boucle 
            continueDebug = false;	
            break;  // quitter la boucle 
        
        default: 
            // acquitter les autres évènements
            ContinueDebugEvent(e.dwProcessId, e.dwThreadId, DBG_CONTINUE); 
            break;
        }      
    }

    // arret du timer (sans effet si c'est le timer qui a provoqué l'arret du debug)
    if (_hTimer) CancelWaitableTimer(_hTimer);

    // retour du code d'erreur ou 0 si rien trouvé
    return (returnCode);
}
Ejemplo n.º 22
0
int main(int argc, char **argv){
    if( argc<2){
        printf("Usage: %s <ip address>\n", argv[0]);
        return 1;
    }
    
    if( IsDebuggerPresent()){
        HANDLE iphlpapi=LoadLibrary("iphlpapi.dll");
        if( !iphlpapi){
            perror("iphlpapi.dll");
            return 1;
        }
        FARPROC IcmpSendEcho=GetProcAddress(iphlpapi, "IcmpSendEcho");
        FARPROC IcmpCreateFile=GetProcAddress(iphlpapi, "IcmpCreateFile");
        FARPROC IcmpCloseHandle=GetProcAddress(iphlpapi, "IcmpCloseHandle");
        if( (IcmpSendEcho && IcmpCreateFile && IcmpCloseHandle)==0){
            perror("icmp functions");
            return 1;
        }
        
        unsigned long ipaddr=INADDR_NONE, params[2];
        HANDLE hIcmpFile;
        char data[32], *reply;
        int replySize=sizeof(ICMP_ECHO_REPLY)+sizeof(data);
        
        if( (ipaddr=inet_addr(argv[1]))==INADDR_NONE){
            perror("Illegal IP address!");
            return 1;
        }
        
        if( (hIcmpFile=(HANDLE)IcmpCreateFile())==INVALID_HANDLE_VALUE){
            perror("IcmpCreateFile");
            return 1;
        }
        
        reply=(char *)malloc(replySize);
        ZeroMemory(data, sizeof(data));
        params[0]=PARAM;
        params[1]=(unsigned long)GetProcAddress(iphlpapi, "IcmpSendEcho2Ex");
        
        RaiseException(EXCEPTION_BREAKPOINT, 0, 2, params);
        puts("Exception raised!");
        IcmpSendEcho(hIcmpFile, ipaddr, data, sizeof(data), NULL, reply, replySize, 1000);
        puts("This line should never be shown...");
        IcmpCloseHandle(hIcmpFile);
        return 0;
    }
    
    PROCESS_INFORMATION pi;
    STARTUPINFO si;
    HANDLE hProcess, hThread;
    DEBUG_EVENT debugEvent;
    EXCEPTION_RECORD *ExceptionRecord=&debugEvent.u.Exception.ExceptionRecord;
    CONTEXT context;
    FARPROC IcmpSendEcho2Ex=NULL;
    char path[256], args[512], originalByte[1];
    
    ZeroMemory(?, sizeof(PROCESS_INFORMATION));
    ZeroMemory(&si, sizeof(STARTUPINFO));
    ZeroMemory(&debugEvent, sizeof(DEBUG_EVENT));
    ZeroMemory(&context, sizeof(CONTEXT));
    ZeroMemory(path, sizeof(path));
    ZeroMemory(args, sizeof(args));
    si.cb=sizeof(STARTUPINFO);
    si.dwFlags=STARTF_USESHOWWINDOW;
    si.wShowWindow=SW_HIDE;
    context.ContextFlags=CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS;
    
    GetModuleFileName(NULL, path, sizeof(path)-1);
    snprintf(args, sizeof(args)-1, "%s %s", path, argv[1]);
    
    if( !CreateProcess(
        NULL,
        args,
        NULL,
        NULL,
        FALSE,
        DEBUG_PROCESS,
        NULL,
        NULL,
        &si,
        ?
    )){
       perror("CreateProcess");
       return 1;
    }
    
    if( (hProcess=OpenProcess(PROCESS_ALL_ACCESS, FALSE, pi.dwProcessId))==NULL){
       perror("OpenProcess");
       return 1;
    }
    
    HANDLE kernel32=LoadLibrary("kernel32.dll");
    FARPROC DebugSetProcessKillOnExit=GetProcAddress(kernel32, "DebugSetProcessKillOnExit");
    FARPROC DebugActiveProcessStop=GetProcAddress(kernel32, "DebugActiveProcessStop");
    FARPROC OpenThread=GetProcAddress(kernel32, "OpenThread");
    CloseHandle(kernel32);
    DebugSetProcessKillOnExit(TRUE);
    
    while(WaitForDebugEvent(&debugEvent, INFINITE) && debugEvent.dwDebugEventCode!=EXIT_PROCESS_DEBUG_EVENT){
             if( debugEvent.dwDebugEventCode==EXCEPTION_DEBUG_EVENT && ExceptionRecord->ExceptionCode==EXCEPTION_BREAKPOINT){
                 if( ExceptionRecord->NumberParameters>1 && ExceptionRecord->ExceptionInformation[0]==PARAM){
                     IcmpSendEcho2Ex=(FARPROC)ExceptionRecord->ExceptionInformation[1];
                     printf("IcmpSendEcho2Ex %p\n", IcmpSendEcho2Ex);
                     if( !BreakpointSet(hProcess, IcmpSendEcho2Ex, &originalByte)){
                         perror("BreakpointSet");
                         break;
                     }
                 }
                 else if( ExceptionRecord->ExceptionAddress==IcmpSendEcho2Ex){
                      printf("EIP %p\n", IcmpSendEcho2Ex);
                      if( !BreakpointRetrieve(hProcess, IcmpSendEcho2Ex, &originalByte)){
                          perror("BreakpointRetrieve");
                          break;
                      }
                      if((hThread=(HANDLE)OpenThread(THREAD_ALL_ACCESS, FALSE, debugEvent.dwThreadId))==NULL) puts("OpenThread");
                      if(!GetThreadContext(hThread, &context)) puts("GetThreadContext");
                      context.Eip -= 1;
                      if(!SetThreadContext(hThread, &context)) puts("SetThreadContext");
                      CreateThread(NULL, 0, (void *)Terminate, hProcess, 0, NULL);
                 }
             }
             else if( debugEvent.dwDebugEventCode==EXCEPTION_DEBUG_EVENT){
                  puts("Exception!");
                  DebugActiveProcessStop(debugEvent.dwProcessId);
                  break;
             }
             ContinueDebugEvent(debugEvent.dwProcessId, debugEvent.dwThreadId, DBG_CONTINUE);
             ZeroMemory(&debugEvent, sizeof(DEBUG_EVENT));
    }
    
    return 0;
}
Ejemplo n.º 23
0
bool DebugFrontend::StartProcessAndRunToEntry(LPCSTR exeFileName, LPSTR commandLine, LPCSTR directory, PROCESS_INFORMATION& processInfo)
{

    STARTUPINFO startUpInfo = { 0 };
    startUpInfo.cb = sizeof(startUpInfo);

    ExeInfo info;
    if (!GetExeInfo(exeFileName, info) || info.entryPoint == 0)
    {
        MessageEvent("Error: The entry point for the application could not be located", MessageType_Error);
        return false;
    }

    if (!info.i386)
    {
        MessageEvent("Error: Debugging 64-bit applications is not supported", MessageType_Error);
        return false;
    }

    DWORD flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS;

    if (!CreateProcess(NULL, commandLine, NULL, NULL, TRUE, flags, NULL, directory, &startUpInfo, &processInfo))
    {
        OutputError(GetLastError());
        return false;
    }

    // Running to the entry point currently doesn't work for managed applications, so
    // just start it up.

    if (!info.managed)
    {

        unsigned long entryPoint = info.entryPoint;

        BYTE breakPointData;
        bool done = false;
        
        while (!done)
        {

            DEBUG_EVENT debugEvent;
            WaitForDebugEvent(&debugEvent, INFINITE);

            DWORD continueStatus = DBG_EXCEPTION_NOT_HANDLED;

            if (debugEvent.dwDebugEventCode == EXCEPTION_DEBUG_EVENT)
            {
                if (debugEvent.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_SINGLE_STEP ||
                    debugEvent.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT)
                {

                    CONTEXT context;
                    context.ContextFlags = CONTEXT_FULL;

                    GetThreadContext(processInfo.hThread, &context);

                    if (context.Eip == entryPoint + 1)
                    {

                        // Restore the original code bytes.
                        SetBreakpoint(processInfo.hProcess, (LPVOID)entryPoint, false, &breakPointData);
                        done = true;

                        // Backup the instruction pointer so that we execute the original instruction.
                        --context.Eip;
                        SetThreadContext(processInfo.hThread, &context);

                        // Suspend the thread before we continue the debug event so that the program
                        // doesn't continue to run.
                        SuspendThread(processInfo.hThread);

                    }

                    continueStatus = DBG_CONTINUE;

                }
            }
            else if (debugEvent.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
            {
                done = true;
            }
            else if (debugEvent.dwDebugEventCode == CREATE_PROCESS_DEBUG_EVENT)
            {
            
                // Offset the entry point by the load address of the process.
                entryPoint += reinterpret_cast<size_t>(debugEvent.u.CreateProcessInfo.lpBaseOfImage);

                // Write a break point at the entry point of the application so that we
                // will stop when we reach that point.
                SetBreakpoint(processInfo.hProcess, reinterpret_cast<void*>(entryPoint), true, &breakPointData);

                CloseHandle(debugEvent.u.CreateProcessInfo.hFile);

            }
            else if (debugEvent.dwDebugEventCode == LOAD_DLL_DEBUG_EVENT)
            {
                CloseHandle(debugEvent.u.LoadDll.hFile);
            }

            ContinueDebugEvent(debugEvent.dwProcessId, debugEvent.dwThreadId, continueStatus);
        
        }

    }

    DebugActiveProcessStop(processInfo.dwProcessId);
    return true;

}
Ejemplo n.º 24
0
extern "C" int __declspec(dllexport) ExitDebugging()
{
	DebugActiveProcessStop(dwPid);
	ExitProcess(0);
	return 1;
}