void Kill() { HANDLE hProc=OpenProcess(PROCESS_ALL_ACCESS,FALSE,6756); TerminateProcess(hProc,123); }
static bool Launch() { Log(L"Launching browser..."); DWORD processID; // The interface that allows us to activate the browser CComPtr<IApplicationActivationManager> activateMgr; if (FAILED(CoCreateInstance(CLSID_ApplicationActivationManager, NULL, CLSCTX_LOCAL_SERVER, IID_IApplicationActivationManager, (void**)&activateMgr))) { Fail(L"CoCreateInstance CLSID_ApplicationActivationManager failed."); return false; } HRESULT hr; WCHAR appModelID[256]; // Activation is based on the browser's registered app model id if (!GetDefaultBrowserAppModelID(appModelID, (sizeof(appModelID)/sizeof(WCHAR)))) { Fail(L"GetDefaultBrowserAppModelID failed."); return false; } Log(L"App model id='%s'", appModelID); // Hand off focus rights if the terminal has focus to the out-of-process // activation server (explorer.exe). Without this the metro interface // won't launch. if (GetForegroundWindow() == GetConsoleWindow()) { hr = CoAllowSetForegroundWindow(activateMgr, NULL); if (FAILED(hr)) { Fail(L"CoAllowSetForegroundWindow result %X", hr); return false; } } Log(L"Harness process id: %d", GetCurrentProcessId()); // Because we can't pass command line args, we store params in a // tests.ini file in dist/bin which the browser picks up on launch. CStringA testFilePath; if (sFirefoxPath.GetLength()) { // Use the firefoxpath passed to us by the test harness int index = sFirefoxPath.ReverseFind('\\'); if (index == -1) { Fail(L"Bad firefoxpath path"); return false; } testFilePath = sFirefoxPath.Mid(0, index); testFilePath += "\\"; testFilePath += kMetroTestFile; } else { // Use the module path char path[MAX_PATH]; if (!GetModuleFileNameA(NULL, path, MAX_PATH)) { Fail(L"GetModuleFileNameA errorno=%d", GetLastError()); return false; } char* slash = strrchr(path, '\\'); if (!slash) return false; *slash = '\0'; // no trailing slash testFilePath = path; testFilePath += "\\"; testFilePath += kMetroTestFile; } Log(L"Writing out tests.ini to: '%s'", CStringW(testFilePath)); HANDLE hTestFile = CreateFileA(testFilePath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hTestFile == INVALID_HANDLE_VALUE) { Fail(L"CreateFileA errorno=%d", GetLastError()); return false; } DeleteTestFileHelper dtf(testFilePath); CStringA asciiParams = sAppParams; if (!WriteFile(hTestFile, asciiParams, asciiParams.GetLength(), NULL, 0)) { CloseHandle(hTestFile); Fail(L"WriteFile errorno=%d", GetLastError()); return false; } FlushFileBuffers(hTestFile); CloseHandle(hTestFile); // Create a named stdout pipe for the browser if (!SetupTestOutputPipe()) { Fail(L"SetupTestOutputPipe failed (errno=%d)", GetLastError()); return false; } // Launch firefox hr = activateMgr->ActivateApplication(appModelID, L"", AO_NOERRORUI, &processID); if (FAILED(hr)) { Fail(L"ActivateApplication result %X", hr); return false; } Log(L"Activation succeeded. processid=%d", processID); HANDLE child = OpenProcess(SYNCHRONIZE, FALSE, processID); if (!child) { Fail(L"Couldn't find child process. (%d)", GetLastError()); return false; } Log(L"Waiting on child process..."); MSG msg; DWORD waitResult = WAIT_TIMEOUT; HANDLE handles[2] = { child, gTestOutputPipe }; while ((waitResult = MsgWaitForMultipleObjects(2, handles, FALSE, INFINITE, QS_ALLINPUT)) != WAIT_OBJECT_0) { if (waitResult == WAIT_FAILED) { Log(L"Wait failed (errno=%d)", GetLastError()); break; } else if (waitResult == WAIT_OBJECT_0 + 1) { ReadPipe(); } else if (waitResult == WAIT_OBJECT_0 + 2 && PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } } ReadPipe(); CloseHandle(gTestOutputPipe); CloseHandle(child); Log(L"Exiting."); return true; }
int main(int argc, char *argv[]) { int PID = 0; HANDLE hProcess = 0; PBYTE pCodeRemote = NULL; DWORD dwNumBytesXferred = 0; PBYTE pCode = NULL; DWORD dwSizeOfCode = 0; HANDLE hThread = 0; DWORD dwThreadId = 0; int exitcode = 0; if (argc < 2) { printf("Usage: %s pid\n", argv[0]); return -1; } PID = atoi(argv[1]); if (PID <= 0) { printf("[E]: pid should be greater than zero!\n"); return -1; } pCode = (PBYTE)code; dwSizeOfCode = sizeof(code); printf("[I]: Opening remote process %d......", PID); hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, PID); if (hProcess == NULL) { printf("failed.\n"); return -1; } printf("ok.\n"); printf("[I]: Allocating remote memory with size of 0x%08x ......", dwSizeOfCode); pCodeRemote = (PBYTE) VirtualAllocEx(hProcess, 0, dwSizeOfCode, MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (pCodeRemote == NULL) { printf("failed.\n"); CloseHandle(hProcess); return -1; } printf("ok at 0x%08x.\n", pCodeRemote); printf("[I]: Writing code ......"); if (WriteProcessMemory(hProcess, pCodeRemote, pCode, dwSizeOfCode, &dwNumBytesXferred) == 0) { printf("failed.\n"); VirtualFreeEx(hProcess, pCodeRemote, dwSizeOfCode, MEM_RELEASE); CloseHandle(hProcess); return -1; }; printf("ok (%d bytes were written).\n", dwNumBytesXferred); printf("[I]: Creating a remote thread ......"); hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE) pCodeRemote, pCodeRemote, 0 , &dwThreadId); if (hThread == 0) { printf("failed.\n"); if ( pCodeRemote != 0 ) VirtualFreeEx(hProcess, pCodeRemote, 0, MEM_RELEASE); if ( hThread != 0 ) CloseHandle(hThread); return -1; } printf("ok.\n"); printf("[I]: Waiting the remote thread ......"); WaitForSingleObject(hThread, INFINITE); GetExitCodeThread(hThread, (PDWORD) &exitcode); printf("exited with 0x%08X\n", exitcode); VirtualFreeEx(hProcess, pCodeRemote, 0, MEM_RELEASE); CloseHandle(hProcess); return 0; }
int main(int argc,char *argv[]) { HANDLE hRemoteProcess; HANDLE hRemoteThread; DWORD dwRemoteProcess; char DllPath[260]; DWORD size; ListProcess(); printf("请输入要注入进程的ID:"); if(scanf("%d",&dwRemoteProcess)!=1) return -1; hRemoteProcess=OpenProcess(PROCESS_ALL_ACCESS,false,dwRemoteProcess); //打开远程进程 if(hRemoteProcess==0) { printf("打开进程失败。\n"); getch(); return -1; } memset(DllPath,NULL,sizeof(DllPath)); GetCurrentDirectoryA(sizeof(DllPath)-1,DllPath); strcat(DllPath,"\\DLL_Test.dll"); puts(DllPath); LPVOID pRemoteDllPath=VirtualAllocEx(hRemoteProcess,NULL,strlen(DllPath)+1,MEM_COMMIT,PAGE_READWRITE); //在进程中开辟空间 if(pRemoteDllPath==NULL) { printf("VirtualAlloc Error!\n"); getch(); return -1; } if(WriteProcessMemory(hRemoteProcess,pRemoteDllPath,DllPath,strlen(DllPath)+1,&size)==0) //向进程空间中写入数据 { printf("WriteProcessMemory Error!\n"); getch(); return -1; } //获得远程进程中LoadLibrary()的地址 LPTHREAD_START_ROUTINE pLoadLibrary = (LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), \ "LoadLibraryA"); if (pLoadLibrary == NULL) { printf("GetProcAddress error\n"); getch(); return -1; } if((hRemoteThread=CreateRemoteThread(hRemoteProcess,NULL,0,pLoadLibrary,pRemoteDllPath,0,NULL))==NULL) { printf("创建线程失败。\n"); getch(); return -1; } WaitForSingleObject(hRemoteThread,INFINITE); //释放占用的内存 if(VirtualFreeEx(hRemoteProcess,pRemoteDllPath,0,MEM_RELEASE)==NULL) { printf("VirtualFreeEx Error!\n"); getch(); return -1; } CloseHandle(hRemoteProcess); CloseHandle(hRemoteThread); printf("程序结束。\n"); getch(); return 0; }
void PrintMemoryAndTimeInfo (DWORD processID) { HANDLE hProcess; DWORD ExitCode; PROCESS_MEMORY_COUNTERS pmc; FILETIME CreationTime; FILETIME ExitTime; FILETIME KernelTime; FILETIME UserTime; // Print the process identifier. fprintf(stderr, "\nProcess ID: %u\n", processID); // Get a handle for the process hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID); if (NULL == hProcess) { fprintf(stderr, " OpenProcess() returned NULL\n"); return; } if (GetExitCodeProcess(hProcess, &ExitCode)) { fprintf(stderr, " exit code: %d\n", ExitCode); } else { fprintf(stderr, " GetExitCodeProcess() returned FALSE\n"); return; } // Print information about the cpu time of the process. // Documentation for GetProcessTimes() is available here: // http://msdn.microsoft.com/en-us/library/ms683223%28VS.85%29.aspx if (GetProcessTimes(hProcess, &CreationTime, &ExitTime, &KernelTime, &UserTime)) { uint64 ctime = (((uint64) CreationTime.dwHighDateTime << 32) + (uint64) CreationTime.dwLowDateTime); uint64 etime = (((uint64) ExitTime.dwHighDateTime << 32) + (uint64) ExitTime.dwLowDateTime); uint64 ktime = (((uint64) KernelTime.dwHighDateTime << 32) + (uint64) KernelTime.dwLowDateTime); uint64 utime = (((uint64) UserTime.dwHighDateTime << 32) + (uint64) UserTime.dwLowDateTime); // ktime and utime are given to us in units of 100s of // nanoseconds. fprintf(stderr, " elapsed time (seconds): %.2f\n", (etime - ctime) / 10000000.0); fprintf(stderr, " user time (seconds): %.2f\n", utime / 10000000.0); fprintf(stderr, " kernel time (seconds): %.2f\n", ktime / 10000000.0); } else { fprintf(stderr, " GetProcessTimes() returned NULL\n"); } // Print information about the memory usage of the process. if (GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc))) { fprintf(stderr, " Page Fault Count: %u\n", pmc.PageFaultCount); fprintf(stderr, " Peak Working Set Size (kbytes): %u\n", (pmc.PeakWorkingSetSize + 1023) / 1024); fprintf(stderr, " Quota Peak Paged Pool Usage: %u\n", pmc.QuotaPeakPagedPoolUsage); fprintf(stderr, " Quota Peak Non Paged Pool Usage: %u\n", pmc.QuotaPeakNonPagedPoolUsage); fprintf(stderr, " Peak Pagefile Usage: %u\n", pmc.PeakPagefileUsage); // Don't bother to print these statistics, since they are most // likely garbage anyway, by the time the process has exited. // fprintf(stderr, //"\n" //" Note that statistics below are probably worthless, since the\n" //" process has already exited and they reflect the current resources\n" //" used by the process.\n" //"\n" // ); // fprintf(stderr, " Working Set Size (kbytes): %u\n", // (pmc.WorkingSetSize + 1023) / 1024); // fprintf(stderr, " Quota Paged Pool Usage: %u\n", // pmc.QuotaPagedPoolUsage); // fprintf(stderr, " Quota Non Paged Pool Usage: %u\n", // pmc.QuotaNonPagedPoolUsage); // fprintf(stderr, " Pagefile Usage: %u\n", // pmc.PagefileUsage); } else { fprintf(stderr, " GetProcessMemoryInfo() returned NULL\n"); } CloseHandle(hProcess); }
/* * @implemented */ DWORD WINAPI GetProcessVersion(DWORD ProcessId) { DWORD Version = 0; PIMAGE_NT_HEADERS NtHeader = NULL; IMAGE_NT_HEADERS NtHeaders; IMAGE_DOS_HEADER DosHeader; PROCESS_BASIC_INFORMATION ProcessBasicInfo; PVOID BaseAddress = NULL; HANDLE ProcessHandle = NULL; NTSTATUS Status; SIZE_T Count; PEB Peb; _SEH2_TRY { if (0 == ProcessId || GetCurrentProcessId() == ProcessId) { /* Caller's */ BaseAddress = (PVOID) NtCurrentPeb()->ImageBaseAddress; NtHeader = RtlImageNtHeader(BaseAddress); Version = (NtHeader->OptionalHeader.MajorOperatingSystemVersion << 16) | (NtHeader->OptionalHeader.MinorOperatingSystemVersion); } else { /* Other process */ ProcessHandle = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, ProcessId); if (!ProcessHandle) return 0; Status = NtQueryInformationProcess(ProcessHandle, ProcessBasicInformation, &ProcessBasicInfo, sizeof(ProcessBasicInfo), NULL); if (!NT_SUCCESS(Status)) goto Error; Status = NtReadVirtualMemory(ProcessHandle, ProcessBasicInfo.PebBaseAddress, &Peb, sizeof(Peb), &Count); if (!NT_SUCCESS(Status) || Count != sizeof(Peb)) goto Error; memset(&DosHeader, 0, sizeof(DosHeader)); Status = NtReadVirtualMemory(ProcessHandle, Peb.ImageBaseAddress, &DosHeader, sizeof(DosHeader), &Count); if (!NT_SUCCESS(Status) || Count != sizeof(DosHeader)) goto Error; if (DosHeader.e_magic != IMAGE_DOS_SIGNATURE) goto Error; memset(&NtHeaders, 0, sizeof(NtHeaders)); Status = NtReadVirtualMemory(ProcessHandle, (char *)Peb.ImageBaseAddress + DosHeader.e_lfanew, &NtHeaders, sizeof(NtHeaders), &Count); if (!NT_SUCCESS(Status) || Count != sizeof(NtHeaders)) goto Error; if (NtHeaders.Signature != IMAGE_NT_SIGNATURE) goto Error; Version = MAKELONG(NtHeaders.OptionalHeader.MinorSubsystemVersion, NtHeaders.OptionalHeader.MajorSubsystemVersion); Error: if (!NT_SUCCESS(Status)) { SetLastErrorByStatus(Status); } } } _SEH2_FINALLY { if (ProcessHandle) CloseHandle(ProcessHandle); } _SEH2_END; return Version; }
//---------------------------------------------------------------- // CImpIRestrictedProcess::RP_WahCreateSocketHandle() // // In order to use WPUCreateSocketHandle(), this function must be // remoted because it creates a file handle... //---------------------------------------------------------------- STDMETHODIMP CImpIRestrictedProcess::RP_WahCreateSocketHandle( IN DWORD dwTargetPid, IN DWORD dwHelperHandle, OUT DWORD *pdwSocket, OUT DWORD *pdwStatus ) { BOOL fInherit; DWORD dwSourcePid; DWORD dwAccess; DWORD dwOptions; HANDLE hSourceProcess; HANDLE hSourceHandle; HANDLE hTargetProcess; SOCKET Socket; *pdwStatus = WahCreateSocketHandle( (HANDLE)m_hHelper, (SOCKET*)&Socket ); if (*pdwStatus == NO_ERROR) { return NOERROR; } // Get a handle to our own process (to be used by DuplicateHandle()). dwSourcePid = GetCurrentProcessId(); hSourceProcess = OpenProcess( PROCESS_DUP_HANDLE, TRUE, dwSourcePid ); if (!hSourceProcess) { *pdwStatus = GetLastError(); WahCloseSocketHandle(m_hHelper,Socket); return NOERROR; } // Get a handle to the restricted process hTargetProcess = OpenProcess( PROCESS_DUP_HANDLE, TRUE, dwTargetPid ); if (!hTargetProcess) { *pdwStatus = GetLastError(); WahCloseSocketHandle(m_hHelper,Socket); CloseHandle(hSourceProcess); return NOERROR; } // Ok, duplicate the helper handle into the restricted client. dwAccess = 0; fInherit = FALSE; dwOptions = DUPLICATE_SAME_ACCESS; if (!DuplicateHandle(hSourceProcess, (HANDLE)Socket, hTargetProcess, (HANDLE*)pdwSocket, dwAccess, fInherit, dwOptions )) { *pdwStatus = GetLastError(); } // Close local copies of the helper handle and the socket, // both of these are now in the child process. WahCloseSocketHandle(m_hHelper,Socket); WahCloseHandleHelper(m_hHelper); m_hHelper = 0; // Done with the process handles. CloseHandle(hSourceProcess); CloseHandle(hTargetProcess); return NOERROR; }
explicit SecurityAttributes(MemoryPool& pool) : m_pool(pool) { // Ensure that our process has the SYNCHRONIZE privilege granted to everyone PSECURITY_DESCRIPTOR pOldSD = NULL; PACL pOldACL = NULL; // Pseudo-handles do not work on WinNT. Need real process handle. HANDLE hCurrentProcess = OpenProcess(READ_CONTROL | WRITE_DAC, FALSE, GetCurrentProcessId()); if (hCurrentProcess == NULL) { Firebird::system_call_failed::raise("OpenProcess"); } DWORD result = GetSecurityInfo(hCurrentProcess, SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pOldACL, NULL, &pOldSD); if (result == ERROR_CALL_NOT_IMPLEMENTED) { // For Win9X - sumulate that the call worked alright pOldACL = NULL; result = ERROR_SUCCESS; } if (result != ERROR_SUCCESS) { CloseHandle(hCurrentProcess); Firebird::system_call_failed::raise("GetSecurityInfo", result); } // NULL pOldACL means all privileges. If we assign pNewACL in this case // we'll lost all privileges except assigned SYNCHRONIZE if (pOldACL) { SID_IDENTIFIER_AUTHORITY sidAuth = SECURITY_WORLD_SID_AUTHORITY; PSID pSID = NULL; AllocateAndInitializeSid(&sidAuth, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pSID); EXPLICIT_ACCESS ea; memset(&ea, 0, sizeof(EXPLICIT_ACCESS)); ea.grfAccessPermissions = SYNCHRONIZE; ea.grfAccessMode = GRANT_ACCESS; ea.grfInheritance = NO_INHERITANCE; ea.Trustee.TrusteeForm = TRUSTEE_IS_SID; ea.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; ea.Trustee.ptstrName = (LPTSTR) pSID; PACL pNewACL = NULL; SetEntriesInAcl(1, &ea, pOldACL, &pNewACL); SetSecurityInfo(hCurrentProcess, SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, pNewACL, NULL); if (pSID) { FreeSid(pSID); } if (pNewACL) { LocalFree(pNewACL); } } CloseHandle(hCurrentProcess); if (pOldSD) { LocalFree(pOldSD); } // Create and initialize the default security descriptor // to be assigned to various IPC objects. // // WARNING!!! The absent DACL means full access granted // to everyone, this is a huge security risk! PSECURITY_DESCRIPTOR p_security_desc = static_cast<PSECURITY_DESCRIPTOR>( pool.allocate(SECURITY_DESCRIPTOR_MIN_LENGTH)); attributes.nLength = sizeof(attributes); attributes.lpSecurityDescriptor = p_security_desc; attributes.bInheritHandle = TRUE; if (!InitializeSecurityDescriptor(p_security_desc, SECURITY_DESCRIPTOR_REVISION) || !SetSecurityDescriptorDacl(p_security_desc, TRUE, NULL, FALSE)) { pool.deallocate(p_security_desc); attributes.lpSecurityDescriptor = NULL; } }
int main ( int argc, char ** argv ) { if ( argc==2 ) COMMIT_STEP = atoi ( argv[1] ); // threads should be initialized before memory allocations char cTopOfMainStack; sphThreadInit(); MemorizeStack ( &cTopOfMainStack ); CSphString sError; CSphDictSettings tDictSettings; tDictSettings.m_bWordDict = false; ISphTokenizer * pTok = sphCreateUTF8Tokenizer(); CSphDict * pDict = sphCreateDictionaryCRC ( tDictSettings, NULL, pTok, "rt1", sError ); CSphSource_MySQL * pSrc = SpawnSource ( "SELECT id, channel_id, UNIX_TIMESTAMP(published) published, " "title, UNCOMPRESS(content) content FROM posting WHERE id<=10000 AND id%2=0", pTok, pDict ); ISphTokenizer * pTok2 = sphCreateUTF8Tokenizer(); CSphDict * pDict2 = sphCreateDictionaryCRC ( tDictSettings, NULL, pTok, "rt2", sError ); CSphSource_MySQL * pSrc2 = SpawnSource ( "SELECT id, channel_id, UNIX_TIMESTAMP(published) published, " "title, UNCOMPRESS(content) content FROM posting WHERE id<=10000 AND id%2=1", pTok2, pDict2 ); CSphSchema tSrcSchema; if ( !pSrc->UpdateSchema ( &tSrcSchema, sError ) ) sphDie ( "update-schema failed: %s", sError.cstr() ); CSphSchema tSchema; // source schema must be all dynamic attrs; but index ones must be static tSchema.m_dFields = tSrcSchema.m_dFields; for ( int i=0; i<tSrcSchema.GetAttrsCount(); i++ ) tSchema.AddAttr ( tSrcSchema.GetAttr(i), false ); g_iFieldsCount = tSrcSchema.m_dFields.GetLength(); CSphConfigSection tRTConfig; sphRTInit ( tRTConfig, true ); sphRTConfigure ( tRTConfig, true ); SmallStringHash_T< CSphIndex * > dTemp; sphReplayBinlog ( dTemp, 0 ); ISphRtIndex * pIndex = sphCreateIndexRT ( tSchema, "testrt", 32*1024*1024, "data/dump", false ); pIndex->SetTokenizer ( pTok ); // index will own this pair from now on pIndex->SetDictionary ( pDict ); if ( !pIndex->Prealloc ( false ) ) sphDie ( "prealloc failed: %s", pIndex->GetLastError().cstr() ); pIndex->PostSetup(); g_pIndex = pIndex; // initial indexing int64_t tmStart = sphMicroTimer(); SphThread_t t1, t2; sphThreadCreate ( &t1, IndexingThread, pSrc ); sphThreadCreate ( &t2, IndexingThread, pSrc2 ); sphThreadJoin ( &t1 ); sphThreadJoin ( &t2 ); #if 0 // update tParams.m_sQuery = "SELECT id, channel_id, UNIX_TIMESTAMP(published) published, title, " "UNCOMPRESS(content) content FROM rt2 WHERE id<=10000"; SetupIndexing ( pSrc, tParams ); DoIndexing ( pSrc, pIndex ); #endif // search DoSearch ( pIndex ); // shutdown index (should cause dump) int64_t tmShutdown = sphMicroTimer(); #if SPH_ALLOCS_PROFILER printf ( "pre-shutdown allocs=%d, bytes=" INT64_FMT "\n", sphAllocsCount(), sphAllocBytes() ); #endif SafeDelete ( pIndex ); #if SPH_ALLOCS_PROFILER printf ( "post-shutdown allocs=%d, bytes=" INT64_FMT "\n", sphAllocsCount(), sphAllocBytes() ); #endif int64_t tmEnd = sphMicroTimer(); printf ( "shutdown done in %d.%03d sec\n", (int)((tmEnd-tmShutdown)/1000000), (int)(((tmEnd-tmShutdown)%1000000)/1000) ); printf ( "total with shutdown %d.%03d sec, %.2f MB/sec\n", (int)((tmEnd-tmStart)/1000000), (int)(((tmEnd-tmStart)%1000000)/1000), g_fTotalMB*1000000.0f/(tmEnd-tmStart) ); #if SPH_DEBUG_LEAKS || SPH_ALLOCS_PROFILER sphAllocsStats(); #endif #if USE_WINDOWS PROCESS_MEMORY_COUNTERS pmc; HANDLE hProcess = OpenProcess ( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, GetCurrentProcessId() ); if ( hProcess && GetProcessMemoryInfo ( hProcess, &pmc, sizeof(pmc)) ) { printf ( "--- peak-wss=%d, peak-pagefile=%d\n", (int)pmc.PeakWorkingSetSize, (int)pmc.PeakPagefileUsage ); } #endif SafeDelete ( pIndex ); sphRTDone (); }
QList<DWORD> * getDxProcessesIDs(QList<DWORD> * processes, LPCWSTR wstrSystemRootPath) { DWORD aProcesses[1024]; HMODULE hMods[1024]; DWORD cbNeeded; DWORD cProcesses; char debug_buf[255]; WCHAR executableName[MAX_PATH]; unsigned int i; // Get the list of process identifiers. processes->clear(); if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) ) return NULL; // Calculate how many process identifiers were returned. cProcesses = cbNeeded / sizeof(DWORD); // Print the names of the modules for each process. for ( i = 0; i < cProcesses; i++ ) { if (aProcesses[i] != GetCurrentProcessId()) { HANDLE hProcess; hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, aProcesses[i] ); if (NULL == hProcess) goto nextProcess; GetModuleFileNameExW(hProcess, 0, executableName, sizeof (executableName)); if (wcsstr(executableName, wstrSystemRootPath) != NULL) { goto nextProcess; } PathStripPathW(executableName); ::WideCharToMultiByte(CP_ACP, 0, executableName, -1, debug_buf, 255, NULL, NULL); DEBUG_MID_LEVEL << Q_FUNC_INFO << debug_buf; for (unsigned k=0; k < SIZEOF_ARRAY(pwstrExcludeProcesses); k++) { if (wcsicmp(executableName, pwstrExcludeProcesses[k])== 0) { DEBUG_MID_LEVEL << Q_FUNC_INFO << "skipping " << pwstrExcludeProcesses; goto nextProcess; } } // Get a list of all the modules in this process. if( EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) { bool isDXPresent = false; for ( DWORD j = 0; j < (cbNeeded / sizeof(HMODULE)); j++ ) { WCHAR szModName[MAX_PATH]; if ( GetModuleFileNameExW( hProcess, hMods[j], szModName, sizeof(szModName) / sizeof(WCHAR))) { PathStripPathW(szModName); ::WideCharToMultiByte(CP_ACP, 0, szModName, -1, debug_buf, 255, NULL, NULL); DEBUG_HIGH_LEVEL << Q_FUNC_INFO << debug_buf; if(wcsicmp(szModName, lightpackHooksDllName) == 0) { goto nextProcess; } else { if (wcsicmp(szModName, L"d3d9.dll") == 0 || wcsicmp(szModName, L"dxgi.dll") == 0 ) isDXPresent = true; } } } if (isDXPresent) processes->append(aProcesses[i]); } nextProcess: // Release the handle to the process. CloseHandle( hProcess ); } } return processes; }
bool MSWindowsSession::isProcessInSession(const char* name, PHANDLE process = NULL) { // first we need to take a snapshot of the running processes HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (snapshot == INVALID_HANDLE_VALUE) { LOG((CLOG_ERR "could not get process snapshot")); throw XArch(new XArchEvalWindows()); } PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); // get the first process, and if we can't do that then it's // unlikely we can go any further BOOL gotEntry = Process32First(snapshot, &entry); if (!gotEntry) { LOG((CLOG_ERR "could not get first process entry")); throw XArch(new XArchEvalWindows()); } // used to record process names for debug info std::list<std::string> nameList; // now just iterate until we can find winlogon.exe pid DWORD pid = 0; while(gotEntry) { // make sure we're not checking the system process if (entry.th32ProcessID != 0) { DWORD processSessionId; BOOL pidToSidRet = ProcessIdToSessionId( entry.th32ProcessID, &processSessionId); if (!pidToSidRet) { // if we can not acquire session associated with a specified process, // simply ignore it LOG((CLOG_ERR "could not get session id for process id %i", entry.th32ProcessID)); gotEntry = nextProcessEntry(snapshot, &entry); continue; } else { // only pay attention to processes in the active session if (processSessionId == m_activeSessionId) { // store the names so we can record them for debug nameList.push_back(entry.szExeFile); if (_stricmp(entry.szExeFile, name) == 0) { pid = entry.th32ProcessID; } } } } // now move on to the next entry (if we're not at the end) gotEntry = nextProcessEntry(snapshot, &entry); } std::string nameListJoin; for(std::list<std::string>::iterator it = nameList.begin(); it != nameList.end(); it++) { nameListJoin.append(*it); nameListJoin.append(", "); } LOG((CLOG_DEBUG "processes in session %d: %s", m_activeSessionId, nameListJoin.c_str())); CloseHandle(snapshot); if (pid) { if (process != NULL) { // now get the process, which we'll use to get the process token. LOG((CLOG_DEBUG "found %s in session %i", name, m_activeSessionId)); *process = OpenProcess(MAXIMUM_ALLOWED, FALSE, pid); } return true; } else { LOG((CLOG_DEBUG "did not find %s in session %i", name, m_activeSessionId)); return false; } }
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)) ) { _tprintf(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 ) { _tprintf(L"EjectDll() : There is not %s module in process(%d) memory!!!\n", szDllPath, dwPID); goto EJECTDLL_EXIT; } dwDesiredAccess = PROCESS_ALL_ACCESS; if( !(hProcess = OpenProcess(dwDesiredAccess, FALSE, dwPID)) ) { _tprintf(L"EjectDll() : OpenProcess(%d) failed!!! [%d]\n", dwPID, GetLastError()); goto EJECTDLL_EXIT; } hMod = GetModuleHandle(L"kernel32.dll"); if( hMod == NULL ) { _tprintf(L"EjectDll() : GetModuleHandle(\"kernel32.dll\") failed!!! [%d]\n", GetLastError()); goto EJECTDLL_EXIT; } pThreadProc = (LPTHREAD_START_ROUTINE)GetProcAddress(hMod, "FreeLibrary"); if( pThreadProc == NULL ) { _tprintf(L"EjectDll() : GetProcAddress(\"FreeLibrary\") failed!!! [%d]\n", GetLastError()); goto EJECTDLL_EXIT; } if( !MyCreateRemoteThread(hProcess, pThreadProc, me.modBaseAddr) ) { _tprintf(L"EjectDll() : MyCreateRemoteThread() failed!!!\n"); goto EJECTDLL_EXIT; } bRet = TRUE; EJECTDLL_EXIT: _tcscpy_s(szProcName, GetProcName(dwPID)); _tprintf(L"%s(%d) %s!!! [%d]\n", szProcName, dwPID, bRet ? L"SUCCESS" : L"-->> FAILURE", GetLastError()); if( hThread ) CloseHandle(hThread); if( hProcess ) CloseHandle(hProcess); if( hSnapshot != INVALID_HANDLE_VALUE ) CloseHandle(hSnapshot); return bRet; }
BOOL InjectDll(DWORD dwPID, LPCTSTR szDllPath) { HANDLE hProcess = NULL; HANDLE hThread = NULL; LPVOID pRemoteBuf = NULL; DWORD dwBufSize = (DWORD)(_tcslen(szDllPath) + 1) * sizeof(TCHAR); LPTHREAD_START_ROUTINE pThreadProc = NULL; BOOL bRet = FALSE; HMODULE hMod = NULL; DWORD dwDesiredAccess = 0; TCHAR szProcName[MAX_PATH] = {0,}; dwDesiredAccess = PROCESS_ALL_ACCESS; //dwDesiredAccess = MAXIMUM_ALLOWED; if ( !(hProcess = OpenProcess(dwDesiredAccess, FALSE, dwPID)) ) { _tprintf(L"InjectDll() : OpenProcess(%d) failed!!! [%d]\n", dwPID, GetLastError()); goto INJECTDLL_EXIT; } pRemoteBuf = VirtualAllocEx(hProcess, NULL, dwBufSize, MEM_COMMIT, PAGE_READWRITE); if( pRemoteBuf == NULL ) { _tprintf(L"InjectDll() : VirtualAllocEx() failed!!! [%d]\n", GetLastError()); goto INJECTDLL_EXIT; } if( !WriteProcessMemory(hProcess, pRemoteBuf, (LPVOID)szDllPath, dwBufSize, NULL) ) { _tprintf(L"InjectDll() : WriteProcessMemory() failed!!! [%d]\n", GetLastError()); goto INJECTDLL_EXIT; } hMod = GetModuleHandle(L"kernel32.dll"); if( hMod == NULL ) { _tprintf(L"InjectDll() : GetModuleHandle(\"kernel32.dll\") failed!!! [%d]\n", GetLastError()); goto INJECTDLL_EXIT; } pThreadProc = (LPTHREAD_START_ROUTINE)GetProcAddress(hMod, "LoadLibraryW"); if( pThreadProc == NULL ) { _tprintf(L"InjectDll() : GetProcAddress(\"LoadLibraryW\") failed!!! [%d]\n", GetLastError()); goto INJECTDLL_EXIT; } if( !MyCreateRemoteThread(hProcess, pThreadProc, pRemoteBuf) ) { _tprintf(L"InjectDll() : MyCreateRemoteThread() failed!!!\n"); goto INJECTDLL_EXIT; } bRet = CheckDllInProcess(dwPID, szDllPath); INJECTDLL_EXIT: wsprintf(szProcName, L"%s", GetProcName(dwPID)); if( szProcName[0] == '\0' ) _tcscpy_s(szProcName, L"(no_process)"); _tprintf(L"%s(%d) %s!!! [%d]\n", szProcName, dwPID, bRet ? L"SUCCESS" : L"-->> FAILURE", GetLastError()); if( pRemoteBuf ) VirtualFreeEx(hProcess, pRemoteBuf, 0, MEM_RELEASE); if( hThread ) CloseHandle(hThread); if( hProcess ) CloseHandle(hProcess); return bRet; }
int main(int argc, char *argv[]) /* Thread One */ { DWORD dwThreadID; HANDLE hProcess; HANDLE hThread1, hThread2, hThread3, hThread4; char szCommandLine[1024]; int i; PARAMETERS myParameters; INIT(); /* set exception handler */ strcpy(szCommandLine, "\0"); ThreadNr = 0; InitializeArguments(&myParameters); ParseArguments(argc, argv, &myParameters); if (argc == 1) { myParameters.bAll = TRUE; } // On initial call, no args are present; execute each subtest below if (myParameters.bAll == TRUE) { LaunchAllTests(argv, myParameters); } else { print("Entering thread with options:\n"); for (i = 1; i < argc; i++) { if (!strncmp(argv[i], "/PID", 4)) { strcat(szCommandLine, "/PID"); } else { strcat(szCommandLine, argv[i]); } } print("%s\n", szCommandLine); do { hThread1 = CreateThread(NULL, 0, &ThreadProc, &(myParameters.nSleepTime), 0, &dwThreadID); ExerciseThread(hThread1, myParameters); WaitForSingleObject(hThread1, INFINITE); ThreadNr++; thread_proc_wait = TRUE; hThread2 = CreateThread(NULL, 0, &ThreadProc, &(myParameters.nSleepTime), 0, &dwThreadID); while (!thread_proc_waiting) { YIELD(); } TerminateThread(hThread2, -1); thread_proc_wait = FALSE; thread_proc_waiting = FALSE; ThreadNr++; // ThreadProc2 calls ExitThread() immediately hThread3 = CreateThread(NULL, 0, &ThreadProc2, &ThreadNr, 0, &dwThreadID); WaitForSingleObject(hThread3, INFINITE); ThreadNr++; if (hThread1 != NULL) { CloseHandle(hThread1); } if (hThread2 != NULL) { CloseHandle(hThread2); } if (hThread3 != NULL) { CloseHandle(hThread3); } } while (ThreadNr < MAX_THREADS); if (myParameters.nPID != 0) { // Prints out results in host PID hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, myParameters.nPID); if ((hProcess == NULL) && (myParameters.bVerbose == TRUE)) { print("Error in OpenProcess(Code %d)\n", GetLastError()); } hThread4 = CreateRemoteThread(hProcess, 0, 0, &ThreadProc, &(myParameters.nSleepTime), 0, &dwThreadID); if ((hThread4 == NULL) && (myParameters.bVerbose == TRUE)) { print("Error in CreateRemoteThread(Code %d)\n", GetLastError()); } WaitForSingleObject(hThread4, INFINITE); if (hThread4 != NULL) { CloseHandle(hThread4); } } print("Exiting thread with options:\n"); print("%s\n", szCommandLine); } return 0; }
EASYHOOK_NT_EXPORT RhInjectLibrary( ULONG InTargetPID, ULONG InWakeUpTID, ULONG InInjectionOptions, WCHAR* InLibraryPath_x86, WCHAR* InLibraryPath_x64, PVOID InPassThruBuffer, ULONG InPassThruSize) { /* Description: Injects a library into the target process. This is a very stable operation. The problem so far is, that only the NET layer will support injection through WOW64 boundaries and into other terminal sessions. It is quite complex to realize with unmanaged code and that's why it is not supported! If you really need this feature I highly recommend to at least look at C++.NET because using the managed injection can speed up your development progress about orders of magnitudes. I know by experience that writing the required multi-process injection code in any unmanaged language is a rather daunting task! Parameters: - InTargetPID The process in which the library should be injected. - InWakeUpTID If the target process was created suspended (RhCreateAndInject), then this parameter should be set to the main thread ID of the target. You may later resume the process from within the injected library by calling RhWakeUpProcess(). If the process is already running, you should specify zero. - InInjectionOptions All flags can be combined. EASYHOOK_INJECT_DEFAULT: No special behavior. The given libraries are expected to be unmanaged DLLs. Further they should export an entry point named "NativeInjectionEntryPoint" (in case of 64-bit) and "_NativeInjectionEntryPoint@4" (in case of 32-bit). The expected entry point signature is REMOTE_ENTRY_POINT. EASYHOOK_INJECT_MANAGED: The given user library is a NET assembly. Further they should export a class named "EasyHook.InjectionLoader" with a static method named "Main". The signature of this method is expected to be "int (String)". Please refer to the managed injection loader of EasyHook for more information about writing such managed entry points. EASYHOOK_INJECT_STEALTH: Uses the experimental stealth thread creation. If it fails you may try it with default settings. EASYHOOK_INJECT_HEART_BEAT: Is only used internally to workaround the managed process creation bug. For curiosity, NET seems to hijack our remote thread if a managed process is created suspended. It doesn't do anything with the suspended main thread, - InLibraryPath_x86 A relative or absolute path to the 32-bit version of the user library being injected. If you don't want to inject into 32-Bit processes, you may set this parameter to NULL. - InLibraryPath_x64 A relative or absolute path to the 64-bit version of the user library being injected. If you don't want to inject into 64-Bit processes, you may set this parameter to NULL. - InPassThruBuffer An optional buffer containg data to be passed to the injection entry point. Such data is available in both, the managed and unmanaged user library entry points. Set to NULL if no used. - InPassThruSize Specifies the size in bytes of the pass thru data. If "InPassThruBuffer" is NULL, this parameter shall also be zero. Returns: */ HANDLE hProc = NULL; HANDLE hRemoteThread = NULL; HANDLE hSignal = NULL; UCHAR* RemoteInjectCode = NULL; LPREMOTE_INFO Info = NULL; LPREMOTE_INFO RemoteInfo = NULL; ULONG RemoteInfoSize = 0; BYTE* Offset = 0; ULONG CodeSize; BOOL Is64BitTarget; NTSTATUS NtStatus; LONGLONG Diff; HANDLE Handles[2]; ULONG UserLibrarySize; ULONG PATHSize; ULONG EasyHookPathSize; ULONG EasyHookEntrySize; ULONG Code; SIZE_T BytesWritten; WCHAR UserLibrary[MAX_PATH+1]; WCHAR PATH[MAX_PATH + 1]; WCHAR EasyHookPath[MAX_PATH + 1]; #ifdef _M_X64 CHAR* EasyHookEntry = "HookCompleteInjection"; #else CHAR* EasyHookEntry = "_HookCompleteInjection@4"; #endif // validate parameters if(InPassThruSize > MAX_PASSTHRU_SIZE) THROW(STATUS_INVALID_PARAMETER_7, L"The given pass thru buffer is too large."); if(InPassThruBuffer != NULL) { if(!IsValidPointer(InPassThruBuffer, InPassThruSize)) THROW(STATUS_INVALID_PARAMETER_6, L"The given pass thru buffer is invalid."); } else if(InPassThruSize != 0) THROW(STATUS_INVALID_PARAMETER_7, L"If no pass thru buffer is specified, the pass thru length also has to be zero."); if(InTargetPID == GetCurrentProcessId()) THROW(STATUS_NOT_SUPPORTED, L"For stability reasons it is not supported to inject into the calling process."); // open target process if((hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, InTargetPID)) == NULL) { if(GetLastError() == ERROR_ACCESS_DENIED) THROW(STATUS_ACCESS_DENIED, L"Unable to open target process. Consider using a system service.") else THROW(STATUS_NOT_FOUND, L"The given target process does not exist!"); } /* Check bitness... After this we can assume hooking a target that is running in the same WOW64 level. */ #ifdef _M_X64 FORCE(RhIsX64Process(InTargetPID, &Is64BitTarget)); if(!Is64BitTarget) THROW(STATUS_WOW_ASSERTION, L"It is not supported to directly hook through the WOW64 barrier."); if(!GetFullPathNameW(InLibraryPath_x64, MAX_PATH, UserLibrary, NULL)) THROW(STATUS_INVALID_PARAMETER_5, L"Unable to get full path to the given 64-bit library."); #else FORCE(RhIsX64Process(InTargetPID, &Is64BitTarget)); if(Is64BitTarget) THROW(STATUS_WOW_ASSERTION, L"It is not supported to directly hook through the WOW64 barrier."); if(!GetFullPathNameW(InLibraryPath_x86, MAX_PATH, UserLibrary, NULL)) THROW(STATUS_INVALID_PARAMETER_4, L"Unable to get full path to the given 32-bit library."); #endif /* Validate library path... */ if(!RtlFileExists(UserLibrary)) { #ifdef _M_X64 THROW(STATUS_INVALID_PARAMETER_5, L"The given 64-Bit library does not exist!"); #else THROW(STATUS_INVALID_PARAMETER_4, L"The given 32-Bit library does not exist!"); #endif } // import strings... RtlGetWorkingDirectory(PATH, MAX_PATH - 1); RtlGetCurrentModulePath(EasyHookPath, MAX_PATH); // allocate remote information block EasyHookPathSize = (RtlUnicodeLength(EasyHookPath) + 1) * 2; EasyHookEntrySize = (RtlAnsiLength(EasyHookEntry) + 1); PATHSize = (RtlUnicodeLength(PATH) + 1 + 1) * 2; UserLibrarySize = (RtlUnicodeLength(UserLibrary) + 1 + 1) * 2; PATH[PATHSize / 2 - 2] = ';'; PATH[PATHSize / 2 - 1] = 0; RemoteInfoSize = EasyHookPathSize + EasyHookEntrySize + PATHSize + InPassThruSize + UserLibrarySize; RemoteInfoSize += sizeof(REMOTE_INFO); if((Info = (LPREMOTE_INFO)RtlAllocateMemory(TRUE, RemoteInfoSize)) == NULL) THROW(STATUS_NO_MEMORY, L"Unable to allocate memory in current process."); Info->LoadLibraryW = (PVOID)GetProcAddress(hKernel32, "LoadLibraryW"); Info->FreeLibrary = (PVOID)GetProcAddress(hKernel32, "FreeLibrary"); Info->GetProcAddress = (PVOID)GetProcAddress(hKernel32, "GetProcAddress"); Info->VirtualFree = (PVOID)GetProcAddress(hKernel32, "VirtualFree"); Info->VirtualProtect = (PVOID)GetProcAddress(hKernel32, "VirtualProtect"); Info->ExitThread = (PVOID)GetProcAddress(hKernel32, "ExitThread"); Info->GetLastError = (PVOID)GetProcAddress(hKernel32, "GetLastError"); Info->WakeUpThreadID = InWakeUpTID; Info->IsManaged = InInjectionOptions & EASYHOOK_INJECT_MANAGED; // allocate memory in target process CodeSize = GetInjectionSize(); if((RemoteInjectCode = (BYTE*)VirtualAllocEx(hProc, NULL, CodeSize + RemoteInfoSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE)) == NULL) THROW(STATUS_NO_MEMORY, L"Unable to allocate memory in target process."); // save strings Offset = (BYTE*)(Info + 1); Info->EasyHookEntry = (char*)Offset; Info->EasyHookPath = (wchar_t*)(Offset += EasyHookEntrySize); Info->PATH = (wchar_t*)(Offset += EasyHookPathSize); Info->UserData = (BYTE*)(Offset += PATHSize); Info->UserLibrary = (WCHAR*)(Offset += InPassThruSize); Info->Size = RemoteInfoSize; Info->HostProcess = GetCurrentProcessId(); Info->UserDataSize = 0; Offset += UserLibrarySize; if((ULONG)(Offset - ((BYTE*)Info)) > Info->Size) THROW(STATUS_BUFFER_OVERFLOW, L"A buffer overflow in internal memory was detected."); RtlCopyMemory(Info->EasyHookPath, EasyHookPath, EasyHookPathSize); RtlCopyMemory(Info->PATH, PATH, PATHSize); RtlCopyMemory(Info->EasyHookEntry, EasyHookEntry, EasyHookEntrySize); RtlCopyMemory(Info->UserLibrary, UserLibrary, UserLibrarySize); if(InPassThruBuffer != NULL) { RtlCopyMemory(Info->UserData, InPassThruBuffer, InPassThruSize); Info->UserDataSize = InPassThruSize; } // copy code into target process if(!WriteProcessMemory(hProc, RemoteInjectCode, GetInjectionPtr(), CodeSize, &BytesWritten) || (BytesWritten != CodeSize)) THROW(STATUS_INTERNAL_ERROR, L"Unable to write into target process memory."); // create and export signal event> if((hSignal = CreateEvent(NULL, TRUE, FALSE, NULL)) == NULL) THROW(STATUS_INSUFFICIENT_RESOURCES, L"Unable to create event."); // Possible resource leck: the remote handles cannt be closed here if an error occurs if(!DuplicateHandle(GetCurrentProcess(), hSignal, hProc, &Info->hRemoteSignal, EVENT_ALL_ACCESS, FALSE, 0)) THROW(STATUS_INTERNAL_ERROR, L"Failed to duplicate remote event."); // relocate remote information RemoteInfo = (LPREMOTE_INFO)(RemoteInjectCode + CodeSize); Diff = ((BYTE*)RemoteInfo - (BYTE*)Info); Info->EasyHookEntry = (char*)(((BYTE*)Info->EasyHookEntry) + Diff); Info->EasyHookPath = (wchar_t*)(((BYTE*)Info->EasyHookPath) + Diff); Info->PATH = (wchar_t*)(((BYTE*)Info->PATH) + Diff); Info->UserLibrary = (wchar_t*)(((BYTE*)Info->UserLibrary) + Diff); if(Info->UserData != NULL) Info->UserData = (BYTE*)(((BYTE*)Info->UserData) + Diff); Info->RemoteEntryPoint = RemoteInjectCode; if(!WriteProcessMemory(hProc, RemoteInfo, Info, RemoteInfoSize, &BytesWritten) || (BytesWritten != RemoteInfoSize)) THROW(STATUS_INTERNAL_ERROR, L"Unable to write into target process memory."); if((InInjectionOptions & EASYHOOK_INJECT_STEALTH) != 0) { FORCE(RhCreateStealthRemoteThread(InTargetPID, (LPTHREAD_START_ROUTINE)RemoteInjectCode, RemoteInfo, &hRemoteThread)); } else { if(!RTL_SUCCESS(NtCreateThreadEx(hProc, (LPTHREAD_START_ROUTINE)RemoteInjectCode, RemoteInfo, FALSE, &hRemoteThread))) { // create remote thread and wait for injection completion if((hRemoteThread = CreateRemoteThread(hProc, NULL, 0, (LPTHREAD_START_ROUTINE)RemoteInjectCode, RemoteInfo, 0, NULL)) == NULL) THROW(STATUS_ACCESS_DENIED, L"Unable to create remote thread."); } } /* * The assembler codes are designed to let us derive extensive error information... */ Handles[1] = hSignal; Handles[0] = hRemoteThread; Code = WaitForMultipleObjects(2, Handles, FALSE, INFINITE); if(Code == WAIT_OBJECT_0) { // parse error code GetExitCodeThread(hRemoteThread, &Code); SetLastError(Code & 0x0FFFFFFF); switch(Code & 0xF0000000) { case 0x10000000: THROW(STATUS_INTERNAL_ERROR, L"Unable to find internal entry point."); case 0x20000000: THROW(STATUS_INTERNAL_ERROR, L"Unable to make stack executable."); case 0x30000000: THROW(STATUS_INTERNAL_ERROR, L"Unable to release injected library."); case 0x40000000: THROW(STATUS_INTERNAL_ERROR, L"Unable to find EasyHook library in target process context."); case 0xF0000000: // error in C++ injection completion { switch(Code & 0xFF) { #ifdef _M_X64 case 20: THROW(STATUS_INVALID_PARAMETER_5, L"Unable to load the given 64-bit library into target process."); case 21: THROW(STATUS_INVALID_PARAMETER_5, L"Unable to find the required native entry point in the given 64-bit library."); case 12: THROW(STATUS_INVALID_PARAMETER_5, L"Unable to find the required managed entry point in the given 64-bit library."); #else case 20: THROW(STATUS_INVALID_PARAMETER_4, L"Unable to load the given 32-bit library into target process."); case 21: THROW(STATUS_INVALID_PARAMETER_4, L"Unable to find the required native entry point in the given 32-bit library."); case 12: THROW(STATUS_INVALID_PARAMETER_4, L"Unable to find the required managed entry point in the given 32-bit library."); #endif case 13: THROW(STATUS_DLL_INIT_FAILED, L"The user defined managed entry point failed in the target process. Make sure that EasyHook is registered in the GAC. Refer to event logs for more information."); case 1: THROW(STATUS_INTERNAL_ERROR, L"Unable to allocate memory in target process."); case 2: THROW(STATUS_INTERNAL_ERROR, L"Unable to adjust target's PATH variable."); case 10: THROW(STATUS_INTERNAL_ERROR, L"Unable to load 'mscoree.dll' into target process."); case 11: THROW(STATUS_INTERNAL_ERROR, L"Unable to bind NET Runtime to target process."); case 22: THROW(STATUS_INTERNAL_ERROR, L"Unable to signal remote event."); default: THROW(STATUS_INTERNAL_ERROR, L"Unknown error in injected C++ completion routine."); } }break; case 0: THROW(STATUS_INTERNAL_ERROR, L"C++ completion routine has returned success but didn't raise the remote event."); default: THROW(STATUS_INTERNAL_ERROR, L"Unknown error in injected assembler code."); } } else if(Code != WAIT_OBJECT_0 + 1) THROW(STATUS_INTERNAL_ERROR, L"Unable to wait for injection completion due to timeout. "); RETURN; THROW_OUTRO: FINALLY_OUTRO: { // release resources if(hProc != NULL) CloseHandle(hProc); if(Info != NULL) RtlFreeMemory(Info); if(hRemoteThread != NULL) CloseHandle(hRemoteThread); if(hSignal != NULL) CloseHandle(hSignal); return NtStatus; } }
/* * This function tries to determine the icon geometry from the tray * * If it fails an invalid rect is returned. */ QRect QSystemTrayIconSys::findIconGeometry(const int iconId) { static PtrShell_NotifyIconGetRect Shell_NotifyIconGetRect = (PtrShell_NotifyIconGetRect)QSystemLibrary::resolve(QLatin1String("shell32"), "Shell_NotifyIconGetRect"); if (Shell_NotifyIconGetRect) { Q_NOTIFYICONIDENTIFIER nid; memset(&nid, 0, sizeof(nid)); nid.cbSize = sizeof(nid); nid.hWnd = winId(); nid.uID = iconId; RECT rect; HRESULT hr = Shell_NotifyIconGetRect(&nid, &rect); if (SUCCEEDED(hr)) { return QRect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top); } } QRect ret; TBBUTTON buttonData; DWORD processID = 0; HWND trayHandle = FindWindow(L"Shell_TrayWnd", NULL); //find the toolbar used in the notification area if (trayHandle) { trayHandle = FindWindowEx(trayHandle, NULL, L"TrayNotifyWnd", NULL); if (trayHandle) { HWND hwnd = FindWindowEx(trayHandle, NULL, L"SysPager", NULL); if (hwnd) { hwnd = FindWindowEx(hwnd, NULL, L"ToolbarWindow32", NULL); if (hwnd) trayHandle = hwnd; } } } if (!trayHandle) return ret; GetWindowThreadProcessId(trayHandle, &processID); if (processID <= 0) return ret; HANDLE trayProcess = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ, 0, processID); if (!trayProcess) return ret; int buttonCount = SendMessage(trayHandle, TB_BUTTONCOUNT, 0, 0); LPVOID data = VirtualAllocEx(trayProcess, NULL, sizeof(TBBUTTON), MEM_COMMIT, PAGE_READWRITE); if ( buttonCount < 1 || !data ) { CloseHandle(trayProcess); return ret; } //search for our icon among all toolbar buttons for (int toolbarButton = 0; toolbarButton < buttonCount; ++toolbarButton ) { SIZE_T numBytes = 0; DWORD appData[2] = { 0, 0 }; SendMessage(trayHandle, TB_GETBUTTON, toolbarButton , (LPARAM)data); if (!ReadProcessMemory(trayProcess, data, &buttonData, sizeof(TBBUTTON), &numBytes)) continue; if (!ReadProcessMemory(trayProcess, (LPVOID) buttonData.dwData, appData, sizeof(appData), &numBytes)) continue; int currentIconId = appData[1]; HWND currentIconHandle = (HWND) appData[0]; bool isHidden = buttonData.fsState & TBSTATE_HIDDEN; if (currentIconHandle == winId() && currentIconId == iconId && !isHidden) { SendMessage(trayHandle, TB_GETITEMRECT, toolbarButton , (LPARAM)data); RECT iconRect = {0, 0}; if(ReadProcessMemory(trayProcess, data, &iconRect, sizeof(RECT), &numBytes)) { MapWindowPoints(trayHandle, NULL, (LPPOINT)&iconRect, 2); QRect geometry(iconRect.left + 1, iconRect.top + 1, iconRect.right - iconRect.left - 2, iconRect.bottom - iconRect.top - 2); if (geometry.isValid()) ret = geometry; break; } } } VirtualFreeEx(trayProcess, data, 0, MEM_RELEASE); CloseHandle(trayProcess); return ret; }
int CollectorWin::preCollect(const CollectorHints& hints, uint64_t /* iTick */) { LogFlowThisFuncEnter(); uint64_t user, kernel, idle, total; int rc = getRawHostCpuLoad(&user, &kernel, &idle); if (RT_FAILURE(rc)) return rc; total = user + kernel + idle; DWORD dwError; const CollectorHints::ProcessList& processes = hints.getProcessFlags(); CollectorHints::ProcessList::const_iterator it; mProcessStats.clear(); for (it = processes.begin(); it != processes.end() && RT_SUCCESS(rc); it++) { RTPROCESS process = it->first; HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, process); if (!h) { dwError = GetLastError(); Log (("OpenProcess() -> 0x%x\n", dwError)); rc = RTErrConvertFromWin32(dwError); break; } VMProcessStats vmStats; if ((it->second & COLLECT_CPU_LOAD) != 0) { FILETIME ftCreate, ftExit, ftKernel, ftUser; if (!GetProcessTimes(h, &ftCreate, &ftExit, &ftKernel, &ftUser)) { dwError = GetLastError(); Log (("GetProcessTimes() -> 0x%x\n", dwError)); rc = RTErrConvertFromWin32(dwError); } else { vmStats.cpuKernel = FILETTIME_TO_100NS(ftKernel); vmStats.cpuUser = FILETTIME_TO_100NS(ftUser); vmStats.cpuTotal = total; } } if (RT_SUCCESS(rc) && (it->second & COLLECT_RAM_USAGE) != 0) { PROCESS_MEMORY_COUNTERS pmc; if (!GetProcessMemoryInfo(h, &pmc, sizeof(pmc))) { dwError = GetLastError(); Log (("GetProcessMemoryInfo() -> 0x%x\n", dwError)); rc = RTErrConvertFromWin32(dwError); } else vmStats.ramUsed = pmc.WorkingSetSize; } CloseHandle(h); mProcessStats[process] = vmStats; } LogFlowThisFuncLeave(); return rc; }
int OperationFailed(const string& Object, LNGID Title, const string& Description, bool AllowSkip) { std::vector<string> Msg; IFileIsInUse *pfiu = nullptr; LNGID Reason = MObjectLockedReasonOpened; bool SwitchBtn = false, CloseBtn = false; DWORD Error = Global->CaughtError(); if(Error == ERROR_ACCESS_DENIED || Error == ERROR_SHARING_VIOLATION || Error == ERROR_LOCK_VIOLATION || Error == ERROR_DRIVE_LOCKED) { string FullName; ConvertNameToFull(Object, FullName); pfiu = CreateIFileIsInUse(FullName); if (pfiu) { FILE_USAGE_TYPE UsageType = FUT_GENERIC; pfiu->GetUsage(&UsageType); switch(UsageType) { case FUT_PLAYING: Reason = MObjectLockedReasonPlayed; break; case FUT_EDITING: Reason = MObjectLockedReasonEdited; break; case FUT_GENERIC: Reason = MObjectLockedReasonOpened; break; } DWORD Capabilities = 0; pfiu->GetCapabilities(&Capabilities); if(Capabilities&OF_CAP_CANSWITCHTO) { SwitchBtn = true; } if(Capabilities&OF_CAP_CANCLOSE) { CloseBtn = true; } LPWSTR AppName = nullptr; if(SUCCEEDED(pfiu->GetAppName(&AppName))) { Msg.emplace_back(AppName); } } else { DWORD dwSession; WCHAR szSessionKey[CCH_RM_SESSION_KEY+1] = {}; if (Imports().RmStartSession(&dwSession, 0, szSessionKey) == ERROR_SUCCESS) { PCWSTR pszFile = FullName.data(); if (Imports().RmRegisterResources(dwSession, 1, &pszFile, 0, nullptr, 0, nullptr) == ERROR_SUCCESS) { DWORD dwReason; DWORD RmGetListResult; UINT nProcInfoNeeded; UINT nProcInfo = 1; std::vector<RM_PROCESS_INFO> rgpi(nProcInfo); while((RmGetListResult=Imports().RmGetList(dwSession, &nProcInfoNeeded, &nProcInfo, rgpi.data(), &dwReason)) == ERROR_MORE_DATA) { nProcInfo = nProcInfoNeeded; rgpi.resize(nProcInfo); } if(RmGetListResult ==ERROR_SUCCESS) { for (size_t i = 0; i < nProcInfo; i++) { string tmp = rgpi[i].strAppName; if (*rgpi[i].strServiceShortName) { tmp.append(L" [").append(rgpi[i].strServiceShortName).append(L"]"); } tmp += L" (PID: " + std::to_wstring(rgpi[i].Process.dwProcessId); HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, rgpi[i].Process.dwProcessId); if (hProcess) { FILETIME ftCreate, ftExit, ftKernel, ftUser; if (GetProcessTimes(hProcess, &ftCreate, &ftExit, &ftKernel, &ftUser) && rgpi[i].Process.ProcessStartTime == ftCreate) { string Name; if (os::GetModuleFileNameEx(hProcess, nullptr, Name)) { tmp += L", " + Name; } } CloseHandle(hProcess); } tmp += L")"; Msg.emplace_back(tmp); } } } Imports().RmEndSession(dwSession); } } } auto Msgs = make_vector(Description, QuoteLeadingSpace(string(Object))); if(!Msg.empty()) { Msgs.emplace_back(LangString(MObjectLockedReason) << MSG(Reason)); Msgs.insert(Msgs.end(), ALL_CONST_RANGE(Msg)); } std::vector<string> Buttons; Buttons.reserve(4); if(SwitchBtn) { Buttons.emplace_back(MSG(MObjectLockedSwitchTo)); } Buttons.emplace_back(MSG(CloseBtn? MObjectLockedClose : MDeleteRetry)); if(AllowSkip) { Buttons.emplace_back(MSG(MDeleteSkip)); Buttons.emplace_back(MSG(MDeleteFileSkipAll)); } Buttons.emplace_back(MSG(MDeleteCancel)); int Result = -1; for(;;) { Result = Message(MSG_WARNING|MSG_ERRORTYPE, MSG(Title), Msgs, Buttons); if(SwitchBtn) { if(Result == 0) { HWND Wnd = nullptr; if (pfiu && SUCCEEDED(pfiu->GetSwitchToHWND(&Wnd))) { SetForegroundWindow(Wnd); if (IsIconic(Wnd)) ShowWindow(Wnd, SW_RESTORE); } continue; } else if(Result > 0) { --Result; } } if(CloseBtn && Result == 0) { // close & retry if (pfiu) { pfiu->CloseFile(); } } break; } if (pfiu) { pfiu->Release(); } return Result; }
//---------------------------------------------------------------- // CImpIRestrictedProcess::RP_WahOpenHandleHelper() // // In order to use WPUCreateSocketHandle(), this function must be // remoted because it creates a file handle... // // BUGBUG: Make hSourceProcess and hTargetProcess part of the // object... //---------------------------------------------------------------- STDMETHODIMP CImpIRestrictedProcess::RP_WahOpenHandleHelper( IN DWORD dwTargetPid, OUT DWORD *pdwHelperHandle, OUT DWORD *pdwStatus ) { BOOL fInherit; DWORD dwSourcePid; DWORD dwAccess; DWORD dwOptions; HANDLE hSourceProcess; HANDLE hSourceHandle; HANDLE hTargetProcess; *pdwHelperHandle = 0; *pdwStatus = WahOpenHandleHelper(&m_hHelper); if (*pdwStatus) { return NOERROR; } // Get a handle to our own process (to be used by DuplicateHandle()). dwSourcePid = GetCurrentProcessId(); hSourceProcess = OpenProcess( PROCESS_DUP_HANDLE, TRUE, dwSourcePid ); if (!hSourceProcess) { *pdwStatus = GetLastError(); WahCloseHandleHelper(m_hHelper); m_hHelper = 0; return NOERROR; } // Get a handle to the restricted process hTargetProcess = OpenProcess( PROCESS_DUP_HANDLE, TRUE, dwTargetPid ); if (!hTargetProcess) { *pdwStatus = GetLastError(); WahCloseHandleHelper(m_hHelper); m_hHelper = 0; CloseHandle(hSourceProcess); return NOERROR; } // Ok, duplicate the helper handle into the restricted client. dwAccess = 0; fInherit = FALSE; dwOptions = DUPLICATE_SAME_ACCESS; if (!DuplicateHandle(hSourceProcess, (HANDLE)m_hHelper, hTargetProcess, (HANDLE*)pdwHelperHandle, dwAccess, fInherit, dwOptions )) { *pdwStatus = GetLastError(); WahCloseHandleHelper(m_hHelper); m_hHelper = 0; } else { m_hHelper = (HANDLE)*pdwHelperHandle; } // Done with the process handles. CloseHandle(hSourceProcess); CloseHandle(hTargetProcess); return NOERROR; }
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; }
//---------------------------------------------------------------- // CImpIRestrictedProcess::RP_WSPConnect() // //---------------------------------------------------------------- STDMETHODIMP CImpIRestrictedProcess::RP_WSPConnect( IN RPC_SOCKADDR_IN *pInAddr, IN long lAddrLen, IN RPC_WSABUF *pCallerData, OUT RPC_WSABUF *pCalleeData, IN RPC_QOS *pSQOS, IN RPC_QOS *pGQOS, IN DWORD dwTargetPid, OUT DWORD *pTargetSocket, OUT long *pError ) { int iRet; HRESULT hr; BOOL fInherit; DWORD dwSourcePid; DWORD dwAccess; DWORD dwOptions; NTSTATUS NtStatus; HANDLE hSourceProcess; HANDLE hSourceHandle; HANDLE hTargetProcess; *pError = NO_ERROR; dwSourcePid = GetCurrentProcessId(); if (!dwSourcePid) { *pError = GetLastError(); return NOERROR; } if (m_Socket == INVALID_SOCKET) { *pError = WSAEACCES; closesocket(m_Socket); m_Socket = INVALID_SOCKET; return NOERROR; } // // Check to make sure the restricted client is connecting only // to a server that we allow. // hr = IsValidAddr( (char*)&(pInAddr->sin_addr), sizeof(ULONG) ); #ifdef DBG_ALWAYS_RESTRICTED DbgPrint("RP_WSPConnect(): IsValidAdder(): %s\n", (hr == S_OK)? "TRUE" : "FALSE" ); hr = S_OK; #endif if (S_OK != hr) { *pError = WSAEACCES; closesocket(m_Socket); m_Socket = INVALID_SOCKET; return NOERROR; } // Ok, do the connect() on behalf of the restricted client iRet = WSAConnect( m_Socket, (struct sockaddr *)pInAddr, lAddrLen, (WSABUF*)pCallerData, (WSABUF*)pCalleeData, (QOS*)pSQOS, (QOS*)pGQOS ); if (iRet == SOCKET_ERROR) { *pError = WSAGetLastError(); closesocket(m_Socket); m_Socket = INVALID_SOCKET; return NOERROR; } // Get a handle to our own process (to be used by DuplicateHandle()). hSourceProcess = OpenProcess( PROCESS_DUP_HANDLE, TRUE, dwSourcePid ); if (!hSourceProcess) { *pError = GetLastError(); closesocket(m_Socket); m_Socket = INVALID_SOCKET; return NOERROR; } // Get a handle to the restricted process hTargetProcess = OpenProcess( PROCESS_DUP_HANDLE, TRUE, dwTargetPid ); if (!hTargetProcess) { *pError = GetLastError(); closesocket(m_Socket); m_Socket = INVALID_SOCKET; CloseHandle(hSourceProcess); return NOERROR; } // Ok, duplicate the socket into the restricted client. dwAccess = 0; fInherit = FALSE; dwOptions = DUPLICATE_SAME_ACCESS; if (!DuplicateHandle(hSourceProcess, (HANDLE)m_Socket, hTargetProcess, (HANDLE*)pTargetSocket, dwAccess, fInherit, dwOptions )) { *pError = GetLastError(); } // No longer need a local copy of the open socket. closesocket(m_Socket); m_Socket = INVALID_SOCKET; // Done with the process handles. CloseHandle(hSourceProcess); CloseHandle(hTargetProcess); return NOERROR; }
/* * Entry. */ int __cdecl main(int argc, char **argv) { HANDLE handle, process, console; INT16 priority = 1121; // Arbitrary. const char *filter = "true", *err_str; char path[MAX_PATH+1]; char local_str[INET6_ADDRSTRLEN+1], remote_str[INET6_ADDRSTRLEN+1]; char *filename; DWORD path_len; WINDIVERT_ADDRESS addr; BOOL block = FALSE; switch (argc) { case 1: break; case 2: if (strcmp(argv[1], "--block") == 0) { block = TRUE; } else { filter = argv[1]; } break; case 3: if (strcmp(argv[1], "--block") == 0) { block = TRUE; filter = argv[2]; break; } // Fallthrough: default: fprintf(stderr, "usage: %s [filter]\n", argv[0]); fprintf(stderr, " %s --block [filter]\n", argv[0]); exit(EXIT_FAILURE); } // Open WinDivert SOCKET handle: handle = WinDivertOpen(filter, WINDIVERT_LAYER_SOCKET, priority, (block? 0: WINDIVERT_FLAG_SNIFF) | WINDIVERT_FLAG_RECV_ONLY); if (handle == INVALID_HANDLE_VALUE) { if (GetLastError() == ERROR_INVALID_PARAMETER && !WinDivertHelperCompileFilter(filter, WINDIVERT_LAYER_SOCKET, NULL, 0, &err_str, NULL)) { fprintf(stderr, "error: invalid filter \"%s\"\n", err_str); exit(EXIT_FAILURE); } fprintf(stderr, "error: failed to open the WinDivert device (%d)\n", GetLastError()); return EXIT_FAILURE; } // Main loop: console = GetStdHandle(STD_OUTPUT_HANDLE); while (TRUE) { if (!WinDivertRecv(handle, NULL, 0, NULL, &addr)) { fprintf(stderr, "failed to read packet (%d)\n", GetLastError()); continue; } switch (addr.Event) { case WINDIVERT_EVENT_SOCKET_BIND: SetConsoleTextAttribute(console, FOREGROUND_GREEN); printf("BIND"); break; case WINDIVERT_EVENT_SOCKET_LISTEN: SetConsoleTextAttribute(console, FOREGROUND_GREEN); printf("LISTEN"); break; case WINDIVERT_EVENT_SOCKET_CONNECT: SetConsoleTextAttribute(console, FOREGROUND_GREEN); printf("CONNECT"); break; case WINDIVERT_EVENT_SOCKET_ACCEPT: SetConsoleTextAttribute(console, FOREGROUND_GREEN); printf("ACCEPT"); break; case WINDIVERT_EVENT_SOCKET_CLOSE: SetConsoleTextAttribute(console, FOREGROUND_RED); printf("CLOSE"); break; default: SetConsoleTextAttribute(console, FOREGROUND_BLUE); printf("???"); break; } SetConsoleTextAttribute(console, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); printf(" pid="); SetConsoleTextAttribute(console, FOREGROUND_RED | FOREGROUND_GREEN); printf("%u", addr.Socket.ProcessId); SetConsoleTextAttribute(console, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); printf(" program="); process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, addr.Socket.ProcessId); path_len = 0; if (process != NULL) { path_len = GetProcessImageFileName(process, path, sizeof(path)); CloseHandle(process); } SetConsoleTextAttribute(console, FOREGROUND_RED | FOREGROUND_GREEN); if (path_len != 0) { filename = PathFindFileName(path); printf("%s", filename); } else if (addr.Socket.ProcessId == 4) { printf("Windows"); } else { printf("???"); } SetConsoleTextAttribute(console, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); printf(" endpoint="); SetConsoleTextAttribute(console, FOREGROUND_RED | FOREGROUND_GREEN); printf("%lu", addr.Socket.EndpointId); SetConsoleTextAttribute(console, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); printf(" parent="); SetConsoleTextAttribute(console, FOREGROUND_RED | FOREGROUND_GREEN); printf("%lu", addr.Socket.ParentEndpointId); SetConsoleTextAttribute(console, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); printf(" protocol="); SetConsoleTextAttribute(console, FOREGROUND_RED | FOREGROUND_GREEN); switch (addr.Socket.Protocol) { case IPPROTO_TCP: printf("TCP"); break; case IPPROTO_UDP: printf("UDP"); break; case IPPROTO_ICMP: printf("ICMP"); break; case IPPROTO_ICMPV6: printf("ICMPV6"); break; default: printf("%u", addr.Socket.Protocol); break; } SetConsoleTextAttribute(console, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); WinDivertHelperFormatIPv6Address(addr.Socket.LocalAddr, local_str, sizeof(local_str)); if (addr.Socket.LocalPort != 0 || strcmp(local_str, "::") != 0) { printf(" local="); SetConsoleTextAttribute(console, FOREGROUND_RED | FOREGROUND_GREEN); printf("[%s]:%u", local_str, addr.Socket.LocalPort); SetConsoleTextAttribute(console, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); } WinDivertHelperFormatIPv6Address(addr.Socket.RemoteAddr, remote_str, sizeof(remote_str)); if (addr.Socket.RemotePort != 0 || strcmp(remote_str, "::") != 0) { printf(" remote="); SetConsoleTextAttribute(console, FOREGROUND_RED | FOREGROUND_GREEN); printf("[%s]:%u", remote_str, addr.Socket.RemotePort); SetConsoleTextAttribute(console, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); } putchar('\n'); } return 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, RString &sName ) { /* This method works in everything except for NT4, and only uses * kernel32.lib functions. */ do { HANDLE hSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, iProcessID ); if( hSnap == NULL ) { sName = werr_ssprintf( 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_ssprintf( GetLastError(), "Module32First" ); } while(0); // This method only works in NT/2K/XP. do { static HINSTANCE hPSApi = NULL; typedef DWORD (WINAPI* pfnGetProcessImageFileNameA)(HANDLE hProcess, LPSTR lpImageFileName, DWORD nSize); static pfnGetProcessImageFileNameA pGetProcessImageFileName = NULL; static bool bTried = false; if( !bTried ) { bTried = true; hPSApi = LoadLibrary("psapi.dll"); if( hPSApi == NULL ) { sName = werr_ssprintf( GetLastError(), "LoadLibrary" ); break; } else { pGetProcessImageFileName = (pfnGetProcessImageFileNameA) GetProcAddress( hPSApi, "GetProcessImageFileNameA" ); if( pGetProcessImageFileName == NULL ) { sName = werr_ssprintf( GetLastError(), "GetProcAddress" ); break; } } } if( pGetProcessImageFileName != NULL ) { HANDLE hProc = OpenProcess( PROCESS_VM_READ|PROCESS_QUERY_INFORMATION, NULL, iProcessID ); if( hProc == NULL ) { sName = werr_ssprintf( 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_ssprintf( GetLastError(), "GetProcessImageFileName" ); } } while(0); return false; }
int main(int argc, char *argv[]) { #if 1 HANDLE hProcess; DWORD procAddr, procAddr2; DWORD procId; if (argc < 2) { printf("Current process\n"); procId = (DWORD) GetCurrentProcessId(); } else { printf("Process: %s\n", argv[1]); procId = atoi(argv[1]); } hProcess = OpenProcess( PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, procId); if (hProcess == NULL) return 1; DWORD pKernel32 = GetRemoteModule(hProcess, "kernel32.dll"); DWORD pNtdll = GetRemoteModule(hProcess, "ntdll.dll"); if ((!pKernel32)||(!pNtdll)) return 1; procAddr = GetProcedureAddress(hProcess, pKernel32, "KERNEL32.dll", LOAD_LIBRARY_NAME); procAddr2 = GetProcedureAddress(hProcess, pNtdll, "ntdll.dll", "RtlGetLastWin32Error"); printf("LoadLibraryA:\t0x%08x\nRtlGetLastWin32Error:\t0x%08x\n", procAddr, procAddr2); if ((procAddr == 0)||(procAddr2 == 0)) { return 1; } printf("Trying to inject...\n"); // HMODULE hModule = LoadLibraryW(L"kernel32.dll"); #endif #define THREAD_ALLOC_SIZE 4096 LPVOID pRemote = VirtualAllocEx( hProcess, NULL, THREAD_ALLOC_SIZE, MEM_COMMIT, PAGE_EXECUTE_READWRITE ); if (pRemote == NULL) { printf("Failed to allocate memory in remote process: %x\n", GetLastError()); goto exit; } char libName[] = "c:\\111\\dll.dll"; printf("lib_name:\t%d\nop_call_2:\t%d\nop_ret:\t%d\n", FIELD_OFFSET(SHELL_CODE,lib_name), FIELD_OFFSET(SHELL_CODE,op_call_2), FIELD_OFFSET(SHELL_CODE,op_ret)); /* // Copy string to remote process address space if (!WriteProcessMemory(hProcess, (LPVOID) ((DWORD) pRemote + 13), (PVOID) libName, sizeof(libName), NULL)) { printf("Failed to write in remote process libName: %x\n", GetLastError()); goto exit; } DWORD tmp = (DWORD) pRemote + 18; DWORD call_addr = procAddr - (DWORD) pRemote - 11; printf("Call Addr: 0x%08x\n", call_addr); DWORD call_addr2 = procAddr2 - (DWORD) pRemote - 16; printf("Call Addr: 0x%08x\n", call_addr); //pRemote+6 : call call_addr // dest_addr = pRemote + 11 + call_addr = procAddr; char code[] = { 0xcc, // int3 0x68, tmp & 0xff, tmp >> 8 & 0xff, tmp >> 16 & 0xff, tmp >> 24 & 0xff , // push 0xe8, call_addr & 0xff, call_addr >> 8 & 0xff, call_addr >> 16 & 0xff, call_addr >> 24 & 0xff , // call 0xe8, call_addr2 & 0xff, call_addr2 >> 8 & 0xff, call_addr2 >> 16 & 0xff, call_addr2 >> 24 & 0xff , 0xcc, 0xc2, 0x04, // ret }; */ char code[256]; InitShellCode((PSHELL_CODE)code, (DWORD) pRemote, procAddr, procAddr2, libName); __debugbreak(); LoadLibraryA(libName); // Write inject code if (!WriteProcessMemory(hProcess, pRemote, code, sizeof(code), NULL)) { printf("Failed to write in remote process code: %x\n", GetLastError()); goto exit; } HANDLE hThread = CreateRemoteThread( hProcess, NULL, 0, (LPTHREAD_START_ROUTINE) pRemote, NULL, 0, NULL ); if(hThread == NULL) { printf("Failed to CreateRemoteThread: %x\n", GetLastError()); return 1; } WaitForSingleObject(hThread, INFINITE); exit: printf("Freeing resources...\n"); if (pRemote) VirtualFreeEx(hProcess, pRemote, 0, MEM_RELEASE); if (hThread) CloseHandle(hThread); if (hProcess) CloseHandle(hProcess); getch(); return 0; }
//------------------------------------------------------------------------------ // Name: update_list(const QString &filter) // Desc: //------------------------------------------------------------------------------ void DialogAttach::update_list(const QString &filter) { QMap<edb::pid_t, ProcessInfo> procs; edb::uid_t myUID = 0; // FILL up procs HANDLE handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(handle != INVALID_HANDLE_VALUE) { PROCESSENTRY32 lppe; std::memset(&lppe, 0, sizeof(lppe)); lppe.dwSize = sizeof(lppe); if(Process32First(handle, &lppe)) { do { ProcessInfo pi; pi.pid = lppe.th32ProcessID; pi.uid = 0; // TODO pi.name = QString::fromWCharArray(lppe.szExeFile); HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, lppe.th32ProcessID); if(hProc != 0) { BOOL wow64 = FALSE; if(fnIsWow64Process && fnIsWow64Process(hProc, &wow64) && wow64) { pi.name += " *32"; } pi.user = dumpToken(hProc); CloseHandle(hProc); } procs[pi.pid] = pi; std::memset(&lppe, 0, sizeof(lppe)); lppe.dwSize = sizeof(lppe); } while(Process32Next(handle, &lppe)); } CloseHandle(handle); } const bool filterUID = ui->filter_uid->isChecked(); const QString lowerFilter = filter.toLower(); ui->processes_table->setSortingEnabled(false); ui->processes_table->setRowCount(0); Q_FOREACH(const ProcessInfo &procInfo, procs) { const QString procName = procInfo.name; if(filter.isEmpty() || procName.toLower().contains(lowerFilter)) { if(!filterUID || procInfo.uid == myUID) { const int row = ui->processes_table->rowCount(); ui->processes_table->insertRow(row); QTableWidgetItem *const itemPID = new QTableWidgetItem; itemPID->setData(Qt::DisplayRole, static_cast<quint32>(procInfo.pid)); QTableWidgetItem *itemUID; if(!procInfo.user.isEmpty()) { itemUID = new QTableWidgetItem(procInfo.user); } else { itemUID = new QTableWidgetItem; itemUID->setData(Qt::DisplayRole, static_cast<quint32>(procInfo.uid)); } ui->processes_table->setItem(row, 0, itemPID); ui->processes_table->setItem(row, 1, itemUID); ui->processes_table->setItem(row, 2, new QTableWidgetItem(procInfo.name)); } } } ui->processes_table->setSortingEnabled(true); }
EASYHOOK_NT_EXPORT RhIsX64Process( ULONG InProcessId, BOOL* OutResult) { /* Description: Detects the bitness of a given process. Parameters: - InProcessId The calling process must have PROCESS_QUERY_INFORMATION access to the process represented by this ID. - OutResult Is set to TRUE if the given process is running under 64-Bit, FALSE otherwise. */ BOOL IsTarget64Bit = FALSE; HANDLE hProc = NULL; IsWow64Process_PROC* pIsWow64Process; NTSTATUS NtStatus; #ifndef _M_X64 GetNativeSystemInfo_PROC* pGetNativeSystemInfo; SYSTEM_INFO SysInfo; #endif if(!IsValidPointer(OutResult, sizeof(BOOL))) THROW(STATUS_INVALID_PARAMETER_2, L"The given result storage is invalid."); // open target process if((hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, InProcessId)) == NULL) { if(GetLastError() == ERROR_ACCESS_DENIED) THROW(STATUS_ACCESS_DENIED, L"The given process is not accessible.") else THROW(STATUS_NOT_FOUND, L"The given process does not exist."); } // if WOW64 is not available then target must be 32-bit pIsWow64Process = (IsWow64Process_PROC*)GetProcAddress(hKernel32, "IsWow64Process"); #ifdef _M_X64 // if the target is not WOW64, then it is 64-bit if(!pIsWow64Process(hProc, &IsTarget64Bit)) THROW(STATUS_INTERNAL_ERROR, L"Unable to detect wether target process is 64-bit or not."); IsTarget64Bit = !IsTarget64Bit; #else IsTarget64Bit = FALSE; if(pIsWow64Process != NULL) { // check if we are running on a 32-bit OS pGetNativeSystemInfo = (GetNativeSystemInfo_PROC*)GetProcAddress(hKernel32, "GetNativeSystemInfo"); if(pGetNativeSystemInfo != NULL) { pGetNativeSystemInfo(&SysInfo); if(SysInfo.wProcessorArchitecture != PROCESSOR_ARCHITECTURE_INTEL) { // if not, then and only then a 32-bit process will be marked as WOW64 process! if(!pIsWow64Process(hProc, &IsTarget64Bit)) THROW(STATUS_INTERNAL_ERROR, L"Unable to detect wether target process is 64-bit or not."); IsTarget64Bit = !IsTarget64Bit; } } } #endif *OutResult = IsTarget64Bit; RETURN(STATUS_SUCCESS); THROW_OUTRO: FINALLY_OUTRO: { if(hProc != NULL) CloseHandle(hProc); return NtStatus; } }
void injectPID(DWORD pid) { HANDLE h; CHK(0 != (h = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid))); injectProcess(h); CHK(CloseHandle(h)); }
EASYHOOK_NT_EXPORT RhCreateAndInject( WCHAR* InEXEPath, WCHAR* InCommandLine, ULONG InProcessCreationFlags, ULONG InInjectionOptions, WCHAR* InLibraryPath_x86, WCHAR* InLibraryPath_x64, PVOID InPassThruBuffer, ULONG InPassThruSize, ULONG* OutProcessId) { /* Description: Creates a suspended process and immediately injects the user library. This is done BEFORE any of the usual process initialization is called. When the injection is made, NO thread has actually executed any instruction so far... It is just like your library entry point is the first thing executed in such a process and you can allow the original execution to take place by calling RhWakeUpProcess() in the injected library. But even that is no requirement for the process to work... Parameters: - InEXEPath A relative or absolute path to the EXE file of the process being created. - InCommandLine Optional command line parameters passed to the newly created process. - InProcessCreationFlags Custom process creation flags. - InInjectionOptions All flags can be combined. EASYHOOK_INJECT_DEFAULT: No special behavior. The given libraries are expected to be unmanaged DLLs. Further they should export an entry point named "NativeInjectionEntryPoint" (in case of 64-bit) and "_NativeInjectionEntryPoint@4" (in case of 32-bit). The expected entry point signature is REMOTE_ENTRY_POINT. EASYHOOK_INJECT_MANAGED: The given user library is a NET assembly. Further they should export a class named "EasyHook.InjectionLoader" with a static method named "Main". The signature of this method is expected to be "int (String)". Please refer to the managed injection loader of EasyHook for more information about writing such managed entry points. EASYHOOK_INJECT_STEALTH: Uses the experimental stealth thread creation. If it fails you may try it with default settings. - InLibraryPath_x86 A relative or absolute path to the 32-bit version of the user library being injected. If you don't want to inject into 32-Bit processes, you may set this parameter to NULL. - InLibraryPath_x64 A relative or absolute path to the 64-bit version of the user library being injected. If you don't want to inject into 64-Bit processes, you may set this parameter to NULL. - InPassThruBuffer An optional buffer containg data to be passed to the injection entry point. Such data is available in both, the managed and unmanaged user library entry points. Set to NULL if no used. - InPassThruSize Specifies the size in bytes of the pass thru data. If "InPassThruBuffer" is NULL, this parameter shall also be zero. - OutProcessId Receives the PID of the newly created process. */ ULONG ProcessId = 0; ULONG ThreadId = 0; HANDLE hProcess = NULL; NTSTATUS NtStatus; if(!IsValidPointer(OutProcessId, sizeof(ULONG))) THROW(STATUS_INVALID_PARAMETER_8, L"The given process ID storage is invalid."); // all other parameters are validate by called APIs... FORCE(RtlCreateSuspendedProcess(InEXEPath, InCommandLine, InProcessCreationFlags, &ProcessId, &ThreadId)); // inject library FORCE(RhInjectLibrary( ProcessId, ThreadId, InInjectionOptions, InLibraryPath_x86, InLibraryPath_x64, InPassThruBuffer, InPassThruSize)); *OutProcessId = ProcessId; RETURN; THROW_OUTRO: { if(ProcessId != 0) { hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessId); TerminateProcess(hProcess, 0); CloseHandle(hProcess); } } FINALLY_OUTRO: return NtStatus; }
int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) { HANDLE hProcess; HANDLE hToken; TOKEN_PRIVILEGES tkp; HANDLE hMutex; /* check wether we're already running or not */ hMutex = CreateMutexW(NULL, TRUE, L"taskmgrros"); if (hMutex && GetLastError() == ERROR_ALREADY_EXISTS) { /* Restore existing taskmanager and bring window to front */ /* Relies on the fact that the application title string and window title are the same */ HWND hTaskMgr; TCHAR szTaskmgr[128]; LoadString(hInst, IDS_APP_TITLE, szTaskmgr, sizeof(szTaskmgr)/sizeof(TCHAR)); hTaskMgr = FindWindow(NULL, szTaskmgr); if (hTaskMgr != NULL) { SendMessage(hTaskMgr, WM_SYSCOMMAND, SC_RESTORE, 0); SetForegroundWindow(hTaskMgr); } return 0; } else if (!hMutex) { return 1; } /* Initialize global variables */ hInst = hInstance; /* Change our priority class to HIGH */ hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId()); SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS); CloseHandle(hProcess); /* Now lets get the SE_DEBUG_NAME privilege * so that we can debug processes */ /* Get a token for this process. */ if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) { /* Get the LUID for the debug privilege. */ LookupPrivilegeValueW(NULL, SE_DEBUG_NAME, &tkp.Privileges[0].Luid); tkp.PrivilegeCount = 1; /* one privilege to set */ tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; /* Get the debug privilege for this process. */ AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0); CloseHandle(hToken); } /* Load our settings from the registry */ LoadSettings(); /* Initialize perf data */ if (!PerfDataInitialize()) { return -1; } DialogBoxW(hInst, (LPCWSTR)IDD_TASKMGR_DIALOG, NULL, TaskManagerWndProc); /* Save our settings to the registry */ SaveSettings(); PerfDataUninitialize(); return 0; }
NTSTATUS kuhl_m_sekurlsa_acquireLSA() { NTSTATUS status = STATUS_SUCCESS; KULL_M_MEMORY_TYPE Type; HANDLE hData = NULL; DWORD pid; PMINIDUMP_SYSTEM_INFO pInfos; DWORD processRights = PROCESS_VM_READ | PROCESS_QUERY_INFORMATION | PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_VM_WRITE; BOOL isError = FALSE; if(!cLsass.hLsassMem) { status = STATUS_NOT_FOUND; if(NT_SUCCESS(lsassLocalHelper->initLocalLib())) { if(pMinidumpName) { Type = KULL_M_MEMORY_TYPE_PROCESS_DMP; kprintf(L"Opening : \'%s\' file for minidump...\n", pMinidumpName); hData = CreateFile(pMinidumpName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); } else { Type = KULL_M_MEMORY_TYPE_PROCESS; if(kull_m_process_getProcessIdForName(L"lsass.exe", &pid)) hData = OpenProcess(processRights, FALSE, pid); else PRINT_ERROR(L"LSASS process not found (?)\n"); } if(hData && hData != INVALID_HANDLE_VALUE) { if(kull_m_memory_open(Type, hData, &cLsass.hLsassMem)) { if(Type == KULL_M_MEMORY_TYPE_PROCESS_DMP) { if(pInfos = (PMINIDUMP_SYSTEM_INFO) kull_m_minidump_stream(cLsass.hLsassMem->pHandleProcessDmp->hMinidump, SystemInfoStream)) { cLsass.osContext.MajorVersion = pInfos->MajorVersion; cLsass.osContext.MinorVersion = pInfos->MinorVersion; cLsass.osContext.BuildNumber = pInfos->BuildNumber; if(isError = (cLsass.osContext.MajorVersion != MIMIKATZ_NT_MAJOR_VERSION)) PRINT_ERROR(L"Minidump pInfos->MajorVersion (%u) != MIMIKATZ_NT_MAJOR_VERSION (%u)\n", pInfos->MajorVersion, MIMIKATZ_NT_MAJOR_VERSION); #ifdef _M_X64 else if(isError = (pInfos->ProcessorArchitecture != PROCESSOR_ARCHITECTURE_AMD64)) PRINT_ERROR(L"Minidump pInfos->ProcessorArchitecture (%u) != PROCESSOR_ARCHITECTURE_AMD64 (%u)\n", pInfos->ProcessorArchitecture, PROCESSOR_ARCHITECTURE_AMD64); #elif defined _M_IX86 else if(isError = (pInfos->ProcessorArchitecture != PROCESSOR_ARCHITECTURE_INTEL)) PRINT_ERROR(L"Minidump pInfos->ProcessorArchitecture (%u) != PROCESSOR_ARCHITECTURE_INTEL (%u)\n", pInfos->ProcessorArchitecture, PROCESSOR_ARCHITECTURE_INTEL); #endif } else { isError = TRUE; PRINT_ERROR(L"Minidump without SystemInfoStream (?)\n"); } } else { cLsass.osContext.MajorVersion = MIMIKATZ_NT_MAJOR_VERSION; cLsass.osContext.MinorVersion = MIMIKATZ_NT_MINOR_VERSION; cLsass.osContext.BuildNumber = MIMIKATZ_NT_BUILD_NUMBER; } if(!isError) { kuhl_m_sekurlsa_livessp_package.isValid = (cLsass.osContext.BuildNumber >= KULL_M_WIN_MIN_BUILD_8); kuhl_m_sekurlsa_tspkg_package.isValid = (cLsass.osContext.MajorVersion >= 6) || (cLsass.osContext.MinorVersion < 2); if(NT_SUCCESS(kull_m_process_getVeryBasicModuleInformations(cLsass.hLsassMem, kuhl_m_sekurlsa_findlibs, NULL)) && kuhl_m_sekurlsa_msv_package.Module.isPresent) { kuhl_m_sekurlsa_dpapi_lsa_package.Module = kuhl_m_sekurlsa_msv_package.Module; if(kuhl_m_sekurlsa_utils_search(&cLsass, &kuhl_m_sekurlsa_msv_package.Module)) { status = lsassLocalHelper->AcquireKeys(&cLsass, &lsassPackages[0]->Module.Informations); if(!NT_SUCCESS(status)) PRINT_ERROR(L"Key import\n"); } else PRINT_ERROR(L"Logon list\n"); } else PRINT_ERROR(L"Modules informations\n"); } } else PRINT_ERROR(L"Memory opening\n"); } else PRINT_ERROR_AUTO(L"Handle on memory"); if(!NT_SUCCESS(status)) { cLsass.hLsassMem = kull_m_memory_close(cLsass.hLsassMem); CloseHandle(hData); } } else PRINT_ERROR(L"Local LSA library failed\n"); } return status; }