BOOL Utils::GetProcessInfo( CAtlArray< Utils::ProcessInfo > & ProcList) { HANDLE hToolHelp = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); if(hToolHelp != INVALID_HANDLE_VALUE) { PROCESSENTRY32 Entry; Entry.dwSize = sizeof(Entry); if(Process32First(hToolHelp, &Entry)) { Utils::ProcessInfo Info; do { Info.PID = Entry.th32ProcessID; HANDLE hModuleHelp =CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, Info.PID); Info.Name = Entry.szExeFile; Info.CompanyName = L""; if(hModuleHelp != INVALID_HANDLE_VALUE ) { MODULEENTRY32 ModEntry = {0}; ModEntry.dwSize = sizeof(ModEntry); Module32First(hModuleHelp, &ModEntry); Info.Path = ModEntry.szExePath; CloseHandle(hModuleHelp); // file info DWORD dwHandle = 0; DWORD InfoLen = GetFileVersionInfoSize(Info.Path, &dwHandle); if(InfoLen > 0) { BYTE *VerData = new BYTE[InfoLen]; ZeroMemory(VerData, InfoLen); BOOL ret = GetFileVersionInfo(Info.Path, NULL, InfoLen, VerData); LPVOID lpvi; UINT iLen; if (VerQueryValue(VerData, _T("\\"), &lpvi, &iLen)) { memcpy(&Info.FileInfo,lpvi, iLen); if (VerQueryValue(VerData, _T("\\VarFileInfo\\Translation"), &lpvi, &iLen) && iLen >= 4) { memcpy(&Info.LangID,lpvi, 4); } CString query; LPCTSTR pVal = NULL; UINT iLenVal; #define GetVersionValue(v) query.Format(_T("\\StringFileInfo\\%04x%04x\\%s"), Info.LangID,Info.Charset,_T(#v)); \ VerQueryValue(VerData, (LPTSTR)(LPCTSTR)query, (LPVOID*)&pVal, &iLenVal) ; \ Info.##v = pVal; GetVersionValue(CompanyName); GetVersionValue(FileVersion); } delete VerData; } } ProcList.Add(Info); } while (Process32Next(hToolHelp , &Entry)); } } CloseHandle(hToolHelp); return TRUE; }
static void *get_proc_address(void *process, DWORD pid, const char *func) { void *ret = 0; MODULEENTRY32 entry; entry.dwSize = sizeof(entry); void *list = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid); for (int k = Module32First(list, &entry); k; k = Module32Next(list, &entry)) { IMAGE_DOS_HEADER dos; IMAGE_NT_HEADERS nt; IMAGE_EXPORT_DIRECTORY expdir; uint32_t exportaddr; uint8_t *base = entry.modBaseAddr; if (stricmp("kernel32.dll", entry.szModule)) continue; SIZE_T tmp; ReadProcessMemory(process, base, &dos, sizeof(dos), &tmp); ReadProcessMemory(process, base + dos.e_lfanew, &nt, sizeof(nt), &tmp); exportaddr = nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress; if (!exportaddr) continue; ReadProcessMemory(process, base + exportaddr, &expdir, sizeof(expdir), &tmp); for (int i = 0; i < (int)expdir.NumberOfNames; ++i) { uint32_t nameaddr; /* Look for our function name in the list of names */ ReadProcessMemory(process, base + expdir.AddressOfNames + i * sizeof(DWORD), &nameaddr, sizeof(nameaddr), &tmp); char buf[1024]; size_t buflen = strlen(func) + 1; ReadProcessMemory(process, base + nameaddr, buf, buflen, &tmp); if (strcmp(buf, func)) continue; /* If we found a function with this name, return its address */ uint16_t j; ReadProcessMemory(process, base + expdir.AddressOfNameOrdinals + i * sizeof(WORD), &j, sizeof(j), &tmp); uint32_t funcaddr; ReadProcessMemory(process, base + expdir.AddressOfFunctions + j * sizeof(DWORD), &funcaddr, sizeof(funcaddr), &tmp); ret = base + funcaddr; goto _finished; } } _finished: CloseHandle(list); return ret; }
bool CAttachDlg::CanAttachWindow(HWND hFind, DWORD nSkipPID, CProcessData* apProcessData, CAttachDlg::AttachWndInfo& Info) { static bool bIsWin64 = IsWindows64(); ZeroStruct(Info); DWORD_PTR nStyle = GetWindowLongPtr(hFind, GWL_STYLE); DWORD_PTR nStyleEx = GetWindowLongPtr(hFind, GWL_EXSTYLE); if (!GetWindowThreadProcessId(hFind, &Info.nPID)) Info.nPID = 0; if (!Info.nPID) return false; bool lbCan = ((nStyle & (WS_VISIBLE/*|WS_CAPTION|WS_MAXIMIZEBOX*/)) == (WS_VISIBLE/*|WS_CAPTION|WS_MAXIMIZEBOX*/)); if (lbCan) { // Более тщательно стили проверить lbCan = ((nStyle & WS_MAXIMIZEBOX) == WS_MAXIMIZEBOX) || ((nStyle & WS_THICKFRAME) == WS_THICKFRAME); } if (lbCan && Info.nPID == GetCurrentProcessId()) lbCan = false; if (lbCan && Info.nPID == nSkipPID) lbCan = false; if (lbCan && (nStyle & WS_CHILD)) lbCan = false; if (lbCan && (nStyleEx & WS_EX_TOOLWINDOW)) lbCan = false; if (lbCan && gpConEmu->isOurConsoleWindow(hFind)) lbCan = false; if (lbCan && gpConEmu->mp_Inside && (hFind == gpConEmu->mp_Inside->mh_InsideParentRoot)) lbCan = false; GetClassName(hFind, Info.szClass, countof(Info.szClass)); GetWindowText(hFind, Info.szTitle, countof(Info.szTitle)); if (gpSetCls->isAdvLogging) { wchar_t szLogInfo[MAX_PATH*3]; _wsprintf(szLogInfo, SKIPLEN(countof(szLogInfo)) L"Attach:%s x%08X/x%08X/x%08X {%s} \"%s\"", Info.szExeName, LODWORD(hFind), nStyle, nStyleEx, Info.szClass, Info.szTitle); CVConGroup::LogString(szLogInfo); } if (!lbCan) return false; _wsprintf(Info.szPid, SKIPLEN(countof(Info.szPid)) L"%u", Info.nPID); const wchar_t sz32bit[] = L" [32]"; const wchar_t sz64bit[] = L" [64]"; HANDLE h; DEBUGTEST(DWORD nErr); bool lbExeFound = false; if (apProcessData) { lbExeFound = apProcessData->GetProcessName(Info.nPID, Info.szExeName, countof(Info.szExeName), Info.szExePathName, countof(Info.szExePathName), &Info.nImageBits); if (lbExeFound) { //ListView_SetItemText(hList, nItem, alc_File, szExeName); //ListView_SetItemText(hList, nItem, alc_Path, szExePathName); if (bIsWin64 && Info.nImageBits) { wcscat_c(Info.szPid, (Info.nImageBits == 64) ? sz64bit : sz32bit); } } } if (!lbExeFound) { Info.nImageBits = GetProcessBits(Info.nPID); if (bIsWin64 && Info.nImageBits) { wcscat_c(Info.szPid, (Info.nImageBits == 64) ? sz64bit : sz32bit); } h = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, Info.nPID); if (h && h != INVALID_HANDLE_VALUE) { MODULEENTRY32 mi = {sizeof(mi)}; if (Module32First(h, &mi)) { lstrcpyn(Info.szExeName, *mi.szModule ? mi.szModule : (wchar_t*)PointToName(mi.szExePath), countof(Info.szExeName)); lstrcpyn(Info.szExePathName, mi.szExePath, countof(Info.szExePathName)); lbExeFound = true; } else { if (bIsWin64) { wcscat_c(Info.szPid, sz64bit); } } CloseHandle(h); } else { #ifdef _DEBUG nErr = GetLastError(); _ASSERTE(nErr == 5 || (nErr == 299 && Info.nImageBits == 64)); #endif wcscpy_c(Info.szExeName, L"???"); } #if 0 //#ifdef _WIN64 -- no need to call TH32CS_SNAPMODULE32, simple TH32CS_SNAPMODULE will handle both if it can if (!lbExeFound) { h = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE|TH32CS_SNAPMODULE32, Info.nPID); if (h && h != INVALID_HANDLE_VALUE) { MODULEENTRY32 mi = {sizeof(mi)}; if (Module32First(h, &mi)) { //ListView_SetItemText(hList, nItem, alc_File, *mi.szModule ? mi.szModule : (wchar_t*)PointToName(mi.szExePath)); lstrcpyn(Info.szExeName, *mi.szModule ? mi.szModule : (wchar_t*)PointToName(mi.szExePath), countof(Info.szExeName)); //ListView_SetItemText(hList, nItem, alc_Path, mi.szExePath); lstrcpyn(Info.szExePathName, mi.szExePath, countof(Info.szExePathName)); } CloseHandle(h); } } #endif } if (!lbExeFound) { // Так можно получить только имя файла процесса PROCESSENTRY32 pi = {sizeof(pi)}; h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (h && h != INVALID_HANDLE_VALUE) { if (Process32First(h, &pi)) { do { if (pi.th32ProcessID == Info.nPID) { lstrcpyn(Info.szExeName, pi.szExeFile, countof(Info.szExeName)); break; } } while (Process32Next(h, &pi)); } } } wcscpy_c(Info.szType, isConsoleClass(Info.szClass) ? szTypeCon : szTypeGui); return true; }
bool PlatformSpecificProgramIdentifierHelper::_isExePathRelatedToProcess(DWORD dwPID, QString exePath) { HANDLE hModuleSnap = INVALID_HANDLE_VALUE; MODULEENTRY32 me32; FLAG_FOR_REVIEW_WITH_HINT("https://bitbucket.org/shadevampire/easyapps/issue/238/bug-termination-fails-for-some-64-bit-apps"); // Take a snapshot of all modules in the specified process. #ifdef __MINGW32__ hModuleSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE/* | TH32CS_SNAPMODULE32*/, dwPID ); #else // MSVC hModuleSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, dwPID ); #endif if( hModuleSnap == INVALID_HANDLE_VALUE ) { DLog("Failed, retry if error-bad-length..."); bool isSuccess = false; int lastErrorCode = GetLastError(); while( (lastErrorCode = GetLastError()) == ERROR_BAD_LENGTH) { // retry while failes // it's hilarious, but this is what the docs says... // http://msdn.microsoft.com/en-us/library/windows/desktop/ms682489(v=vs.85).aspx DLog("Retry while it's error-bad-length, as the docs says...") << lastErrorCode; #ifdef __MINGW32__ hModuleSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE/* | TH32CS_SNAPMODULE32*/, dwPID ); #else // MSVC hModuleSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, dwPID ); #endif if( hModuleSnap == INVALID_HANDLE_VALUE ) { // retry if error-bad-length } else { isSuccess = true; } } if(!isSuccess) { DLog("FAILED: CreateToolhelp32Snapshot (of modules). Last error code: ") << lastErrorCode; return( false ); } } // Set the size of the structure before using it. me32.dwSize = sizeof( MODULEENTRY32 ); // Retrieve information about the first module, // and exit if unsuccessful if( !Module32First( hModuleSnap, &me32 ) ) { DLog("FAILED: Module32First"); // show cause of failure CloseHandle( hModuleSnap ); // clean the snapshot object return( false ); } bool isFound = false; // Now walk the module list of the process, // and display information about each module do { // _tprintf( TEXT("\n\n MODULE NAME: %s"), me32.szModule ); // _tprintf( TEXT("\n Executable = %s"), me32.szExePath ); // _tprintf( TEXT("\n Process ID = 0x%08X"), me32.th32ProcessID ); // _tprintf( TEXT("\n Ref count (g) = 0x%04X"), me32.GlblcntUsage ); // _tprintf( TEXT("\n Ref count (p) = 0x%04X"), me32.ProccntUsage ); // _tprintf( TEXT("\n Base address = 0x%08X"), (DWORD) me32.modBaseAddr ); // _tprintf( TEXT("\n Base size = %d"), me32.modBaseSize ); if(me32.th32ProcessID == dwPID) { QString processRelatedExePath = QString::fromWCharArray(me32.szExePath); processRelatedExePath = QDir().absoluteFilePath(processRelatedExePath); processRelatedExePath = PathHelper::cleanThisPath(processRelatedExePath); QString absoluteReferenceExePath = QDir().absoluteFilePath(exePath); absoluteReferenceExePath = PathHelper::cleanThisPath(absoluteReferenceExePath); // DLogS << "proc related exe-path: " << processRelatedExePath << " reference path: " << absoluteReferenceExePath; if(processRelatedExePath == absoluteReferenceExePath) { isFound = true; break; } } } while( Module32Next( hModuleSnap, &me32 ) ); CloseHandle( hModuleSnap ); return( isFound ); }
void * dlsym(void *handle, const char *symbol) { FARPROC fp = NULL; LPCTSTR new_symbol; if (!symbol || !*symbol) return NULL; #ifdef UNICODE new_symbol = evil_char_to_wchar(symbol); #else new_symbol = symbol; #endif /* UNICODE */ if (handle == RTLD_DEFAULT) { #ifdef _WIN32_WCE HANDLE snapshot; MODULEENTRY32 module; snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS | TH32CS_SNAPMODULE | TH32CS_GETALLMODS, 0); if (!snapshot) return NULL; module.dwSize = sizeof(module); if (Module32First(snapshot, &module)) do { fp = GetProcAddress(module.hModule, new_symbol); if (fp) break; } while (Module32Next(snapshot, &module)); CloseToolhelp32Snapshot(snapshot); #else HMODULE modules[1024]; DWORD needed; DWORD i; /* TODO: use EnumProcessModulesEx() on Windows >= Vista */ if (!EnumProcessModules(GetCurrentProcess(), modules, sizeof(modules), &needed)) return NULL; for (i = 0; i < (needed / sizeof(HMODULE)); i++) { fp = GetProcAddress(modules[i], new_symbol); if (fp) break; } #endif } else fp = GetProcAddress(handle, new_symbol); #ifdef UNICODE free((void *)new_symbol); #endif /* UNICODE */ if (!fp) get_last_error("GetProcAddress returned: "); return fp; }
void UpdateMemoryMap(void) { MemMap.clear(); MemMapCode.clear(); MemMapData.clear(); MemMapModule.clear(); Exports.clear(); CustomNames.clear(); if (hProcess == NULL) return; if (!IsProcHandleValid(hProcess)) { hProcess = NULL; return; } SYSTEM_INFO SysInfo; GetSystemInfo(&SysInfo); MEMORY_BASIC_INFORMATION MBI; ULONG_PTR pMemory = (ULONG_PTR)SysInfo.lpMinimumApplicationAddress; while(pMemory < (ULONG_PTR)SysInfo.lpMaximumApplicationAddress) { if ( VirtualQueryEx(hProcess,(LPCVOID)pMemory,&MBI,sizeof(MBI)) != 0) { if (MBI.State == MEM_COMMIT /*&& MBI.Type == MEM_PRIVATE*/) { MemMapInfo Mem; Mem.Start = (DWORD_PTR)pMemory; Mem.End = (DWORD_PTR)pMemory + MBI.RegionSize - 1; MemMap.push_back(Mem); } pMemory = (ULONG_PTR)MBI.BaseAddress + MBI.RegionSize; } else { pMemory += 1024; } } MODULEENTRY32 ModInfo; ModInfo.dwSize = sizeof(MODULEENTRY32); HANDLE ModuleList = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,GetProcessId(hProcess)); if ((int)ModuleList != -1) { BOOL rm = Module32First(ModuleList,&ModInfo); while(rm) { MemMapInfo Mem; Mem.Start = (DWORD_PTR)ModInfo.modBaseAddr; Mem.End = Mem.Start + ModInfo.modBaseSize; Mem.Name = ModInfo.szModule; MemMapModule.push_back(Mem); rm = Module32Next(ModuleList,&ModInfo); } CloseHandle(ModuleList); } AddressName Entry; ModuleList = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,GetProcessId(hProcess)); if ((int)ModuleList != -1) { BOOL rm = Module32First(ModuleList,&ModInfo); while(rm) { IMAGE_DOS_HEADER DH; IMAGE_NT_HEADERS pe; ReadProcessMemory(hProcess,ModInfo.modBaseAddr,&DH,sizeof(DH),NULL); ReadProcessMemory(hProcess,ModInfo.modBaseAddr + DH.e_lfanew,&pe,sizeof(pe),NULL); DWORD ssize = (DWORD)pe.FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER); PIMAGE_SECTION_HEADER sh = (PIMAGE_SECTION_HEADER)(new char[ssize]); ReadProcessMemory(hProcess,ModInfo.modBaseAddr + DH.e_lfanew + sizeof(IMAGE_NT_HEADERS),sh,ssize,NULL); for (int i=0; i < pe.FileHeader.NumberOfSections; i++) { CString txt; MemMapInfo Mem; txt.Format("%.8s",sh[i].Name); txt.MakeLower(); if (txt == ".text" || txt == "code") { Mem.Start = (DWORD_PTR)ModInfo.modBaseAddr + sh[i].VirtualAddress; Mem.End = Mem.Start + sh[i].Misc.VirtualSize; Mem.Name = ModInfo.szModule; MemMapCode.push_back(Mem); } if (txt == ".data" || txt == "data" || txt == ".rdata" || txt == ".idata") { Mem.Start = (DWORD_PTR)ModInfo.modBaseAddr + sh[i].VirtualAddress; Mem.End = Mem.Start + sh[i].Misc.VirtualSize; Mem.Name = ModInfo.szModule; MemMapData.push_back(Mem); } } delete sh; rm = Module32Next(ModuleList,&ModInfo); } CloseHandle(ModuleList); } for (UINT i=0; i<MemMap.size();i++) { if (IsModule(MemMap[i].Start)) MemMap[i].Name = GetModuleName(MemMap[i].Start); } }
BOOL EjectDll(DWORD dwPID, LPCTSTR szDllPath) { BOOL bMore = FALSE, bFound = FALSE, bRet = FALSE; HANDLE hSnapshot = INVALID_HANDLE_VALUE; HANDLE hProcess = NULL; HANDLE hThread = NULL; MODULEENTRY32 me = { sizeof(me), }; LPTHREAD_START_ROUTINE pThreadProc = NULL; HMODULE hMod = NULL; DWORD dwDesiredAccess = 0; TCHAR szProcName[MAX_PATH] = { 0, }; if (INVALID_HANDLE_VALUE == (hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwPID))) { wsprintf(buf, L"EjectDll() : CreateToolhelp32Snapshot(%d) failed!!! [%d]\n", dwPID, GetLastError()); goto EJECTDLL_EXIT; } bMore = Module32First(hSnapshot, &me); for (; bMore; bMore = Module32Next(hSnapshot, &me)) { if (!_tcsicmp(me.szModule, szDllPath) || !_tcsicmp(me.szExePath, szDllPath)) { bFound = TRUE; break; } } if (!bFound) { wsprintf(buf, L"EjectDll() : There is not %s module in process(%d) memory!!!\n", szDllPath, dwPID); MessageBox(NULL, buf, L"error", MB_OK); goto EJECTDLL_EXIT; } dwDesiredAccess = PROCESS_ALL_ACCESS; if (!(hProcess = OpenProcess(dwDesiredAccess, FALSE, dwPID))) { wsprintf(buf, L"EjectDll() : OpenProcess(%d) failed!!! [%d]\n", dwPID, GetLastError()); MessageBox(NULL, buf, L"error", MB_OK); goto EJECTDLL_EXIT; } hMod = GetModuleHandle(L"kernel32.dll"); if (hMod == NULL) { wsprintf(buf, L"EjectDll() : GetModuleHandle(\"kernel32.dll\") failed!!! [%d]\n", GetLastError()); MessageBox(NULL, buf, L"error", MB_OK); goto EJECTDLL_EXIT; } pThreadProc = (LPTHREAD_START_ROUTINE)GetProcAddress(hMod, "FreeLibrary"); if (pThreadProc == NULL) { wsprintf(buf, L"EjectDll() : GetProcAddress(\"FreeLibrary\") failed!!! [%d]\n", GetLastError()); MessageBox(NULL, buf, L"error", MB_OK); goto EJECTDLL_EXIT; } if (!MyCreateRemoteThread(hProcess, pThreadProc, me.modBaseAddr)) { wsprintf(buf, L"EjectDll() : MyCreateRemoteThread() failed!!!\n"); MessageBox(NULL, buf, L"error", MB_OK); goto EJECTDLL_EXIT; } bRet = TRUE; EJECTDLL_EXIT: _tcscpy_s(szProcName, GetProcName(dwPID)); wsprintf(buf, L"%s(%d) %s!!! [%d]\n", szProcName, dwPID, bRet ? L"SUCCESS" : L"-->> FAILURE", GetLastError()); OutputDebugStringW(buf); if (hThread) CloseHandle(hThread); if (hProcess) CloseHandle(hProcess); if (hSnapshot != INVALID_HANDLE_VALUE) CloseHandle(hSnapshot); return bRet; }
void CExceptionHandler::WriteExceptionReport() #endif { // Get the current time and date time_t t = time(NULL); const struct tm * tm = localtime(&t); // Get the 'crashinfo' directory path String strPath(SharedUtility::GetAbsolutePath("crashinfo")); // Create the 'crashinfo' directory if needed if(!SharedUtility::Exists(strPath)) SharedUtility::CreateDirectory(strPath); // Append the client or server string to the path #ifdef _SERVER strPath.Append("\\Server"); #else strPath.Append("\\Client"); #endif // Append the operating system string to the path strPath.Append("-" OS_STRING); // Append the version, date and time to the path strPath.AppendF("-" MOD_VERSION_STRING "-%04d.%02d.%02d-%02d.%02d.%02d", (tm->tm_year + 1900), (tm->tm_mon + 1), tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); // Get the log file path String strLogPath("%s.log", strPath.Get()); // Open the log file FILE * fFile = fopen(strLogPath, "w"); // Did the log file open successfully? if(fFile) { String strReportData; // Write the unhandled exception report start notice to the log file fprintf(fFile, "-- Unhandled Exception Report Start --\n"); #ifdef WIN32 // Write the exception code and exception code string to the log file strReportData.AppendF("Exception code: 0x%p (%s)\n", ExceptionInfo->ExceptionRecord->ExceptionCode, ExceptionCodeToString(ExceptionInfo->ExceptionRecord->ExceptionCode)); // Write the exception address to the log file #ifndef _SERVER strReportData.AppendF("Exception address: 0x%p (Game base: 0x%p)\n", ExceptionInfo->ExceptionRecord->ExceptionAddress, CGame::GetBase()); strReportData.AppendF("Exception real-add: 0x%p / 0x%p\n", ((int)ExceptionInfo->ExceptionRecord->ExceptionAddress-CGame::GetBase()), (CGame::GetBase()-(int)ExceptionInfo->ExceptionRecord->ExceptionAddress)); #else strReportData.AppendF("Exception address: 0x%p\n", ExceptionInfo->ExceptionRecord->ExceptionAddress); #endif // Create a tool help 32 process snapshot HANDLE hModuleSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId()); if(hModuleSnapShot) { MODULEENTRY32 ModuleEntry; ModuleEntry.dwSize = sizeof(ModuleEntry); if(Module32First(hModuleSnapShot, &ModuleEntry)) { // Enumerate through all modules while(Module32Next(hModuleSnapShot, &ModuleEntry)) { // See if exception was within this module if((ExceptionInfo->ContextRecord->Eip >= (DWORD)ModuleEntry.modBaseAddr) && (ExceptionInfo->ContextRecord->Eip <= ((DWORD)ModuleEntry.modBaseAddr + ModuleEntry.modBaseSize))) { strReportData.AppendF("Exception module: %s (+0x%p)\n", ModuleEntry.szModule, (ExceptionInfo->ContextRecord->Eip - (DWORD)ModuleEntry.modBaseAddr)); break; } } } } // Write the registers segment header strReportData.AppendF("Exception registers: \n"); // If we have segments context information then write it to the log file if(ExceptionInfo->ContextRecord->ContextFlags & CONTEXT_SEGMENTS) { strReportData.AppendF("GS=0x%p FS=0x%p ES=0x%p DS=0x%p\n", ExceptionInfo->ContextRecord->SegGs, ExceptionInfo->ContextRecord->SegFs, ExceptionInfo->ContextRecord->SegEs, ExceptionInfo->ContextRecord->SegDs); } // If we have integer context information then write it to the log file if(ExceptionInfo->ContextRecord->ContextFlags & CONTEXT_INTEGER) { strReportData.AppendF("EDI=0x%p ESI=0x%p EBX=0x%p EDX=0x%p\n", ExceptionInfo->ContextRecord->Edi, ExceptionInfo->ContextRecord->Esi, ExceptionInfo->ContextRecord->Ebx, ExceptionInfo->ContextRecord->Edx); strReportData.AppendF("ECX=0x%p EAX=0x%p\n", ExceptionInfo->ContextRecord->Ecx, ExceptionInfo->ContextRecord->Eax); } // If we have control context information then write it to the log file if(ExceptionInfo->ContextRecord->ContextFlags & CONTEXT_CONTROL) { strReportData.AppendF("EBP=0x%p EIP=0x%p CS=0x%p EFLAGS=0x%p\n", ExceptionInfo->ContextRecord->Ebp, ExceptionInfo->ContextRecord->Eip, ExceptionInfo->ContextRecord->SegCs, ExceptionInfo->ContextRecord->EFlags); strReportData.AppendF("ESP=0x%p SS=0x%p\n", ExceptionInfo->ContextRecord->Esp, ExceptionInfo->ContextRecord->SegSs); } #else void * pArray[50]; int iSize = backtrace(pArray, 50); char ** szMessages = backtrace_symbols(pArray, iSize); for(int i = 0; i < iSize && (szMessages[i] != NULL); i++) strReportData.AppendF("[Backtrace %d]: %s\n", i, szMessages[i]); #endif // If we have a callback call it if(m_pfnCallback) m_pfnCallback(strReportData); // Print the report data to the log file fprintf(fFile, strReportData.Get()); // Write the unhandled exception report end notice to the log file fprintf(fFile, "--Unhandled Exception Report End --\n"); // Close the log file fclose(fFile); } else CLogFile::Printf("Failed to open the crash log file."); #ifdef WIN32 // Get the minidump file path String strMiniDumpPath("%s.dmp", strPath.Get()); // Open the minidump file HANDLE hFile = CreateFileA(strMiniDumpPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL , NULL); // Did the minidump file open successfully? if(hFile) { // Create the minidump exception information MINIDUMP_EXCEPTION_INFORMATION exceptionInfo; exceptionInfo.ThreadId = GetCurrentThreadId(); exceptionInfo.ExceptionPointers = ExceptionInfo; exceptionInfo.ClientPointers = FALSE; // Write the minidump to the minidump file if(!MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, MiniDumpNormal, &exceptionInfo, NULL, NULL)) CLogFile::Printf("Failed to write the minidump file."); // Close the minidump file CloseHandle(hFile); } else CLogFile::Printf("Failed to open the minidump file."); #endif // Print a message in the log file CLogFile::Printf("IV:MP has crashed. Please see %s for more information.", strLogPath.Get()); }
INT_PTR CALLBACK about_dlg_proc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { case WM_INITDIALOG: { HANDLE hsnap; HWND hw; SetDlgItemText(hwnd, IDC_PRODUCT, TEXT(KH_VERSTR_PRODUCT_1033)); /* retain the original copyright strings */ #ifdef OVERRIDE_COPYRIGHT SetDlgItemText(hwnd, IDC_COPYRIGHT, TEXT(KH_VERSTR_COPYRIGHT_1033)); #endif SetDlgItemText(hwnd, IDC_BUILDINFO, TEXT(KH_VERSTR_BUILDINFO_1033)); hsnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, 0); if (hsnap != INVALID_HANDLE_VALUE) { LVCOLUMN lvc; MODULEENTRY32 mod; RECT r; hw = GetDlgItem(hwnd, IDC_MODULES); #ifdef DEBUG assert(hw != NULL); #endif GetWindowRect(hw, &r); OffsetRect(&r, -r.left, -r.top); ZeroMemory(&lvc, sizeof(lvc)); lvc.mask = LVCF_TEXT | LVCF_WIDTH; lvc.pszText = L"Name"; lvc.cx = r.right / 4; ListView_InsertColumn(hw, 0, &lvc); lvc.pszText = L"Path"; lvc.cx = (r.right * 3) / 4; ListView_InsertColumn(hw, 1, &lvc); ZeroMemory(&mod, sizeof(mod)); mod.dwSize = sizeof(mod); /* done with columns, now for the actual data */ if (!Module32First(hsnap, &mod)) goto _done_with_modules; do { LVITEM lvi; int idx; ZeroMemory(&lvi, sizeof(lvi)); lvi.mask = LVIF_TEXT; lvi.pszText = mod.szModule; idx = ListView_InsertItem(hw, &lvi); lvi.mask = LVIF_TEXT; lvi.iItem = idx; lvi.iSubItem = 1; lvi.pszText = mod.szExePath; ListView_SetItem(hw, &lvi); ZeroMemory(&mod, sizeof(mod)); mod.dwSize = sizeof(mod); } while(Module32Next(hsnap, &mod)); _done_with_modules: CloseHandle(hsnap); } } return FALSE; case WM_DESTROY: return TRUE; case WM_CLOSE: EndDialog(hwnd, 0); return TRUE; case WM_COMMAND: if (wParam == MAKEWPARAM(IDOK, BN_CLICKED)) { EndDialog(hwnd, 0); } return TRUE; } return FALSE; }
BOOL CPipeServer::OpenOrAttachToProcess(void) { ICLRMetaHost *pMetaHost; IEnumUnknown *RuntimeEnum; HANDLE ths; MODULEENTRY32 m; HRESULT r; BOOL result=FALSE; CLR_DEBUGGING_VERSION v; v.wStructVersion=0; v.wMajor=4; v.wMinor=0; v.wRevision=30319; v.wBuild=65535; CLRDebugging=NULL; CorDebugProcess=NULL; CorDebugProcess5=NULL; libprovider=NULL; datacallback=NULL; HMODULE hMscoree = LoadLibraryA("mscoree.dll"); CLRCreateInstanceFnPtr CLRCreateInstance; if (hMscoree==NULL) return FALSE; CLRCreateInstance=(CLRCreateInstanceFnPtr)GetProcAddress(hMscoree, "CLRCreateInstance"); if (CLRCreateInstance==NULL) return FALSE; //only 4.0 is supported for now processhandle=OpenProcess(PROCESS_ALL_ACCESS , FALSE, processid); if (processhandle==0) return FALSE; if (CLRCreateInstance(CLSID_CLRMetaHost, IID_ICLRMetaHost, (LPVOID*)&pMetaHost)!=S_OK) return FALSE; if (pMetaHost->EnumerateLoadedRuntimes(processhandle, &RuntimeEnum)==S_OK) { ICLRRuntimeInfo *info; ULONG count=0; RuntimeEnum->Next(1, (IUnknown **)&info, &count); if (count) { result=TRUE; libprovider=new CMyICLRDebuggingLibraryProvider(info); //todo: scan for 4.0 } RuntimeEnum->Release(); } pMetaHost->Release(); if (!result) return FALSE; //no runtimes if (CLRCreateInstance(CLSID_CLRDebugging, IID_ICLRDebugging, (void **)&CLRDebugging)!=S_OK) return FALSE; ths=CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, processid); if (ths==INVALID_HANDLE_VALUE) return FALSE; ZeroMemory(&m, sizeof(m)); m.dwSize=sizeof(m); if (Module32First(ths, &m)) { datacallback=new CMyIcorDebugDataTarget(processhandle); do { CLR_DEBUGGING_PROCESS_FLAGS flags; r=CLRDebugging->OpenVirtualProcess((ULONG64)m.hModule, datacallback, libprovider, &v, IID_ICorDebugProcess, (IUnknown **)&CorDebugProcess, &v, &flags); if (r==S_OK) { CorDebugProcess->QueryInterface(IID_ICorDebugProcess5, (void **)&CorDebugProcess5); break; } } while (Module32Next(ths, &m)); } CloseHandle(ths); if (r!=S_OK) return FALSE; //still here return TRUE; }
BOOL HookManager::DoHook(int hookingMethod) { HMODULE hModule; PROC OrigAddrFunc; if(hookingMethod==Hook_Specified_Module){ for(int i=0;i< MyHookedAPIList->g_Counter;i++) { if(strcmp(MyHookedAPIList->GetModuleName(i),"")==0) { OutputDebugStringA("Module Not Found!"); return FALSE; } hModule=LoadLibraryA(MyHookedAPIList->GetModuleName(i)); //Also Hook EAT function for yet-to-load DLL if functions , that are going //to be hooked , are exported. OrigAddrFunc=HookExportTable(MyHookedAPIList->GetDLLName(i), MyHookedAPIList->GetOrigAddressOfFunc(i), MyHookedAPIList->GetNewAddressOfFunc(i)); OrigAddrFunc=HookInOneModule(hModule, MyHookedAPIList->GetDLLName(i), MyHookedAPIList->GetOrigAddressOfFunc(i), MyHookedAPIList->GetNewAddressOfFunc(i)); MyHookedAPIList->SetHookedStatus(i); } } //If all modules are to be hooked , HookInAllModule should be defined else if(hookingMethod==Hook_All_Module) { HMODULE hMyDll1=LoadLibraryA("H2.dll"); HMODULE hMyDll2=LoadLibraryA("Forwarder.dll"); HANDLE snap= CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,GetCurrentProcessId()); MODULEENTRY32 mod; mod.dwSize=sizeof(MODULEENTRY32); for(int i=0;i<MyHookedAPIList->g_Counter;i++) { //Also Hook EAT function for yet-to-load DLL if functions , that are going //to be hooked , are exported. OrigAddrFunc=HookExportTable(MyHookedAPIList->GetDLLName(i), MyHookedAPIList->GetOrigAddressOfFunc(i), MyHookedAPIList->GetNewAddressOfFunc(i)); Module32First(snap,&mod); HMODULE first=mod.hModule; OrigAddrFunc=HookInOneModule(first, MyHookedAPIList->GetDLLName(i), MyHookedAPIList->GetOrigAddressOfFunc(i), MyHookedAPIList->GetNewAddressOfFunc(i)); while(Module32Next(snap,&mod)) { HMODULE next=mod.hModule; if(next==hMyDll1||next==hMyDll2) continue; // Do not hook injected DLL OrigAddrFunc=HookInOneModule(next, MyHookedAPIList->GetDLLName(i), MyHookedAPIList->GetOrigAddressOfFunc(i), MyHookedAPIList->GetNewAddressOfFunc(i)); } MyHookedAPIList->SetHookedStatus(i); } } return TRUE; }
int sub_4AAB1E(int a1, char *Str2, int a3, int a4) { void v4; void *v5; void v6; void v7; void v8; void v10; void pe; void me; void *hSnapshot; void hObject; const char String2; pe.dwSize = 0; me.dwSize = 0; memset(&pe.cntUsage, 0, 0x124u); memset(&me.th32ModuleID, 0, 0x220u); if ( !CreateToolhelp32Snapshot || !Process32First || !Process32Next ) return 0; sub_4AAAB3("SeDebugPrivilege", 1); v4 = CreateToolhelp32Snapshot(0xFu, 0); v5 = v4; hSnapshot = v4; if ( v4 == (void)-1 ) { LABEL_25: return 0; } pe.dwSize = 296; if ( !Process32First(v4, &pe) || !Process32Next(v5, &pe) ) { LABEL_24: CloseHandle(&hSnapshot); goto LABEL_25; } while ( 1 ) { if ( a3 ) { hObject = 0; while ( 1 ) { if ( !lstrcmpiA(&pe.szExeFile, &String2) ) break; hObject = (char *)hObject + 4; if ( (unsigned int)hObject >= 0x60 ) goto LABEL_23; } v6 = OpenProcess(0x1F0FFFu, 0, &pe.th32ProcessID); hObject = v6; if ( !v6 || TerminateProcess(&v6, 0) ) goto LABEL_23; v7 = hObject; goto LABEL_15; } if ( Str2 ) break; if ( !a1 ) goto LABEL_23; v8 = CreateToolhelp32Snapshot(8u, pe.th32ProcessID); me.dwSize = 548; if ( a4 ) { if ( Module32First(v8, &me) ) Sleep(0xAu); goto LABEL_23; } v7 = v8; LABEL_15: CloseHandle(&v7); LABEL_23: if ( !Process32Next(hSnapshot, &pe) ) goto LABEL_24; } if ( strcmp(&pe.szExeFile, Str2) ) goto LABEL_23; v10 = OpenProcess(0x1F0FFFu, 0, &pe.th32ProcessID); CloseHandle(&hSnapshot ); if ( !TerminateProcess(&v10, 0) ) { CloseHandle(&v10); return 0; } return 1; }
BOOL CAttachDlg::AttachDlgEnumWin(HWND hFind, LPARAM lParam) { if (IsWindowVisible(hFind)) { CAttachDlg* pDlg = (CAttachDlg*)lParam; // Условия? DWORD_PTR nStyle = GetWindowLongPtr(hFind, GWL_STYLE); DWORD_PTR nStyleEx = GetWindowLongPtr(hFind, GWL_EXSTYLE); DWORD nPID; if (!GetWindowThreadProcessId(hFind, &nPID)) nPID = 0; bool lbCan = ((nStyle & (WS_VISIBLE/*|WS_CAPTION|WS_MAXIMIZEBOX*/)) == (WS_VISIBLE/*|WS_CAPTION|WS_MAXIMIZEBOX*/)); if (lbCan) { // Более тщательно стили проверить lbCan = ((nStyle & WS_MAXIMIZEBOX) == WS_MAXIMIZEBOX) || ((nStyle & WS_THICKFRAME) == WS_THICKFRAME); } if (lbCan && nPID == GetCurrentProcessId()) lbCan = false; if (lbCan && nPID == pDlg->mn_ExplorerPID) lbCan = false; if (lbCan && (nStyle & WS_CHILD)) lbCan = false; if (lbCan && (nStyleEx & WS_EX_TOOLWINDOW)) lbCan = false; if (lbCan && gpConEmu->isOurConsoleWindow(hFind)) lbCan = false; if (lbCan && gpConEmu->mp_Inside && (hFind == gpConEmu->mp_Inside->mh_InsideParentRoot)) lbCan = false; wchar_t szClass[MAX_PATH], szTitle[MAX_PATH]; GetClassName(hFind, szClass, countof(szClass)); GetWindowText(hFind, szTitle, countof(szTitle)); if (gpSetCls->isAdvLogging) { wchar_t szLogInfo[MAX_PATH*3]; _wsprintf(szLogInfo, SKIPLEN(countof(szLogInfo)) L"Attach:%s x%08X/x%08X/x%08X {%s} \"%s\"", (DWORD)hFind, nStyle, nStyleEx, szClass, szTitle); CVConGroup::LogString(szLogInfo); } if (lbCan) { wchar_t szPid[32], szHwnd[32], szType[16]; szPid[0] = szHwnd[0] = szType[0] = 0; wchar_t szExeName[MAX_PATH], szExePathName[MAX_PATH*4]; szExeName[0] = szExePathName[0] = 0; #ifndef ALLOW_GUI_ATTACH if (!isConsoleClass(szClass)) return TRUE; #endif HWND hList = pDlg->mh_List; if (nPID) { _wsprintf(szPid, SKIPLEN(countof(szPid)) L"%u", nPID); } else { #ifdef _DEBUG wcscpy_c(szPid, L"????"); #else return TRUE; #endif } HANDLE h; bool lbExeFound = false; int nImageBits = 32; #if 0 // Так можно получить только имя файла процесса, а интересен еще и путь PROCESSENTRY32 pi = {sizeof(pi)}; h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (h && h != INVALID_HANDLE_VALUE) { if (Process32First(h, &pi)) { while (pi.th32ProcessID != nPID) { if (!Process32Next(h, &pi)) pi.th32ProcessID = 0; } } } #endif if (pDlg->mp_ProcessData) { lbExeFound = pDlg->mp_ProcessData->GetProcessName(nPID, szExeName, countof(szExeName), szExePathName, countof(szExePathName), &nImageBits); if (lbExeFound) { //ListView_SetItemText(hList, nItem, alc_File, szExeName); //ListView_SetItemText(hList, nItem, alc_Path, szExePathName); if (pDlg->mb_IsWin64) { wcscat_c(szPid, (nImageBits == 64) ? L" *64" : L" *32"); } } } if (!lbExeFound) { h = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, nPID); if (h && h != INVALID_HANDLE_VALUE) { MODULEENTRY32 mi = {sizeof(mi)}; if (Module32First(h, &mi)) { //ListView_SetItemText(hList, nItem, alc_File, *mi.szModule ? mi.szModule : (wchar_t*)PointToName(mi.szExePath)); lstrcpyn(szExeName, *mi.szModule ? mi.szModule : (wchar_t*)PointToName(mi.szExePath), countof(szExeName)); //ListView_SetItemText(hList, nItem, alc_Path, mi.szExePath); lstrcpyn(szExePathName, mi.szExePath, countof(szExePathName)); if (pDlg->mb_IsWin64) { wcscat_c(szPid, WIN3264TEST(L" *32",L" *64")); } lbExeFound = true; } else { if (pDlg->mb_IsWin64) { wcscat_c(szPid, L" *64"); } } CloseHandle(h); } #ifdef _WIN64 if (!lbExeFound) { h = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE|TH32CS_SNAPMODULE32, nPID); if (h && h != INVALID_HANDLE_VALUE) { MODULEENTRY32 mi = {sizeof(mi)}; if (Module32First(h, &mi)) { //ListView_SetItemText(hList, nItem, alc_File, *mi.szModule ? mi.szModule : (wchar_t*)PointToName(mi.szExePath)); lstrcpyn(szExeName, *mi.szModule ? mi.szModule : (wchar_t*)PointToName(mi.szExePath), countof(szExeName)); //ListView_SetItemText(hList, nItem, alc_Path, mi.szExePath); lstrcpyn(szExePathName, mi.szExePath, countof(szExePathName)); wcscat_c(szPid, L" *32"); } CloseHandle(h); } } #endif } LVITEM lvi = {LVIF_TEXT|LVIF_STATE}; lvi.state = 0; lvi.stateMask = LVIS_SELECTED|LVIS_FOCUSED; lvi.pszText = szPid; lvi.iItem = ListView_GetItemCount(hList); // в конец int nItem = ListView_InsertItem(hList, &lvi); ListView_SetItemState(hList, nItem, 0, LVIS_SELECTED|LVIS_FOCUSED); ListView_SetItemText(hList, nItem, alc_Title, szTitle); ListView_SetItemText(hList, nItem, alc_Class, szClass); _wsprintf(szHwnd, SKIPLEN(countof(szHwnd)) L"0x%08X", (DWORD)(((DWORD_PTR)hFind) & (DWORD)-1)); ListView_SetItemText(hList, nItem, alc_HWND, szHwnd); wcscpy_c(szType, isConsoleClass(szClass) ? szTypeCon : szTypeGui); ListView_SetItemText(hList, nItem, alc_File, szExeName); ListView_SetItemText(hList, nItem, alc_Path, szExePathName); ListView_SetItemText(hList, nItem, alc_Type, szType); } } return TRUE; // Продолжить }
int __CheckProcessIdModuleInserted(unsigned int procid,const char* pPartDll) { HANDLE hModSnap=INVALID_HANDLE_VALUE; int ret; BOOL bret; char* pCmpDllName=NULL; MODULEENTRY32 mentry; int curnum=0; #ifdef _UNICODE int cmpdllnamesize=0; #endif try_again: hModSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,procid); if(hModSnap == INVALID_HANDLE_VALUE) { ret = LAST_ERROR_CODE(); if(ret != ERROR_BAD_LENGTH) { //ERROR_INFO("[%d] snap module error(%d)\n",procid,ret); goto fail; } /*we try again for next use*/ goto try_again; } mentry.dwSize = sizeof(mentry); bret = Module32First(hModSnap,&mentry); if(!bret) { ret = LAST_ERROR_CODE(); ERROR_INFO("[%d] first error(%d)\n",procid,ret); goto fail; } #ifdef _UNICODE ret = UnicodeToAnsi(mentry.szModule,&pCmpDllName,&cmpdllnamesize); if(ret < 0) { ret = LAST_ERROR_CODE(); ERROR_INFO("[%d]:[%d] get module name error(%d)\n",procid,curnum,ret); goto fail; } #else pCmpDllName = mentry.szModule; #endif //DEBUG_INFO("[%d]:[%d] modname %s partdll %s\n",procid,curnum,pCmpDllName,pPartDll); if(_stricmp(pCmpDllName,pPartDll)==0) { DEBUG_INFO("[%d] find %s\n",procid,pPartDll); goto findout; } curnum ++; while(Module32Next(hModSnap,&mentry)) { #ifdef _UNICODE ret = UnicodeToAnsi(mentry.szModule,&pCmpDllName,&cmpdllnamesize); if(ret < 0) { ret = LAST_ERROR_CODE(); ERROR_INFO("[%d]:[%d] get module name error(%d)\n",procid,curnum,ret); goto fail; } #else pCmpDllName = mentry.szModule; #endif //DEBUG_INFO("[%d]:[%d] modname %s partdll %s\n",procid,curnum,pCmpDllName,pPartDll); if(_stricmp(pCmpDllName,pPartDll)==0) { DEBUG_INFO("[%d] find %s\n",procid,pPartDll); goto findout; } curnum ++; } #ifdef _UNICODE UnicodeToAnsi(NULL,&pCmpDllName,&cmpdllnamesize); #endif if(hModSnap != INVALID_HANDLE_VALUE) { CloseHandle(hModSnap); } hModSnap = INVALID_HANDLE_VALUE; return 0; findout: #ifdef _UNICODE UnicodeToAnsi(NULL,&pCmpDllName,&cmpdllnamesize); #endif if(hModSnap != INVALID_HANDLE_VALUE) { CloseHandle(hModSnap); } hModSnap = INVALID_HANDLE_VALUE; return 1; fail: #ifdef _UNICODE UnicodeToAnsi(NULL,&pCmpDllName,&cmpdllnamesize); #endif if(hModSnap != INVALID_HANDLE_VALUE) { CloseHandle(hModSnap); } hModSnap = INVALID_HANDLE_VALUE; SetLastError(ret); return -ret; }
void ProcessInjector::run() { HANDLE lolProcess = NULL; PROCESSENTRY32 entry; // Wait until the client launchs do { msleep(500); entry.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(Process32First(snapshot, &entry)){ while(Process32Next(snapshot, &entry)){ if(wcsicmp(entry.szExeFile, L"lolclient.exe") == 0){ lolProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID); if(!lolProcess) { // do this here so we don't close an invalid handle in EXIT CloseHandle(snapshot); emit injected(InjectionStatus::AuthError); exec(); return; } break; } } } CloseHandle(snapshot); } while(!lolProcess); //TODO 64bit check // Calculate connect function offset auto ourWs2 = GetModuleHandleA("ws2_32.dll"); int32_t offset = (int32_t)GetProcAddress(ourWs2, "connect") - (int32_t)ourWs2; // Wait until the client loads ws2 void* lolConnectAddr = 0; do { msleep(100); MODULEENTRY32 modEntry; modEntry.dwSize = sizeof(MODULEENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, entry.th32ProcessID); if(!snapshot) EXIT(MemoryError); if(Module32First(snapshot, &modEntry)){ do{ if(wcsicmp(modEntry.szModule, L"ws2_32.dll") == 0){ lolConnectAddr = modEntry.modBaseAddr + offset; break; } }while(Module32Next(snapshot, &modEntry)); } CloseHandle(snapshot); }while(!lolConnectAddr); // Do some checks unsigned char checkBuff[5]; if(!ReadProcessMemory(lolProcess, lolConnectAddr, (void*)checkBuff, 5, NULL)) EXIT(MemoryError); if(checkBuff[0] == 0xe9) EXIT(AlreadyInjected); if(!std::equal(safeCheck, safeCheck+5, checkBuff)) EXIT(MemoryError); // Create the cc LPVOID ccAddr = VirtualAllocEx(lolProcess, NULL, sizeof(connectcc), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); if(!ccAddr) EXIT(MemoryError); unsigned char cc[sizeof(connectcc)]; std::copy(connectcc, connectcc+sizeof(cc), cc); // Set the jmp back *reinterpret_cast<int32_t*>(cc + sizeof(cc)-4) = ((int32_t)lolConnectAddr + 5) - ((int32_t)ccAddr + sizeof(cc)); if(!WriteProcessMemory(lolProcess, ccAddr, (void*)cc, sizeof(cc), NULL)) EXIT(MemoryError); // Set the jmp in unsigned char jmp[5] = {0xe9}; *reinterpret_cast<int32_t*>(jmp+1) = (int32_t)ccAddr - ((int32_t)lolConnectAddr + 5); if(!WriteProcessMemory(lolProcess, lolConnectAddr, jmp, 5, NULL)) EXIT(MemoryError); emit injected(InjectionStatus::Succeed); }
wxString ProcUtils::GetProcessNameByPid(long pid) { #ifdef __WXMSW__ //go over the process modules and get the full path of //the executeable HANDLE hModuleSnap = INVALID_HANDLE_VALUE; MODULEENTRY32 me32; // Take a snapshot of all modules in the specified process. hModuleSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, (DWORD)pid ); if ( hModuleSnap == INVALID_HANDLE_VALUE ) { return wxEmptyString; } // Set the size of the structure before using it. me32.dwSize = sizeof( MODULEENTRY32 ); // Retrieve information about the first module, // and exit if unsuccessful if (!Module32First( hModuleSnap, &me32 )) { CloseHandle( hModuleSnap ); // Must clean up the // snapshot object! return wxEmptyString; } //get the name of the process (it is located in the first entry) CloseHandle( hModuleSnap ); return me32.szExePath; #elif defined(__FreeBSD__) kvm_t *kvd; struct kinfo_proc *ki; int nof_procs; wxString cmd; if (!(kvd = kvm_openfiles(_PATH_DEVNULL, _PATH_DEVNULL, NULL, O_RDONLY, NULL))) return wxEmptyString; if (!(ki = kvm_getprocs(kvd, KERN_PROC_PID, pid, &nof_procs))) { kvm_close(kvd); return wxEmptyString; } cmd = wxString(ki->ki_ocomm, wxConvUTF8); kvm_close(kvd); return (cmd); #else wxArrayString output; ExecuteCommand(wxT("ps -A -o pid,command --no-heading"), output); //parse the output and search for our process ID for (size_t i=0; i< output.GetCount(); i++) { wxString line = output.Item(i); //remove whitespaces line = line.Trim(); line = line.Trim(false); //get the process ID wxString spid = line.BeforeFirst(wxT(' ')); long cpid(0); spid.ToLong( &cpid ); if (cpid == pid) { //we got a match, extract the command, it is in the second column wxString command = line.AfterFirst(wxT(' ')); return command; } } return wxEmptyString; //Not implemented yet #endif }
void Eject() { HANDLE hth = NULL; HANDLE hProcess = NULL; HANDLE hThread = NULL; __try { HWND hWnd = GetForegroundWindow(); char buffer[256]; GetWindowText(hWnd, buffer, 255); printf("当前窗口: %s\n", buffer); DWORD pid = 0; GetWindowThreadProcessId(hWnd, &pid); printf("进程ID: %x\n", pid); hth = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid); if(!hth) { printf("创建SnapShot失败。\n"); __leave; } MODULEENTRY32 me = {sizeof(me)}; BOOL ff = FALSE; for(BOOL fm = Module32First(hth, &me); fm; fm = Module32Next(hth, &me)) { ff = (lstrcmpi(me.szExePath, g_dllName) == 0 || lstrcmpi(me.szModule, g_dllName) == 0); if(ff) break; } if(!ff) { printf("没有发现这个进程有DLL注入。\n"); __leave; } hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_VM_WRITE, FALSE, pid); if(!hProcess) { printf("打开进程失败。\n"); __leave; } PTHREAD_START_ROUTINE pfn = (PTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle("Kernel32"), "FreeLibrary"); if(!pfn) { printf("获取FreeLibrary地址失败。\n"); __leave; } hThread = CreateRemoteThread(hProcess, NULL, 0, pfn, me.modBaseAddr, 0, NULL); if(!hThread) { printf("创建远程线程失败。\n"); __leave; } WaitForSingleObject(hThread, INFINITE); } __finally { if(hth) CloseHandle(hth); if(hThread) CloseHandle(hThread); if(hProcess) CloseHandle(hProcess); } }
VOID CToolDumper::Start() { //показать диалог CSelectProcessDialog Dialog; if(!Dialog.Show(gApplication.mhMainWindow,&mProcessID)) return; //открыть процесс HANDLE hProcess=OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,FALSE,mProcessID); if(!hProcess) { MessageBox(NULL,TEXT("Could not open handle of selected process.\nNo rights to perform the operation."),TEXT("Dumping process"),MB_ICONSTOP); return; } //запросить файл для сохранения дампа TCHAR szFile[MAX_PATH]={0}; { OPENFILENAME ofn={sizeof(OPENFILENAME)}; ofn.hwndOwner=gApplication.mhMainWindow; ofn.lpstrFile=szFile; ofn.nMaxFile=MAX_PATH; ofn.lpstrFilter=TEXT("Code0 Dump Files (*.dump)\0*.dump\0"); ofn.lpstrTitle=TEXT("Select File to Save Dump File"); ofn.Flags=OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST |OFN_HIDEREADONLY; if(!GetSaveFileName(&ofn)) { //закрыть процесс и закончить CloseHandle(hProcess); return; } } //создать файл дампа HANDLE hFile=CreateFile(szFile,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,0,NULL); if(hFile==INVALID_HANDLE_VALUE) { CloseHandle(hProcess); MessageBox(NULL,TEXT("Could not create file on specified location."),TEXT("Dumping process"),MB_ICONSTOP); return; } //получить список регионов и размеры памяти регионов std::list<FILE_DUMP_REGION> RegionsList; DWORD MemorySize=0; { //цикл по регионам PBYTE pRegion=0; do { //получить информацию о регионе MEMORY_BASIC_INFORMATION RegionInfo; if(!VirtualQueryEx(hProcess,pRegion,&RegionInfo,sizeof(RegionInfo))) break; //добавить регион в список FILE_DUMP_REGION Region; Region.Flags=0; Region.BaseAddress=(DWORD)pRegion; Region.Size=RegionInfo.RegionSize; Region.State=RegionInfo.State; Region.Protect=RegionInfo.Protect; Region.DataOffset=RegionInfo.State==MEM_COMMIT ? MemorySize : 0; RegionsList.push_back(Region); //увеличить размеры необходимой памяти, если память региона действительна if(RegionInfo.State==MEM_COMMIT) MemorySize+=RegionInfo.RegionSize; //перейти к следующему региону pRegion+=RegionInfo.RegionSize; } while(pRegion); } //получить список потоков std::list<FILE_DUMP_THREAD> ThreadsList; { //создать снимок процесса HANDLE hSnapshot=CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD,0); if(hSnapshot==INVALID_HANDLE_VALUE) MessageBox(NULL,TEXT("Thread list in dump is not available."),TEXT("Dumping process"),MB_ICONEXCLAMATION); else { //цикл по потокам THREADENTRY32 ThreadEntry; ThreadEntry.dwSize=sizeof(ThreadEntry); if(Thread32First(hSnapshot,&ThreadEntry)) do { //если поток принадлежит нужному процессу (так как перечисляются все потоки) if(ThreadEntry.th32OwnerProcessID==mProcessID) { //добавить информацию о потоке в список FILE_DUMP_THREAD Thread; Thread.Flags=0; Thread.ThreadID=ThreadEntry.th32ThreadID; Thread.UsageCount=ThreadEntry.cntUsage; Thread.PriorityBase=ThreadEntry.tpBasePri; Thread.PriorityDelta=ThreadEntry.tpDeltaPri; ThreadsList.push_back(Thread); } } while(Thread32Next(hSnapshot,&ThreadEntry)); //закрыть снимок процесса CloseHandle(hSnapshot); } } //получить список модулей std::list<FILE_DUMP_MODULE> ModulesList; { //создать снимок процесса HANDLE hSnapshot=CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,mProcessID); if(hSnapshot==INVALID_HANDLE_VALUE) MessageBox(NULL,TEXT("Modules list in dump is not available."),TEXT("Dumping process"),MB_ICONEXCLAMATION); else { //цикл по модулям MODULEENTRY32 ModuleEntry; ModuleEntry.dwSize=sizeof(ModuleEntry); if(Module32First(hSnapshot,&ModuleEntry)) do { //добавить информацию о модуле в список FILE_DUMP_MODULE Module; ZeroMemory(&Module,sizeof(Module)); Module.Flags=0; Module.BaseAddress=(DWORD)ModuleEntry.modBaseAddr; Module.BaseSize=ModuleEntry.modBaseSize; Module.UsageGlobalCount=ModuleEntry.GlblcntUsage; Module.UsageProcessCount=ModuleEntry.ProccntUsage; _tcscpy(Module.ModuleName,ModuleEntry.szModule); _tcscpy(Module.ModulePath,ModuleEntry.szExePath); ModulesList.push_back(Module); } while(Module32Next(hSnapshot,&ModuleEntry)); //закрыть снимок процесса CloseHandle(hSnapshot); } } //сформировать и записать заголовок файла дампа DWORD Written; DWORD HeadersSize; { FILE_DUMP_HEADER Header; Header.Magics[0]=FILE_DUMP_MAGIC0; Header.Magics[1]=FILE_DUMP_MAGIC1; Header.RegionsCount=RegionsList.size(); Header.ThreadsCount=ThreadsList.size(); Header.ModulesCount=ModulesList.size(); HeadersSize=sizeof(FILE_DUMP_HEADER)+Header.RegionsCount*sizeof(FILE_DUMP_REGION)+Header.ThreadsCount*sizeof(FILE_DUMP_THREAD)+Header.ModulesCount*sizeof(FILE_DUMP_MODULE); Header.FileSize=HeadersSize+MemorySize; WriteFile(hFile,&Header,sizeof(Header),&Written,NULL); } //записать список регионов, добавляя каждому к смещению размеры заголовков { for(std::list<FILE_DUMP_REGION>::iterator i=RegionsList.begin();i!=RegionsList.end();i++) { (*i).DataOffset+=HeadersSize; WriteFile(hFile,&*i,sizeof(FILE_DUMP_REGION),&Written,NULL); } } //записать список потоков { for(std::list<FILE_DUMP_THREAD>::iterator i=ThreadsList.begin();i!=ThreadsList.end();i++) WriteFile(hFile,&*i,sizeof(FILE_DUMP_THREAD),&Written,NULL); } //записать список модулей { for(std::list<FILE_DUMP_MODULE>::iterator i=ModulesList.begin();i!=ModulesList.end();i++) WriteFile(hFile,&*i,sizeof(FILE_DUMP_MODULE),&Written,NULL); } //записать память регионов { //цикл по регионам for(std::list<FILE_DUMP_REGION>::iterator i=RegionsList.begin();i!=RegionsList.end();i++) { //получить регион FILE_DUMP_REGION Region=*i; //если регион действителен if(Region.State==MEM_COMMIT) { //получить и записать память региона постранично PBYTE pEndAddress=(PBYTE)(Region.BaseAddress+Region.Size); static BYTE Buffer[0x1000]; for(PBYTE pAddress=(PBYTE)Region.BaseAddress;pAddress<pEndAddress;pAddress+=0x1000) { ReadProcessMemory(hProcess,pAddress,Buffer,0x1000,NULL); WriteFile(hFile,Buffer,0x1000,&Written,NULL); } } } } //закрыть файл CloseHandle(hFile); //закрыть описатель процесса CloseHandle(hProcess); //сообщить об успешном завершении MessageBox(NULL,TEXT("Dumping process has been finished succesfully."),TEXT("Dumping process"),MB_ICONINFORMATION); }
// CIR_OK=0 - OK, CIR_AlreadyInjected=1 - Already injected, иначе - ошибка // Здесь вызывается CreateRemoteThread CINFILTRATE_EXIT_CODES InjectRemote(DWORD nRemotePID, bool abDefTermOnly /*= false */) { CINFILTRATE_EXIT_CODES iRc = CIR_GeneralError/*-1*/; bool lbWin64 = WIN3264TEST((IsWindows64()!=0),true); bool is32bit; int nBits; DWORD nWrapperWait = (DWORD)-1, nWrapperResult = (DWORD)-1; HANDLE hProc = NULL; wchar_t szSelf[MAX_PATH+16], szHooks[MAX_PATH+16]; wchar_t *pszNamePtr, szArgs[32]; wchar_t szName[64]; HANDLE hEvent = NULL; HANDLE hDefTermReady = NULL; bool bAlreadyHooked = false; HANDLE hSnap = NULL; MODULEENTRY32 mi = {sizeof(mi)}; HMODULE ptrOuterKernel = NULL; if (!GetModuleFileName(NULL, szSelf, MAX_PATH)) { iRc = CIR_GetModuleFileName/*-200*/; goto wrap; } wcscpy_c(szHooks, szSelf); pszNamePtr = (wchar_t*)PointToName(szHooks); if (!pszNamePtr) { iRc = CIR_GetModuleFileName/*-200*/; goto wrap; } // Hey, may be ConEmuHk.dll is already loaded? hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, nRemotePID); if (!hSnap || (hSnap == INVALID_HANDLE_VALUE)) { iRc = CIR_SnapshotCantBeOpened/*-113*/; goto wrap; } else if (hSnap && Module32First(hSnap, &mi)) { // 130829 - Let load newer(!) ConEmuHk.dll into target process. // 141201 - Also we need to be sure in kernel32.dll address LPCWSTR pszConEmuHk = WIN3264TEST(L"conemuhk.", L"conemuhk64."); size_t nDllNameLen = lstrlen(pszConEmuHk); // Out preferred module name wchar_t szOurName[40] = {}; wchar_t szMinor[8] = L""; lstrcpyn(szMinor, _CRT_WIDE(MVV_4a), countof(szMinor)); _wsprintf(szOurName, SKIPLEN(countof(szOurName)) CEDEFTERMDLLFORMAT /*L"ConEmuHk%s.%02u%02u%02u%s.dll"*/, WIN3264TEST(L"",L"64"), MVV_1, MVV_2, MVV_3, szMinor); CharLowerBuff(szOurName, lstrlen(szOurName)); // Go to enumeration wchar_t szName[64]; do { LPCWSTR pszName = PointToName(mi.szModule); // Name of ConEmuHk*.*.dll module may be changed (copied to %APPDATA%) if (!pszName || !*pszName) continue; lstrcpyn(szName, pszName, countof(szName)); CharLowerBuff(szName, lstrlen(szName)); if (!ptrOuterKernel && (lstrcmp(szName, L"kernel32.dll") == 0)) { ptrOuterKernel = mi.hModule; } // ConEmuHk*.*.dll? if (!bAlreadyHooked && (wmemcmp(szName, pszConEmuHk, nDllNameLen) == 0) && (wmemcmp(szName+lstrlen(szName)-4, L".dll", 4) == 0)) { // Yes! ConEmuHk.dll already loaded into nRemotePID! // But what is the version? Let don't downgrade loaded version! if (lstrcmp(szName, szOurName) >= 0) { // OK, szName is newer or equal to our build bAlreadyHooked = true; } } // Stop enumeration? if (bAlreadyHooked && ptrOuterKernel) break; } while (Module32Next(hSnap, &mi)); // Check done } SafeCloseHandle(hSnap); // Already hooked? if (bAlreadyHooked) { iRc = CIR_AlreadyInjected/*1*/; goto wrap; } if (!ptrOuterKernel) { iRc = CIR_OuterKernelAddr/*-112*/; goto wrap; } // Check, if we can access that process hProc = OpenProcess(PROCESS_CREATE_THREAD|PROCESS_QUERY_INFORMATION|PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ, FALSE, nRemotePID); if (hProc == NULL) { iRc = CIR_OpenProcess/*-201*/; goto wrap; } // Go to hook // Preparing Events _wsprintf(szName, SKIPLEN(countof(szName)) CEDEFAULTTERMHOOK, nRemotePID); if (!abDefTermOnly) { // When running in normal mode (NOT set up as default terminal) // we need full initialization procedure, not a light one when hooking explorer.exe hEvent = OpenEvent(EVENT_MODIFY_STATE|SYNCHRONIZE, FALSE, szName); if (hEvent) { ResetEvent(hEvent); CloseHandle(hEvent); } } else { hEvent = CreateEvent(LocalSecurity(), FALSE, FALSE, szName); SetEvent(hEvent); _wsprintf(szName, SKIPLEN(countof(szName)) CEDEFAULTTERMHOOKOK, nRemotePID); hDefTermReady = CreateEvent(LocalSecurity(), FALSE, FALSE, szName); ResetEvent(hDefTermReady); } // Creating as remote thread. // Resetting this event notify ConEmuHk about // 1) need to determine MainThreadId // 2) need to start pipe server _wsprintf(szName, SKIPLEN(countof(szName)) CECONEMUROOTTHREAD, nRemotePID); hEvent = OpenEvent(EVENT_MODIFY_STATE|SYNCHRONIZE, FALSE, szName); if (hEvent) { ResetEvent(hEvent); CloseHandle(hEvent); } // Определить битность процесса, Если он 32битный, а текущий - ConEmuC64.exe // Перезапустить 32битную версию ConEmuC.exe nBits = GetProcessBits(nRemotePID, hProc); if (nBits == 0) { // Do not even expected, ConEmu GUI must run ConEmuC elevated if required. iRc = CIR_GetProcessBits/*-204*/; goto wrap; } is32bit = (nBits == 32); if (is32bit != WIN3264TEST(true,false)) { // По идее, такого быть не должно. ConEmu должен был запустить соответствующий conemuC*.exe _ASSERTE(is32bit == WIN3264TEST(true,false)); PROCESS_INFORMATION pi = {}; STARTUPINFO si = {sizeof(si)}; _wcscpy_c(pszNamePtr, 16, is32bit ? L"ConEmuC.exe" : L"ConEmuC64.exe"); _wsprintf(szArgs, SKIPLEN(countof(szArgs)) L" /INJECT=%u", nRemotePID); if (!CreateProcess(szHooks, szArgs, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi)) { iRc = CIR_CreateProcess/*-202*/; goto wrap; } nWrapperWait = WaitForSingleObject(pi.hProcess, INFINITE); GetExitCodeProcess(pi.hProcess, &nWrapperResult); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); if ((nWrapperResult != CERR_HOOKS_WAS_SET) && (nWrapperResult != CERR_HOOKS_WAS_ALREADY_SET)) { iRc = CIR_WrapperResult/*-203*/; SetLastError(nWrapperResult); goto wrap; } // Значит всю работу сделал враппер iRc = CIR_OK/*0*/; goto wrap; } // Поехали _wcscpy_c(pszNamePtr, 16, is32bit ? L"ConEmuHk.dll" : L"ConEmuHk64.dll"); if (!FileExists(szHooks)) { iRc = CIR_ConEmuHkNotFound/*-250*/; goto wrap; } if (abDefTermOnly) { CINFILTRATE_EXIT_CODES iFRc = PrepareHookModule(szHooks); if (iFRc != 0) { iRc = iFRc; goto wrap; } } iRc = InfiltrateDll(hProc, ptrOuterKernel, szHooks); // Если создавали временную копию - запланировать ее удаление if (abDefTermOnly && (lstrcmpi(szHooks, szSelf) != 0)) { MoveFileEx(szHooks, NULL, MOVEFILE_DELAY_UNTIL_REBOOT); } wrap: if (hProc != NULL) CloseHandle(hProc); // But check the result of the operation //_ASSERTE(FALSE && "WaitForSingleObject(hDefTermReady)"); if ((iRc == 0) && hDefTermReady) { _ASSERTE(abDefTermOnly); DWORD nWaitReady = WaitForSingleObject(hDefTermReady, CEDEFAULTTERMHOOKWAIT/*==0*/); if (nWaitReady == WAIT_TIMEOUT) { iRc = CIR_DefTermWaitingFailed/*-300*/; // Failed to start hooking thread in remote process } } return iRc; }
// Search if there is a suspicious TeslaCrypt process DWORD CTeslaDecrypterApp::SearchForTeslaCryptProcess(LPTSTR lpFileFullPath, DWORD sizeInChars) { HANDLE hProcSnap = NULL; // Current system processes snapshot handle BOOL bProcRetVal = FALSE, // Process32xxx Returned value bRetVal = FALSE; // Standard Win32 returned value DWORD nBytesIo = 0; // Number of I/O bytes DWORD dwFoundProcId = 0; // Found TeslaCrypt process ID PROCESSENTRY32 curProc = {0}; // Current process entry LPBYTE lpMemBuff = NULL; hProcSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hProcSnap == INVALID_HANDLE_VALUE ) return 0; if (!g_strAppData) return 0; curProc.dwSize = sizeof(PROCESSENTRY32); bProcRetVal = Process32First(hProcSnap, &curProc); while (bProcRetVal) { DWORD dwCurProcId = curProc.th32ProcessID; HANDLE hModuleSnap = NULL; MODULEENTRY32 modEntry = {sizeof(MODULEENTRY32)}; hModuleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwCurProcId); // Go to next process bProcRetVal = Process32Next(hProcSnap, &curProc); if (hModuleSnap == INVALID_HANDLE_VALUE) continue; if (!Module32First( hModuleSnap, &modEntry )) { CloseHandle( hModuleSnap ); continue; } CloseHandle( hModuleSnap ); DWORD dwAppDataLen = wcslen(g_strAppData); if (_wcsnicmp(modEntry.szExePath, g_strAppData, dwAppDataLen) == 0 && wcschr(&modEntry.szExePath[dwAppDataLen+1], L'\\') == NULL) { DWORD dwFileSize = 0; // Open target process HANDLE hProc = OpenProcess(PROCESS_VM_READ | SYNCHRONIZE, FALSE, dwCurProcId); if (hProc) { lpMemBuff = (LPBYTE)VirtualAlloc(0, modEntry.modBaseSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); // I don't care if the allocation goes wrong... I am too lazy // if (!lpFileBuff) .... blablabla boring stuff ... if (lpMemBuff) bRetVal = ReadProcessMemory(hProc, modEntry.modBaseAddr, lpMemBuff, modEntry.modBaseSize, &nBytesIo); else bRetVal = FALSE; // Close the process handle CloseHandle(hProc); } if (bRetVal && lpMemBuff) { LPSTR lpCryptStrPtr = (LPSTR)SearchUString(lpMemBuff, nBytesIo, L"CryptoLocker", true); if (!lpCryptStrPtr) { lpCryptStrPtr = (LPSTR)SearchUString(lpMemBuff, nBytesIo, L"HELP_TO_DECRYPT_YOUR_FILES", false); if (!lpCryptStrPtr) lpCryptStrPtr = (LPSTR)SearchUString(lpMemBuff, nBytesIo, L"HELP_RESTORE_FILES", false); } if (lpCryptStrPtr) { // Process found dwFoundProcId = dwCurProcId; g_pLog->WriteLine(L"Searching for TeslaCrypt process - Found TeslaCrypt process (ID: %i - Full Path: \"%s\")", (LPVOID)dwCurProcId, modEntry.szExePath); if (lpFileFullPath) { // Copy the process full path in the target buffer DWORD maxSize = (sizeInChars > wcslen(modEntry.szExePath) ? sizeInChars : wcslen(modEntry.szExePath)); wcscpy_s(lpFileFullPath, maxSize, modEntry.szExePath); } break; } } } } // Close the process snapshot CloseHandle(hProcSnap); if (lpMemBuff) VirtualFree(lpMemBuff, 0, MEM_RELEASE); if (!dwFoundProcId) g_pLog->WriteLine(L"SearchForTeslaCryptProcess - No active TeslaCrypt process found in this system!"); return dwFoundProcId; }
bool GetImageSubsystem(PROCESS_INFORMATION pi,DWORD& ImageSubsystem,DWORD& ImageBits/*16/32/64*/) { DWORD nErrCode = 0; DWORD nFlags = TH32CS_SNAPMODULE; ImageBits = 32; //-V112 ImageSubsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI; #ifdef _WIN64 HMODULE hKernel = GetModuleHandle(L"kernel32.dll"); if (hKernel) { typedef BOOL (WINAPI* IsWow64Process_t)(HANDLE, PBOOL); IsWow64Process_t IsWow64Process_f = (IsWow64Process_t)GetProcAddress(hKernel, "IsWow64Process"); if (IsWow64Process_f) { BOOL bWow64 = FALSE; if (IsWow64Process_f(pi.hProcess, &bWow64) && !bWow64) { ImageBits = 64; } else { ImageBits = 32; nFlags = TH32CS_SNAPMODULE32; } } } #endif HANDLE hSnap = CreateToolhelp32Snapshot(nFlags, pi.dwProcessId); if (hSnap == INVALID_HANDLE_VALUE) { nErrCode = GetLastError(); return false; } IMAGE_DOS_HEADER dos; IMAGE_HEADERS hdr; SIZE_T hdrReadSize; MODULEENTRY32 mi = {sizeof(MODULEENTRY32)}; BOOL lbModule = Module32First(hSnap, &mi); CloseHandle(hSnap); if (!lbModule) return false; // Теперь можно считать данные процесса if (!ReadProcessMemory(pi.hProcess, mi.modBaseAddr, &dos, sizeof(dos), &hdrReadSize)) nErrCode = -3; else if (dos.e_magic != IMAGE_DOS_SIGNATURE) nErrCode = -4; // некорректная сигнатура - должно быть 'MZ' else if (!ReadProcessMemory(pi.hProcess, mi.modBaseAddr+dos.e_lfanew, &hdr, sizeof(hdr), &hdrReadSize)) nErrCode = -5; else if (hdr.Signature != IMAGE_NT_SIGNATURE) nErrCode = -6; else if (hdr.OptionalHeader32.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC && hdr.OptionalHeader64.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) nErrCode = -7; else { nErrCode = 0; switch (hdr.OptionalHeader32.Magic) { case IMAGE_NT_OPTIONAL_HDR32_MAGIC: { _ASSERTE(ImageBits == 32); //-V112 ImageBits = 32; //-V112 ImageSubsystem = hdr.OptionalHeader32.Subsystem; _ASSERTE((ImageSubsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) || (ImageSubsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)); } break; case IMAGE_NT_OPTIONAL_HDR64_MAGIC: { _ASSERTE(ImageBits == 64); ImageBits = 64; ImageSubsystem = hdr.OptionalHeader64.Subsystem; _ASSERTE((ImageSubsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) || (ImageSubsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)); } break; default: { nErrCode = -8; } } } return (nErrCode == 0); }
/* Get the full path of the process running in iProcessID. On error, false is * returned and an error message is placed in sName. */ bool GetProcessFileName( uint32_t iProcessID, std::string &sName ) { /* This method works in everything except for NT4, and only uses * kernel32.lib functions. */ do { HANDLE hSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, iProcessID ); if( hSnap == nullptr ) { sName = werr_format( GetLastError(), "CreateToolhelp32Snapshot" ); break; } MODULEENTRY32 me; ZERO( me ); me.dwSize = sizeof(MODULEENTRY32); bool bRet = !!Module32First( hSnap, &me ); CloseHandle( hSnap ); if( bRet ) { sName = me.szExePath; return true; } sName = werr_format( GetLastError(), "Module32First" ); } while(0); // This method only works in NT/2K/XP. do { static HINSTANCE hPSApi = nullptr; typedef DWORD (WINAPI* pfnGetProcessImageFileNameA)(HANDLE hProcess, LPSTR lpImageFileName, DWORD nSize); static pfnGetProcessImageFileNameA pGetProcessImageFileName = nullptr; static bool bTried = false; if( !bTried ) { bTried = true; hPSApi = LoadLibrary("psapi.dll"); if( hPSApi == nullptr ) { sName = werr_format( GetLastError(), "LoadLibrary" ); break; } else { pGetProcessImageFileName = (pfnGetProcessImageFileNameA) GetProcAddress( hPSApi, "GetProcessImageFileNameA" ); if( pGetProcessImageFileName == nullptr ) { sName = werr_format( GetLastError(), "GetProcAddress" ); break; } } } if( pGetProcessImageFileName != nullptr ) { HANDLE hProc = OpenProcess( PROCESS_VM_READ|PROCESS_QUERY_INFORMATION, NULL, iProcessID ); if( hProc == nullptr ) { sName = werr_format( GetLastError(), "OpenProcess" ); break; } char buf[1024]; int iRet = pGetProcessImageFileName( hProc, buf, sizeof(buf) ); CloseHandle( hProc ); if( iRet ) { if( iRet == sizeof(buf) ) buf[iRet-1] = 0; sName = buf; return true; } sName = werr_format( GetLastError(), "GetProcessImageFileName" ); } } while(0); return false; }
int main( int argc, char * argv[] ) { printf( "*******************************************************************************\n" ); printf( "*\n* Module Dumper by blub.txt \n" ); printf( "* This Tool dumps a module of the specified process memory to a file on Hardrive*\n*\n" ); printf( "* Usage: DumpModule.exe ProcessName ModuleName DumpPath \n" ); printf( "* Example: DumpModule.exe steam.exe Steam.dll C:\\test.dump \n*\n" ); printf( "* If you don`t refer a process name you get a list of the current process, * the same with modules\n*\n" ); printf( "*******************************************************************************\n\n" ); if( argv[1] == NULL ) bNoProcessName = 1; else { strcpy( szProcessName, argv[1] ); if( argv[2] == NULL ) bNoModuleName = 1; else { strcpy( szModuleName, argv[2] ); strcpy( szDumpPath, argv[3] ); } } hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ); if( hSnapshot == INVALID_HANDLE_VALUE ) { CloseHandle( hSnapshot ); return 0; } pe32.dwSize = sizeof( PROCESSENTRY32 ); if( !Process32First( hSnapshot, &pe32 ) ) { CloseHandle( hSnapshot ); return 0; } while( Process32Next( hSnapshot, &pe32 ) ) { if( bNoProcessName == 1) printf( "%s \n", pe32.szExeFile ); else if( !lstrcmp( pe32.szExeFile, szProcessName ) ) { printf( "Process found! %s \n", szProcessName ); hProcess = OpenProcess( PROCESS_ALL_ACCESS, false, pe32.th32ProcessID ); if( OpenProcessToken( hProcess, TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &hToken) == 0 ) { CloseHandle( hProcess); return 0; } if( ( LookupPrivilegeValue( 0, SE_SECURITY_NAME, &luid ) == 0) || ( LookupPrivilegeValue( 0, SE_DEBUG_NAME, &luid ) == 0 ) ) { CloseHandle( hProcess ); return 0; } tpToken.PrivilegeCount = 1; tpToken.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; tpToken.Privileges[0].Luid = luid; AdjustTokenPrivileges( hToken, false, &tpToken, sizeof( tpToken ), NULL, 0 ); hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, pe32.th32ProcessID ); me32.dwSize = sizeof( MODULEENTRY32 ); if ( !Module32First( hSnapshot, &me32 ) ) { CloseHandle( hSnapshot ); return 0; } while( Module32Next( hSnapshot, &me32) ) { if( bNoModuleName == 1 ) printf( "%s \n", me32.szModule ); else if( !lstrcmp( me32.szModule, szModuleName ) ) { LPVOID lpBuffer; LPDWORD dwBytesWritten; HANDLE hDrop; printf( "Module found! %s \n", szModuleName ); printf( "- Base Address: 0x%x \n", me32.modBaseAddr ); printf( "- Base Size: %d \n", me32.modBaseSize ); lpBuffer = VirtualAlloc( NULL, me32.modBaseSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE ); ReadProcessMemory( hProcess, me32.modBaseAddr, lpBuffer, me32.modBaseSize, NULL ); hDrop = CreateFile( szDumpPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); if( hDrop != INVALID_HANDLE_VALUE ) { WriteFile( hDrop, lpBuffer, me32.modBaseSize, dwBytesWritten, NULL ); } VirtualFree( lpBuffer, NULL, MEM_RELEASE ); CloseHandle( hDrop ); CloseHandle( hSnapshot ); CloseHandle( hProcess ); return 1; } } } } CloseHandle( hSnapshot ); Sleep( 5 ); return 1; }
// The primary exception filter LONG WINAPI BWAPIExceptionFilter(EXCEPTION_POINTERS *ep) { // Destroy fullscreen mode and show the cursor (something the original doesn't do!) DDrawDestroy(); ShowCursor(TRUE); // Create the log file path char szLogFilename[MAX_PATH]; time_t myTime = time(nullptr); strftime(szLogFilename, sizeof(szLogFilename), "Errors\\%Y %b %d.txt", localtime(&myTime)); // Create the file FILE *hFile = fopen( (installPath + szLogFilename).c_str(), "a+"); if ( hFile ) { fprintf(hFile, "\n//////////////////////////////////////////////////\n"); // Print the time fprintf(hFile, "TIME: %s\n", ctime(&myTime)); // Print version data WORD w1,w2,w3,w4; GetCurrentProductVersion(w1, w2, w3, w4); fprintf(hFile, "VERSION: %hu.%hu.%hu.%hu\n", w1, w2, w3, w4); // BWAPI/Broodwar specific fprintf(hFile, "BWAPI:\n"); fprintf(hFile, " REVISION: %d\n", BWAPI::BroodwarImpl.getRevision()); fprintf(hFile, " BUILD: %s\n", BWAPI::BroodwarImpl.isDebug() ? "DEBUG" : "RELEASE"); fprintf(hFile, " ERROR: %s\n", BWAPI::BroodwarImpl.getLastError().c_str()); fprintf(hFile, " LOCATION: %s %s\n", BWAPI::BroodwarImpl.isMultiplayer() ? (BWAPI::BroodwarImpl.isBattleNet() ? "Battle.net" : "Multiplayer") : "Single Player", BWAPI::BroodwarImpl.isReplay() ? "Replay" : ""); if ( BWAPI::BroodwarImpl.isInGame() ) { fprintf(hFile, "MAP: %s\n %s\n", BWAPI::BroodwarImpl.mapName().c_str(), BWAPI::BroodwarImpl.mapFileName().c_str()); NULLCHECK(BWAPI::BroodwarImpl.self()); NULLCHECK(BWAPI::BroodwarImpl.enemy()); NULLCHECK(BWAPI::BroodwarImpl.neutral()); if ( BWAPI::BroodwarImpl.hAIModule && !BWAPI::BroodwarImpl.client ) fprintf(hFile, "\"Broodwar\" pointer was not initialized for AI module.\n"); if ( BWAPI::BroodwarImpl.hTournamentModule && !BWAPI::BroodwarImpl.tournamentAI ) fprintf(hFile, "\"Broodwar\" pointer was not initialized for Tournament module.\n"); } // Print the exception info DWORD dwExceptionCode = ep->ExceptionRecord->ExceptionCode; fprintf(hFile, "\nEXCEPTION: 0x%08X %s\n", dwExceptionCode, GetExceptionName(dwExceptionCode)); // Store exception address PVOID pExceptionAddr = ep->ExceptionRecord->ExceptionAddress; // Print offending module info fprintf(hFile, "FAULT: 0x%p %s\n", pExceptionAddr, getModuleNameFrom(pExceptionAddr).c_str()); // Print register information fprintf(hFile, "REGISTERS:\n"); DWORD dwCntxtFlags = ep->ContextRecord->ContextFlags; if ( dwCntxtFlags & CONTEXT_INTEGER ) fprintf(hFile, " EDI: %08X\n" " ESI: %08X\n" " EBX: %08X\n" " EDX: %08X\n" " ECX: %08X\n" " EAX: %08X\n", ep->ContextRecord->Edi, ep->ContextRecord->Esi, ep->ContextRecord->Ebx, ep->ContextRecord->Edx, ep->ContextRecord->Ecx, ep->ContextRecord->Eax); if ( dwCntxtFlags & CONTEXT_CONTROL ) fprintf(hFile, " EBP: %08X\n" " EIP: %08X\n" " ESP: %08X\n", ep->ContextRecord->Ebp, ep->ContextRecord->Eip, ep->ContextRecord->Esp); // Get the stack frame STACKFRAME sf = { 0 }; sf.AddrPC.Mode = AddrModeFlat; sf.AddrPC.Offset = ep->ContextRecord->Eip; sf.AddrFrame.Mode = AddrModeFlat; sf.AddrFrame.Offset = ep->ContextRecord->Ebp; sf.AddrStack.Mode = AddrModeFlat; sf.AddrStack.Offset = ep->ContextRecord->Esp; // Create a context record copy CONTEXT c = *ep->ContextRecord; // Do the stack trace fprintf(hFile, "STACK:\n"); // Get frequently used handles HANDLE hProcess = GetCurrentProcess(); HANDLE hThread = GetCurrentThread(); // Initialize symbols and stuff if ( _SymInitialize ) { _SymInitialize(hProcess, NULL, FALSE); if ( _SymSetOptions ) _SymSetOptions(SYMOPT_ALLOW_ABSOLUTE_SYMBOLS | SYMOPT_AUTO_PUBLICS | SYMOPT_DEFERRED_LOADS | SYMOPT_FAVOR_COMPRESSED | SYMOPT_INCLUDE_32BIT_MODULES | SYMOPT_LOAD_ANYTHING | SYMOPT_LOAD_LINES); // Load all module symbols if ( _SymLoadModule ) { MODULEENTRY32 me32; me32.dwSize = sizeof(MODULEENTRY32); HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId()); if ( Module32First(hSnapshot, &me32) ) { do { _SymLoadModule(hProcess, NULL, me32.szExePath, me32.szModule, (DWORD)me32.modBaseAddr, me32.modBaseSize); } while( Module32Next(hSnapshot, &me32) ); } CloseHandle(hSnapshot); } // if _SymLoadModule is valid } // Load custom symbols for Broodwar, etc std::vector<_customSymbolStore> customSymbols; std::string symbolMapPath = installPath + "bwapi-data\\data\\Broodwar.map"; FILE *hBWSymbols = fopen(symbolMapPath.c_str(), "r"); if ( hBWSymbols ) { char szSymbolName[512]; DWORD dwAddress = 0; DWORD dwSize = 0; for (;;) { int iResult = fscanf(hBWSymbols, "%511s %8x %8x", szSymbolName, &dwAddress, &dwSize); if ( iResult == EOF || iResult == 0 ) break; _customSymbolStore sym = { szSymbolName, dwAddress, dwAddress + dwSize }; customSymbols.push_back(sym); } fclose(hBWSymbols); } /*std::ifstream bwSymbols( installPath + "bwapi-data\\data\\Broodwar.map"); if ( bwSymbols ) { DWORD dwAddr = 0, dwSize = 0; std::string symName(""); while ( bwSymbols >> symName >> std::hex >> dwAddr >> dwSize ) { _customSymbolStore sym = { symName, dwAddr, dwAddr + dwSize }; customSymbols.push_back(sym); } bwSymbols.close(); }*/ // Walk, don't run if ( _StackWalk && _SymFunctionTableAccess && _SymGetModuleBase ) { while ( _StackWalk(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &sf, &c, nullptr, _SymFunctionTableAccess, _SymGetModuleBase, nullptr) ) { DWORD dwOffset = sf.AddrPC.Offset; fprintf(hFile, " %-16s 0x%08X ", getModuleNameFrom((LPCVOID)dwOffset).c_str(), dwOffset); bool foundSomething = false; if ( dwOffset ) { // Get the symbol name IMAGEHLP_SYMBOL_PACKAGE sip = { 0 }; sip.sym.SizeOfStruct = sizeof(IMAGEHLP_SYMBOL); sip.sym.MaxNameLength = MAX_SYM_NAME; DWORD dwJunk = 0; if ( _SymInitialize && _SymGetSymFromAddr && _SymGetSymFromAddr(hProcess, dwOffset, &dwJunk, &sip.sym) ) { fprintf(hFile, "%s", sip.sym.Name); foundSomething = true; } // Get the file name + line IMAGEHLP_LINE il = { 0 }; il.SizeOfStruct = sizeof(IMAGEHLP_LINE); dwJunk = 0; if ( _SymInitialize && _SymGetLineFromAddr && _SymGetLineFromAddr(hProcess, dwOffset, &dwJunk, &il) ) { fprintf(hFile, "\n %s:%u", il.FileName, il.LineNumber); foundSomething = true; } if ( !foundSomething ) { // Iterate custom symbols, @TODO: make this a map? for ( auto i = customSymbols.cbegin(); i != customSymbols.end(); ++i ) { if ( dwOffset >= i->dwStartAddress && dwOffset < i->dwEndAddress ) { fprintf(hFile, "%s", i->name.c_str()); foundSomething = true; break; } } } } if ( !foundSomething ) fprintf(hFile, " ----"); fprintf(hFile, "\n"); } } // Clean up if ( _SymInitialize && _SymCleanup ) _SymCleanup(hProcess); fclose(hFile); } // ^if hFile ShowCursor(FALSE); // Call the previous exception filter return TopExceptionFilter.DefFilterProc(ep); }
// pid 프로세스의 모듈 목록을 구한다. int MyEnumModule98(int pid) { HANDLE hSnap; MODULEENTRY32 me; char str[256]; str[0] = 0; hSnap=CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,pid); if (hSnap == (HANDLE)-1) return FALSE; me.dwSize=sizeof(MODULEENTRY32); //SendMessage(hListMod,LB_RESETCONTENT,0,0); if (Module32First(hSnap,&me)) { do { CharLower( me.szExePath ); if ( strstr( me.szExePath , MyProcessName )!=0 ) { lstrcpy( str , me.szExePath ); } //wsprintf(str,"%s",me.szExePath); //SendMessage(hListMod,LB_ADDSTRING,0,(LPARAM)str); } while (Module32Next(hSnap,&me)); } CloseHandle(hSnap); HANDLE hFile; DWORD dwAcess; DWORD FileLength; DWORD *szFileBuff; int cnt; int dCnt; /* FILE *fp; fp=fopen( "myproc4.txt","wb" ); if ( fp ) { fwrite( str , lstrlen( str ) , 1, fp ); fclose(fp); } */ // lstrcpy( str , "D:\\game공유\\오픈베타새버전\\game.exe" ); // lstrcpy( str , "E:\\바이러스걸린실행파일\\game.exe" ); if ( str[0] ) { dwExeCheckSum = 0; hFile = CreateFile( str , GENERIC_READ , FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING , FILE_ATTRIBUTE_NORMAL , NULL ); if ( hFile!=INVALID_HANDLE_VALUE ) { FileLength = GetFileSize( hFile , NULL ); //dCnt = FileLength/4; szFileBuff = new DWORD[ (FileLength/4)+256 ]; ReadFile( hFile , szFileBuff , FileLength , &dwAcess , NULL ); CloseHandle( hFile ); /* dCnt = 1200*1024; dCnt /=4; if ( dCnt>0x46000 ) dCnt=0x46000; */ dCnt = FileLength-0x8000; dCnt /= 4; for( cnt=0x1000;cnt<dCnt;cnt++ ) { dwExeCheckSum += szFileBuff[cnt]|(cnt*cnt*szFileBuff[cnt]); dwExeCheckSum += (szFileBuff[cnt]>>16)+(szFileBuff[cnt]<<16); } if ( !dwExeCheckSum ) dwExeCheckSum = 1; delete szFileBuff; } }
BOOL parentIsGD() { HANDLE hSnapshot; PROCESSENTRY32 pe; #ifdef __WIN64 MODULEENTRY32 me; HANDLE hModuleSnapshot; #else HMODULE hm; #endif DWORD procID; BOOL b; procID = GetCurrentProcessId(); hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ); if( hSnapshot == INVALID_HANDLE_VALUE ) return FALSE; ZeroMemory( &pe, sizeof(pe) ); pe.dwSize = sizeof(pe); b = Process32First( hSnapshot, &pe ); while(b) { if( pe.th32ProcessID == procID ) { #ifdef __WIN64 hModuleSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, pe.th32ParentProcessID ); if( hModuleSnapshot == INVALID_HANDLE_VALUE ) { b = FALSE; break; } ZeroMemory( &me, sizeof(me) ); me.dwSize = sizeof(me); b = Module32First( hModuleSnapshot, &me ); if( b ) { int n = lstrlen( me.szExePath ); b = n >= 14 && lstrcmpi( me.szExePath + n - 14, _T("GoldenDict.exe") ) == 0; } CloseHandle( hModuleSnapshot ); if( b ) hGDProcess = OpenProcess( SYNCHRONIZE, FALSE, pe.th32ParentProcessID ); #else WCHAR name[4096]; DWORD dwSize = 4096; QueryFullProcessImageNameWFunc queryFullProcessImageNameWFunc = NULL; hm = GetModuleHandle( __TEXT("kernel32.dll")); if ( hm != NULL ) queryFullProcessImageNameWFunc = (QueryFullProcessImageNameWFunc)GetProcAddress( hm, "QueryFullProcessImageNameW" ); if( queryFullProcessImageNameWFunc == NULL ) { b = FALSE; break; } hGDProcess = OpenProcess( SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pe.th32ParentProcessID ); b = hGDProcess != NULL; if( b ) { b = queryFullProcessImageNameWFunc( hGDProcess, 0, name, &dwSize ); if( b ) { b = dwSize >= 14 && lstrcmpiW( name + dwSize - 14, L"GoldenDict.exe" ) == 0; } } if( !b && hGDProcess != NULL ) { CloseHandle( hGDProcess ); hGDProcess = NULL; } #endif break; } b = Process32Next( hSnapshot, &pe ); } CloseHandle( hSnapshot ); return b; }
EXM_API int exm_process_dependencies_set(Exm_Process *process) { MODULEENTRY32 me32; HANDLE h; EXM_LOG_DBG("Finding dependencies"); h = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, process->id); if (h == INVALID_HANDLE_VALUE) { EXM_LOG_ERR("Can not retrieve the modules the process %s", process->filename); return 0; } me32.dwSize = sizeof(MODULEENTRY32); if (!Module32First(h, &me32)) { EXM_LOG_ERR("Can not retrieve the first module the process %s", process->filename); goto close_h; } do { size_t i; unsigned char is_found; EXM_LOG_DBG("Finding module %s in process %s", me32.szExePath, strrchr(process->filename, '\\') + 1); for (i = 0; i < (sizeof(_exm_process_crt_names) / sizeof(const char *)); i++) { if (_stricmp(me32.szModule, _exm_process_crt_names[i]) != 0) continue; /* FIXME: this following test should be useless as the list of modules has no duplicata */ if (exm_list_data_is_found(process->crt_names, me32.szExePath, _exm_process_dep_cmp)) continue; process->crt_names = exm_list_append(process->crt_names, _strdup(me32.szExePath)); } is_found = 0; for (i = 0; i < (sizeof(_exm_process_dep_names_supp) / sizeof(const char *)); i++) { if (_stricmp(me32.szModule, _exm_process_dep_names_supp[i]) == 0) { is_found = 1; break; } } if (!is_found && /* FIXME: this following test should be useless as the list of modules has no duplicata */ !exm_list_data_is_found(process->dep_names, me32.szExePath, _exm_process_dep_cmp)) process->dep_names = exm_list_append(process->dep_names, _strdup(me32.szExePath)); } while(Module32Next(h, &me32)); CloseHandle(h); return 1; close_h: CloseHandle(h); return 0; }
bool InitDefTerm() { bool lbRc = true; wchar_t szInfo[MAX_PATH*2]; msprintf(szInfo, countof(szInfo), L"!!! TH32CS_SNAPMODULE, TID=%u, InitDefaultTerm\n", GetCurrentThreadId()); DebugStr(szInfo); // Don't call DefTermLogString here - gpDefTerm was not initialized yet _ASSERTEX(gpDefTerm==NULL); gpDefTerm = new CDefTermHk(); if (!gpDefTerm) { _ASSERTEX(gpDefTerm!=NULL); return false; } //_ASSERTE(FALSE && "InitDefaultTerm"); // При обновлении ConEmu может обновиться и ConEmuHk.dll // Но в процессы с "DefTerm" грузится копия dll-ки, поэтому // после обновления в уже хукнутый процесс загружается // вторая "ConEmuHk.YYMMDD.dll", а старую при этом нужно // выгрузить. Этим и займемся. HMODULE hPrevHooks = NULL; _ASSERTEX(gnSelfPID!=0 && ghOurModule!=NULL); HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, gnSelfPID); if (hSnap != INVALID_HANDLE_VALUE) { MODULEENTRY32 mi = {sizeof(mi)}; //wchar_t szOurName[MAX_PATH] = L""; //GetModuleFileName(ghOurModule, szOurName, MAX_PATH); wchar_t szMinor[8] = L""; lstrcpyn(szMinor, WSTRING(MVV_4a), countof(szMinor)); wchar_t szAddName[40]; msprintf(szAddName, countof(szAddName), CEDEFTERMDLLFORMAT /*L"ConEmuHk%s.%02u%02u%02u%s.dll"*/, WIN3264TEST(L"",L"64"), MVV_1, MVV_2, MVV_3, szMinor); //LPCWSTR pszOurName = PointToName(szOurName); wchar_t* pszDot = wcschr(szAddName, L'.'); wchar_t szCheckName[MAX_PATH+1]; if (pszDot && Module32First(hSnap, &mi)) { pszDot[1] = 0; // Need to check only name, without version number int nCurLen = lstrlen(szAddName); do { if (mi.hModule == ghOurModule) continue; lstrcpyn(szCheckName, PointToName(mi.szExePath), nCurLen+1); if (lstrcmpi(szCheckName, szAddName) == 0) { msprintf(szInfo, countof(szInfo), L"Prevous ConEmuHk module found at address " WIN3264TEST(L"0x%08X",L"0x%X%08X") L": %s", WIN3264WSPRINT(mi.hModule), mi.szExePath); DefTermLogString(szInfo); hPrevHooks = mi.hModule; break; // Prev (old version) instance found! } } while (Module32Next(hSnap, &mi)); } CloseHandle(hSnap); } // Old library was found, unload it before continue if (hPrevHooks) { DefTermLogString(L"Trying to unload previous ConEmuHk module"); if (!FreeLibrary(hPrevHooks)) { lbRc = false; gpDefTerm->DisplayLastError(L"Unloading failed", GetLastError()); } else { DefTermLogString(L"Unloading succeeded"); } } // For Visual Studio check all spawned processes (children of gnSelfPID), find *.vshost.exe if (gbIsVStudio) { //_ASSERTEX(FALSE && "Continue to find existing *.vshost.exe"); HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnap != INVALID_HANDLE_VALUE) { PROCESSENTRY32 pe = {sizeof(pe)}; if (Process32First(hSnap, &pe)) do { if (pe.th32ParentProcessID == gnSelfPID) { if (IsVsNetHostExe(pe.szExeFile)) // *.vshost.exe { // Found! Hook it! DefTermLogString(L"Child VsNetHost found, hooking"); gpDefTerm->StartDefTermHooker(pe.th32ProcessID); break; } } } while (Process32Next(hSnap, &pe)); CloseHandle(hSnap); } } DefTermLogString(L"InitDefaultTerm finished, calling StartDefTerm"); gpDefTerm->StartDefTerm(); return lbRc; }
BOOL WINAPI SSQ_AddressToFunctionName(DWORD address,char** module,char** function) { static HANDLE handle_snapshot; static MODULEENTRY32 module_entry; static BOOL module_next; static PIMAGE_DOS_HEADER dos_header; static PIMAGE_NT_HEADERS nt_headers; static PIMAGE_EXPORT_DIRECTORY export_directory; static DWORD counter; static DWORD counter2; if(HIWORD(address)==0||HIWORD(module)==0||HIWORD(function)==0) { return FALSE; } handle_snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,GetCurrentProcessId()); if(handle_snapshot==INVALID_HANDLE_VALUE) { return FALSE; } module_entry.dwSize = sizeof(module_entry); if(Module32First(handle_snapshot,&module_entry)==FALSE) { CloseHandle(handle_snapshot); return FALSE; } do { if(address>=(DWORD)module_entry.modBaseAddr&&address<((DWORD)module_entry.modBaseAddr+module_entry.modBaseSize)) { *module = module_entry.szModule; break; } } while((module_next = Module32Next(handle_snapshot,&module_entry))==TRUE); CloseHandle(handle_snapshot); if(module_next==FALSE) { return FALSE; } dos_header = (PIMAGE_DOS_HEADER)module_entry.modBaseAddr; nt_headers = (PIMAGE_NT_HEADERS)((DWORD)dos_header+dos_header->e_lfanew); export_directory = (PIMAGE_EXPORT_DIRECTORY)((DWORD)dos_header+nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress); for(counter = 0;counter<export_directory->NumberOfFunctions;counter++) { if(((DWORD)dos_header+((PULONG)((DWORD)dos_header+(DWORD)export_directory->AddressOfFunctions))[counter])==address) { for(counter2 = 0;counter2<export_directory->NumberOfNames;counter2++) { if(((PUSHORT)((DWORD)dos_header+(DWORD)export_directory->AddressOfNameOrdinals))[counter2]==counter) { *function = (char*)((DWORD)dos_header+((PULONG)((DWORD)dos_header+(DWORD)export_directory->AddressOfNames))[counter2]); //wsprintf(test,"c: %i c2 %i address: 0x%08X ordinal: %i %08X aof %08X",counter,counter2,address,ordinal,(DWORD)dos_header+(DWORD)export_directory->AddressOfNameOrdinals,(DWORD)dos_header+(DWORD)export_directory->AddressOfFunctions); //MessageBox(0,*function,test,0); return TRUE; } } } } return FALSE; }
void close_orphaned_processes( const std::list<std::string> &filenames ) { /*build absolute paths and convert to wide-char*/ std::list<std::string> absolute_paths; for( std::list<std::string>::const_iterator i = filenames.begin(); i != filenames.end(); i++ ) { char *absolute_path = build_absolute_path( i->c_str() ); if( absolute_path ) { absolute_paths.push_back( absolute_path ); delete absolute_path; } } /*look for processes matching these absolute paths, and kill them*/ PROCESSENTRY32 process_entry; process_entry.dwSize = sizeof( PROCESSENTRY32 ); HANDLE process_snapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, NULL ); if( Process32First( process_snapshot, &process_entry ) == TRUE ) { do{ bool terminated = false; if( process_entry.th32ProcessID > 0 ) { HANDLE module_snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, process_entry.th32ProcessID); MODULEENTRY32 module_entry; module_entry.dwSize = sizeof( MODULEENTRY32 ); if( Module32First( module_snapshot, &module_entry ) == TRUE ) { for( std::list<std::string>::const_iterator i = absolute_paths.begin(); i != absolute_paths.end(); i++ ) { std::wstring absolute_path_wide; absolute_path_wide.assign( i->begin(), i->end() ); if( absolute_path_wide == module_entry.szExePath ) { if( process_entry.th32ProcessID != GetCurrentProcessId() ) { HANDLE process_handle = OpenProcess( PROCESS_TERMINATE, FALSE, process_entry.th32ProcessID ); if( process_handle ) { if( TerminateProcess( process_handle, 0 ) != 0 ) { INTEGRA_TRACE_PROGRESS << "Killed orphaned process " << *i; terminated = true; } else { INTEGRA_TRACE_ERROR << "failed to terminate orphaned process. Error:" << GetLastError(); } CloseHandle( process_handle ); } else { INTEGRA_TRACE_ERROR << "failed to kill orphaned process - couldn't open process handle. Error: " << GetLastError(); } } } if( terminated ) { break; } } while( !terminated && Module32Next( module_snapshot, &module_entry ) == TRUE ); } CloseHandle( module_snapshot ); } } while( Process32Next( process_snapshot, &process_entry ) == TRUE ); } CloseHandle( process_snapshot ); }