Exemple #1
0
static BOOL UnloadHive(HWND hWnd)
{
    WCHAR Caption[128];
    LPCWSTR pszKeyPath;
    HKEY hRootKey;
    LONG regUnloadResult;

    /* get the item key to unload */
    pszKeyPath = GetItemPath(g_pChildWnd->hTreeWnd, 0, &hRootKey);
    /* load and set the caption and flags for dialog */
    LoadStringW(hInst, IDS_UNLOAD_HIVE, Caption, COUNT_OF(Caption));

    /* Enable the 'restore' privilege, unload the hive, disable the privilege */
    EnablePrivilege(SE_RESTORE_NAME, NULL, TRUE);
    regUnloadResult = RegUnLoadKeyW(hRootKey, pszKeyPath);
    EnablePrivilege(SE_RESTORE_NAME, NULL, FALSE);

    if(regUnloadResult == ERROR_SUCCESS)
    {
        /* refresh tree and list views */
        RefreshTreeView(g_pChildWnd->hTreeWnd);
        pszKeyPath = GetItemPath(g_pChildWnd->hTreeWnd, 0, &hRootKey);
        RefreshListView(g_pChildWnd->hListWnd, hRootKey, pszKeyPath);
    }
    else
    {
        ErrorMessageBox(hWnd, Caption, regUnloadResult);
        return FALSE;
    }
    return TRUE;
}
Exemple #2
0
static BOOL LoadHive(HWND hWnd)
{
    OPENFILENAME ofn;
    WCHAR Caption[128];
    LPCWSTR pszKeyPath;
    WCHAR xPath[LOADHIVE_KEYNAMELENGTH];
    HKEY hRootKey;
    WCHAR Filter[1024];
    FILTERPAIR filter;
    /* get the item key to load the hive in */
    pszKeyPath = GetItemPath(g_pChildWnd->hTreeWnd, 0, &hRootKey);
    /* initialize the "open file" dialog */
    InitOpenFileName(hWnd, &ofn);
    /* build the "All Files" filter up */
    filter.DisplayID = IDS_FLT_ALLFILES;
    filter.FilterID = IDS_FLT_ALLFILES_FLT;
    BuildFilterStrings(Filter, &filter, 1);
    ofn.lpstrFilter = Filter;
    /* load and set the caption and flags for dialog */
    LoadStringW(hInst, IDS_LOAD_HIVE, Caption, COUNT_OF(Caption));
    ofn.lpstrTitle = Caption;
    ofn.Flags |= OFN_ENABLESIZING;
    /*    ofn.lCustData = ;*/
    /* now load the hive */
    if (GetOpenFileName(&ofn))
    {
        if (DialogBoxParamW(hInst, MAKEINTRESOURCEW(IDD_LOADHIVE), hWnd,
                            &LoadHive_KeyNameInHookProc, (LPARAM)xPath))
        {
            LONG regLoadResult;

            /* Enable the 'restore' privilege, load the hive, disable the privilege */
            EnablePrivilege(SE_RESTORE_NAME, NULL, TRUE);
            regLoadResult = RegLoadKeyW(hRootKey, xPath, ofn.lpstrFile);
            EnablePrivilege(SE_RESTORE_NAME, NULL, FALSE);

            if(regLoadResult == ERROR_SUCCESS)
            {
                /* refresh tree and list views */
                RefreshTreeView(g_pChildWnd->hTreeWnd);
                pszKeyPath = GetItemPath(g_pChildWnd->hTreeWnd, 0, &hRootKey);
                RefreshListView(g_pChildWnd->hListWnd, hRootKey, pszKeyPath);
            }
            else
            {
                ErrorMessageBox(hWnd, Caption, regLoadResult);
                return FALSE;
            }
        }
    }
    else
    {
        CheckCommDlgError(hWnd);
    }
    return TRUE;
}
int _tmain(int argc, _TCHAR* argv[])
{
	HMODULE hinstLib=LoadLibrary(L"ntdll.dll");

	if (hinstLib == NULL) 
		goto END;

	myZwSystemDebugControl = (_MY_ZwSystemDebugControl)GetProcAddress(hinstLib, "ZwSystemDebugControl");
	if (!myZwSystemDebugControl)
	{
		printf("GetProcAddress ZwSystemDebugControl - error!\n");
		goto END;
	}
	
	DBGKD_GET_INTERNAL_BREAKPOINT bp[20];
	ULONG n;
	EnablePrivilege(SE_DEBUG_NAME);
	NTSTATUS status = myZwSystemDebugControl(DebugGetTraceInformation,
		0, 0, bp, sizeof bp, &n);
	
	if ( NT_SUCCESS(status) )
		printf("ZwSystemDebugControl succeeded!\n");
	else
		printf("ZwSystemDebugControl failed - 0x%08X\n", status );
	
END:
	if (hinstLib)
		FreeLibrary(hinstLib); 

	return 0;
	
}
Exemple #4
0
inline void EnableAllPrivileges()
{
    for (auto i = SE_MIN_WELL_KNOWN_PRIVILEGE; i <= SE_MAX_WELL_KNOWN_PRIVILEGE; ++i)
    {
        EnablePrivilege(i);
    }
}
bool HookProcess(LPCWSTR lpAppName)
{
	bool bRet = false;

	EnablePrivilege(SE_DEBUG_NAME);
	DWORD Pid = FindSpecificProcess(lpAppName);
	if (!Pid)
	{
		LogMsg("Can not find specific process: %S\n", lpAppName);
		return false;
	}

	HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, Pid);
	if(NULL == hProcess)
	{
		LogMsg("Open %S failed %d\n", lpAppName, GetLastError());
		return false;
	}
	//TODO: best to make sure winlogon.exe not loaded Win32HookExplorerDll.dll before inject.
	//Sometimes we restart MMRService in service management, in this case there is no need to inject.
	if (bRet = InjectThread(hProcess))
	{
		LogMsg("Inject %S success\n", lpAppName);
	}
	CloseHandle(hProcess);

	return bRet;
}
Exemple #6
0
void updatdChess() //更新棋盘数据至 chessdata
{
	if (!EnablePrivilege ())
	{
		MyMessageBox ("EnablePrivilege", GetLastError ());
	}

	//获取窗口句柄
	HWND gameh=::FindWindowA(NULL,g_ChessInfo.caption);
	
	//获取窗口进程ID
	DWORD processid;
	::GetWindowThreadProcessId(gameh,&processid);
	
	//打开指定进程
	HANDLE processH=::OpenProcess(PROCESS_ALL_ACCESS,false,processid);
	
	//读指定进程 内存数据
    DWORD byread;
	//LPCVOID pbase=(LPCVOID)0x0012A508;  //棋盘数据基址
	LPVOID  nbuffer=(LPVOID)&chessdata; //存放棋盘数据

	DWORD dwOldProtect;
	if(!VirtualProtectEx (processH , g_ChessInfo.lpQPBase, sizeof (chessdata), PAGE_READWRITE, &dwOldProtect)){
		MyMessageBox ("VirtualProtectEx", GetLastError ());
	}

	::ReadProcessMemory(processH,g_ChessInfo.lpQPBase,nbuffer,11*19,&byread);

	DWORD dwNewProtect;
	if(!VirtualProtectEx (processH, g_ChessInfo.lpQPBase, sizeof (chessdata), dwOldProtect, &dwNewProtect)){
		MyMessageBox ("VirtualProtectEx2", GetLastError ());
	}
}
int APCCallbacktoInject(_TCHAR* DLLName, DWORD ProcessID)
{
	//提升进程权限
	if (int rtMsg = EnablePrivilege() != 0)
		return rtMsg;
	HANDLE hOProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessID);
	if (hOProcess != NULL)
	{
		_TCHAR* pLibRemote = (_TCHAR*)VirtualAllocEx(hOProcess, NULL, 2 * wcslen(DLLName) + 1, MEM_COMMIT, PAGE_READWRITE);
		if (pLibRemote != NULL)
		{
			if (!WriteProcessMemory(hOProcess, pLibRemote, DLLName, 2 * wcslen(DLLName) + 1, NULL))
			{
				PAPCFUNC pAPCFuncAddr = (PAPCFUNC)GetProcAddress(GetModuleHandle(L"Kernel32"), "LoadLibraryW");
				DWORD dTid = GetTIDbyPID(ProcessID);
				if (dTid != NULL && pAPCFuncAddr != NULL)
				{
					HANDLE hoThread = OpenThread(THREAD_ALL_ACCESS, FALSE, dTid);
					if (!QueueUserAPC(pAPCFuncAddr, hoThread, (ULONG_PTR)pLibRemote))
					{
						wprintf(L"%s\n", L"Inject sucessful!");
					}
				}
			}
		}
	}
	return 0;
}
Exemple #8
0
/****************************************************
 * Unload injected library from the remote process. *
 ****************************************************/
int EjectDll()
{
    HANDLE	hThread;
    HANDLE	hProcess;
    DWORD	dwPID;
    DWORD	dwRetFreeLibrary;

    // Enable DEBUG privilege
    if (!EnablePrivilege(SE_DEBUG_NAME, TRUE))
        return 0;

    // Get remote process id
    dwPID = GetPIDFromName(szProcessName);
    if (dwPID == -1)
        return 0;

    // Open remote process
    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID);
    if (hProcess == NULL)
        return 0;

    // Unload the DLL from the remote process
    // (via CreateRemoteThread & FreeLibrary)
    hThread = CreateRemoteThread(hProcess,
                                 NULL,
                                 0,
                                 (LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle("Kernel32"), "FreeLibrary"),
                                 (void*)hLibModule,
                                 0,
                                 NULL );
    // Failed to unload
    if (hThread == NULL)
        return 0;

    // Wait for FreeLibrary() to finish and get return code
    WaitForSingleObject(hThread, INFINITE);
    GetExitCodeThread(hThread, &dwRetFreeLibrary);
    CloseHandle(hThread);
    CloseHandle(hProcess);

    // Disable DEBUG privilege
    EnablePrivilege(SE_DEBUG_NAME, FALSE);

    return (dwRetFreeLibrary);
}
//参数是要弹出的盘符如:G,F
bool CUsbHelper::UnInstallUsb(char szDriveName) 
{
	DWORD accessMode = 0, shareMode = 0;
	HANDLE   hDevice; 
	ULONG returned = 0,bResult = 0;
	DWORD   dwError;  

	shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;  // default
	accessMode = GENERIC_WRITE | GENERIC_READ;       // default

	if (szDriveName == 0)
	{
		return FALSE;
	}

	CString vol_string = _T("\\\\.\\G:");
	vol_string.SetAt(4, szDriveName);
	hDevice = CreateFile(vol_string,
		accessMode,   shareMode,     NULL, OPEN_EXISTING, 0,       NULL);

	if (hDevice == INVALID_HANDLE_VALUE)
	{
		CString debugInfo;
		dwError   =   GetLastError();    
		debugInfo.Format(_T("error = %d "), dwError);
		TRACE(_T("IOCTL_STORAGE_EJECT_MEDIA  errorcode = %d \n"), dwError);
		return FALSE;
	}

	//弹出U盘的具体命令。
	bResult   =   DeviceIoControl(hDevice, IOCTL_STORAGE_EJECT_MEDIA, 
		NULL, 0, NULL, 0,&returned,      NULL);

	if (!bResult)   //   IOCTL   failed     //经实验,有时虽然失败了,U盘还是能弹出
	{  
		CString debugInfo;
		dwError   =   GetLastError();    
		debugInfo.Format(_T("error = %d "), dwError);
		TRACE(_T("IOCTL_STORAGE_EJECT_MEDIA  errorcode = %d \n"), dwError);
	} 

	bResult   =   CloseHandle(hDevice);    
	if   (!bResult)    
	{    
		CString debugInfo;
		dwError   =   GetLastError();    
		debugInfo.Format(_T("error = %d "), dwError);
		TRACE(_T("IOCTL_STORAGE_EJECT_MEDIA  errorcode = %d \n"), dwError);
		return FALSE;
	} 
	
	EnablePrivilege(SE_DEBUG_NAME, TRUE);
	ClearUsbRegKey(szDriveName);

	return TRUE;
}
 PrivilegeEnabler::PrivilegeEnabler(std::vector<std::wstring> const & privileges)
 {
     _areAllPrivilegesEnabled = true;
     for (auto i = privileges.begin(); i != privileges.end(); ++i)
     {
         if (EnablePrivilege((*i).c_str(), TRUE) == FALSE)
         {
             _areAllPrivilegesEnabled = false;
         }
     }
 }
BOOL _RefCountedPriviledgeHolder::EnablePrivilegeForCurrentProcess(LPCTSTR szPrivName, BOOL fEnable) 
{
    HANDLE hToken;
    BOOL result = FALSE; 

    if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken)) 
    {
        result = EnablePrivilege(hToken, szPrivName, fEnable);
        CloseHandle(hToken);
    }

    return result;
}
Exemple #12
0
int _tmain(int argc, _TCHAR* argv[])
{
	// 提升权限
	EnablePrivilege(TRUE);

	// 打开进程
	HWND hwnd = FindWindow(_T("BASE"), _T("搶曽嵁庫揱丂乣 Legacy of Lunatic Kingdom. ver 1.00b")); // 日文编码就是这样...
	DWORD pid;
	GetWindowThreadProcessId(hwnd, &pid);
	HANDLE process = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
	if (process == NULL)
	{
		printf("打开进程失败,错误代码:%u\n", GetLastError());
		return 1;
	}

	// 要将TH15Render.dll放在本程序当前目录下
	TCHAR dllPath[MAX_PATH]; // 要用绝对路径
	GetCurrentDirectory(_countof(dllPath), dllPath);
	_tcscat_s(dllPath, _T("\\TH15Render.dll"));


	// 注入DLL
	HMODULE remoteModule = InjectDll(process, dllPath);
	if (remoteModule == NULL)
	{
		CloseHandle(process);
		return 2;
	}

	// 暂停
	printf("按回车卸载DLL\n");
	getchar();

	// 卸载DLL
	if (!FreeRemoteDll(process, remoteModule))
	{
		CloseHandle(process);
		return 3;
	}


	// 关闭进程
	CloseHandle(process);

	return 0;
}
Exemple #13
0
void CTask::SendTask(SOCKET sock)
{
	MSGINFO_S msg;
	TASK task;
	memset(&msg, 0, sizeof(MSGINFO_S));
	msg.Msg_id = TASKLIST;

	DWORD needed;
	HANDLE hProcess;
	HMODULE hModule;
	wchar_t path[260] = _T("");
	HANDLE hToken;

	HANDLE  hProcessSnap = NULL;
	PROCESSENTRY32 pe32;
	pe32.dwSize = sizeof(PROCESSENTRY32);
	hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

	if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken))
	{
		EnablePrivilege(hToken,SE_DEBUG_NAME); //尝试提升权限
		Process32First(hProcessSnap, &pe32);
		do
		{
			memset(&task, 0, sizeof(TASK));
			memset(msg.context, 0, sizeof(msg.context));
			hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pe32.th32ProcessID);
			if (hProcess)
			{
				EnumProcessModules(hProcess, &hModule, sizeof(hModule), &needed);
				GetModuleFileNameExW(hProcess, hModule, path, sizeof(path));
				wcscpy_s(task.TaskPath, _countof(path), path);
			}
			wcscpy_s(task.TaskName, _countof(pe32.szExeFile), pe32.szExeFile); //进程名
			task.TaskID = pe32.th32ProcessID;
			task.flag = false;
			memcpy(msg.context, &task, sizeof(TASK));
			m_sock.MySend(sock, (char*)&msg, sizeof(MSGINFO_S));
		} while (Process32Next(hProcessSnap, &pe32));
	}
	CloseHandle(hProcess);
	CloseHandle(hModule);

	task.flag = true;
	memcpy(msg.context, &task, sizeof(TASK));
	m_sock.MySend(sock, (char*)&msg, sizeof(MSGINFO_S));
}
Exemple #14
0
void GrantAllPrivs(HANDLE h)
{
	Log(L"DEBUG: GrantAllPrivs", false);
	CString privs = L"SeCreateTokenPrivilege,SeAssignPrimaryTokenPrivilege,SeLockMemoryPrivilege,SeIncreaseQuotaPrivilege,SeMachineAccountPrivilege,"
					L"SeTcbPrivilege,SeSecurityPrivilege,SeTakeOwnershipPrivilege,SeLoadDriverPrivilege,SeSystemProfilePrivilege,SeSystemtimePrivilege,SeProfileSingleProcessPrivilege,"
					L"SeIncreaseBasePriorityPrivilege,SeCreatePagefilePrivilege,SeCreatePermanentPrivilege,SeBackupPrivilege,SeRestorePrivilege,SeShutdownPrivilege,SeDebugPrivilege,"
					L"SeAuditPrivilege,SeSystemEnvironmentPrivilege,SeChangeNotifyPrivilege,SeRemoteShutdownPrivilege,SeUndockPrivilege,SeSyncAgentPrivilege,SeEnableDelegationPrivilege,"
					L"SeManageVolumePrivilege,SeImpersonatePrivilege,SeCreateGlobalPrivilege,SeTrustedCredManAccessPrivilege,SeRelabelPrivilege,SeIncreaseWorkingSetPrivilege,"
					L"SeTimeZonePrivilege,SeCreateSymbolicLinkPrivilege";

	wchar_t* pC = wcstok(privs.LockBuffer(), L",");
	while(NULL != pC)
	{
		EnablePrivilege(pC, h); //needed to call CreateProcessAsUser
		pC = wcstok(NULL, L",");
	}
}
Exemple #15
0
int isModuleUsedByProcess(DWORD dwPID, LPCTSTR szLibrary, bool *found)
{
	int iReturnCode = DIAGLIB_OK;

    HANDLE hModuleSnap = INVALID_HANDLE_VALUE;
    MODULEENTRY32 me32;
	*found=false;

    EnablePrivilege(SE_DEBUG_NAME);
	if(INVALID_HANDLE_VALUE == ( hModuleSnap=CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwPID)))
	{
		LOG_LASTERROR(L"CreateToolhelp32Snapshot failed");
		return RETURN_LOG_INTERNAL_ERROR;
	}

	me32.dwSize = sizeof(MODULEENTRY32);

    if (!Module32First (hModuleSnap, &me32))
    {
 		LOG_LASTERROR(L"Module32First failed");
		if(!CloseHandle( hModuleSnap ))
		{
			LOG_LASTERROR(L"CloseHandle failed");
		}
		return RETURN_LOG_INTERNAL_ERROR;
    }

    do
    {
        if (!lstrcmpi(szLibrary, me32.szModule))
        {
			*found=true;
            break;
        }

    } while (Module32Next(hModuleSnap, &me32));

	if(!CloseHandle( hModuleSnap ))
	{
		LOG_LASTERROR(L"CloseHandle failed");
	}

    return iReturnCode;
}
/*************************************
* int WinMain(
*			HINSTANCE hInstance,
*			HINSTANCE hPrevInstance,
*			LPSTR lpCmdLine,
*			int nCmdShow
*			)
**************************************/
int WinMain(
			HINSTANCE hInstance,
			HINSTANCE hPrevInstance,
			LPSTR lpCmdLine,
			int nCmdShow
			)
{
	DWORD dwPID;
	// 提权,获取SE_DEBUG_NAME权限,
	// 可以在其他进程的内存空间中写入、创建线程
	if(0!=EnablePrivilege (SE_DEBUG_NAME))
		return 0;
	// 获取目录进程的PID
	if(!GetProcessIdByName("explorer.exe",&dwPID))
		return 0;
	// 通过创建远程线程加载DLL
	// 将msg.dll放置在系统目录下
	if(!LoadRometeDll(dwPID,"msg.dll"))
		return 0;
	return 1;
}
int RemoteToInject(_TCHAR* DLLName, DWORD ProcessID)
{
	//DWORD ThreadId = GetTIDbyPID(ProcessID);
	//进程提取
	if (int rt = EnablePrivilege() != 0)
		return rt;
	HANDLE hOprocess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessID);
	if (hOprocess != NULL)
	{
		_TCHAR* pLibFileRemote = (_TCHAR*)VirtualAllocEx(hOprocess, NULL, 2 * wcslen(DLLName) + 1, MEM_COMMIT, PAGE_READWRITE);
		if (pLibFileRemote != NULL)
		{
			if (!WriteProcessMemory(hOprocess, (void*)pLibFileRemote, DLLName, 2 * wcslen(DLLName) + 1, NULL))
				return GetLastError();

			//Get LoadLibraryW Address
			PTHREAD_START_ROUTINE pfnStartAddr = (PTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle(L"Kernel32"), "LoadLibraryW");
			if (pfnStartAddr != NULL)
			{
				HANDLE hRemote = CreateRemoteThread(hOprocess, NULL, 0, pfnStartAddr, (PVOID)pLibFileRemote, 0, NULL);
				if (hRemote != NULL)
				{
					wprintf(L"%s\n", L"Inject sucessful!");
					WaitForSingleObject(hRemote, INFINITE);
					wprintf(L"%s\n", L"The inject was killed!");
					if (!VirtualFreeEx(hOprocess, pLibFileRemote, 0, MEM_RELEASE))
						return GetLastError();
				}
				else
					return GetLastError();
			}
		}
		else
			return GetLastError();
	}
	else
		return GetLastError();
	return 0;
}
Exemple #18
0
bool isModuleUsedByProcess(DWORD dwPID, LPCTSTR szLibrary)
{
    HANDLE hModuleSnap = INVALID_HANDLE_VALUE;
    MODULEENTRY32 me32;
	bool bFound=false;

    EnablePrivilege(SE_DEBUG_NAME);
    hModuleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwPID);

    if (hModuleSnap == (HANDLE) - 1)
    {
        return false;
    }

    me32.dwSize = sizeof(MODULEENTRY32);

    if (!Module32First (hModuleSnap, &me32))
    {
        CloseHandle(hModuleSnap);
        return false;
    }

    do
    {
        if (!lstrcmpi(szLibrary, me32.szModule))
        {
			bFound=true;
            break;
        }

    } while (Module32Next(hModuleSnap, &me32));

    CloseHandle(hModuleSnap);

    return bFound;
}
Exemple #19
0
/* Main entry for program */
int wmain(int argc, WCHAR *argv[])
{
    DWORD error = ERROR_SUCCESS;
    struct CommandLineOptions opts;

    if (argc == 1) /* i.e. no commandline arguments given */
    {
        PrintResourceString(IDS_USAGE);
        return EXIT_SUCCESS;
    }

    error = ParseArguments(&opts, argc, argv);
    if (error != ERROR_SUCCESS)
    {
        DisplayError(error);
        return EXIT_FAILURE;
    }

    /* If the user wants to abort a shutdown */
    if (opts.abort)
    {
        /* First, the program has to determine if the shutdown/restart is local
        or remote. This is done since each one requires separate privileges. */
        if (opts.remote_system == NULL)
            EnablePrivilege(SE_SHUTDOWN_NAME, TRUE);
        else
            EnablePrivilege(SE_REMOTE_SHUTDOWN_NAME, TRUE);

        /* Abort the delayed system shutdown specified. */
        if (!AbortSystemShutdownW(opts.remote_system))
        {
            PrintResourceString(IDS_ERROR_ABORT);
            DisplayError(GetLastError());
            return EXIT_FAILURE;
        }
        else
        {
            return EXIT_SUCCESS;
        }
    }

    /*
     * If the user wants to hibernate the computer. Assume
     * that the user wants to wake the computer up from 
     * hibernation and it should not force it on the system.
     */
    if (opts.hibernate)
    {
        if (IsPwrHibernateAllowed())
        {
            EnablePrivilege(SE_SHUTDOWN_NAME, TRUE);
            
            /* The shutdown utility cannot hibernate remote systems */
            if (opts.remote_system != NULL)
            {
                return EXIT_FAILURE;
            }
        
            if (!SetSuspendState(TRUE, FALSE, FALSE))
            {
                PrintResourceString(IDS_ERROR_HIBERNATE);
                DisplayError(GetLastError());
                return EXIT_FAILURE;
            }
            else
            {
                PrintResourceString(IDS_ERROR_HIBERNATE_ENABLED);
                return EXIT_SUCCESS;
            }
        }
        else
        {
            return EXIT_FAILURE;
        }
    }

    /* Both shutdown and restart flags cannot both be true */
    if (opts.shutdown && opts.restart)
    {
        PrintResourceString(IDS_ERROR_SHUTDOWN_REBOOT);
        return EXIT_FAILURE;
    }

    /* Ensure that the timout amount is not too high or a negative number */
    if ((opts.shutdown_delay < 0) || (opts.shutdown_delay > MAX_TIMEOUT))
    {
        PrintResourceString(IDS_ERROR_TIMEOUT, opts.shutdown_delay);
        return EXIT_FAILURE;
    }

    /* If the user wants a GUI environment */
    if (opts.show_gui)
    {
        if (ShutdownGuiMain(opts))
            return EXIT_SUCCESS;
        else
            return EXIT_FAILURE;
    }

    if (opts.logoff && (opts.remote_system == NULL))
    {
        /*
         * NOTE: Sometimes, shutdown and logoff are used together. If the logoff
         * flag is used by itself, then simply logoff. But if used with shutdown,
         * then skip logging off of the computer and eventually go to the action
         * for shutdown.
         */
        if (!opts.shutdown && !opts.restart)
        {
            EnablePrivilege(SE_SHUTDOWN_NAME, TRUE);

            if (ExitWindowsEx(EWX_LOGOFF, opts.reason))
            {
                return EXIT_SUCCESS;
            }
            else
            {
                PrintResourceString(IDS_ERROR_LOGOFF);
                DisplayError(GetLastError());
                return EXIT_FAILURE;
            }
        }
    }

    /*
     * Since both shutting down the system and restarting calls the exact same
     * function, all we need to know is if we wanted to restart or shutdown.
     */
    if (opts.shutdown || opts.restart)
    {
        /*
         * First, the program has to determine if the shutdown/restart is local
         * or remote. This is done since each one requires separate privileges.
         */
        if (opts.remote_system == NULL)
        {
            EnablePrivilege(SE_SHUTDOWN_NAME, TRUE);
        }
        else
        {
            /* TODO: Remote shutdown is not supported yet */
            // EnablePrivilege(SE_REMOTE_SHUTDOWN_NAME, TRUE);
            return EXIT_SUCCESS;
        }

        /**
         ** HACK: When InitiateSystemShutdownExW will become really implemented,
         ** activate this line and delete the other...
         **
        if(!InitiateSystemShutdownExW(opts.remote_system,
                                      opts.message,
                                      opts.shutdown_delay,
                                      opts.force,
                                      opts.restart,
                                      opts.reason))
        ***/
        if (!ExitWindowsEx((opts.shutdown ? EWX_SHUTDOWN : EWX_REBOOT) |
                           (opts.force ? EWX_FORCE : 0),
                           opts.reason))
        {
            /*
             * If there is an error, give the proper output depending
             * on whether the user wanted to shutdown or restart.
             */
            if (opts.restart)
                PrintResourceString(IDS_ERROR_RESTART);
            else
                PrintResourceString(IDS_ERROR_SHUTDOWN);
            
            DisplayError(GetLastError());
            return EXIT_FAILURE;
        }
        else
        {
            return EXIT_SUCCESS;
        }
    }

    return EXIT_SUCCESS;
}
Exemple #20
0
int EjectCode ()
{
    HANDLE		hProcess;				// Remote process handle
    DWORD		*pCodeRemote;			// Address of EjectFunc() in the remote process
    HANDLE		hThread = NULL;			// The handle and ID of the thread executing
    DWORD		dwThreadId = 0;			//   the remote EjectFunc().
    int			nSuccess	= 0;		// EjectFunc() success ?
    DWORD		dwNumBytesCopied = 0;	// Number of bytes written to the remote process.
    DWORD		size;					// Calculated function size (= AfterFunc() - Func())

    // Enable Debug privilege (needed for some processes)
    EnablePrivilege(SE_DEBUG_NAME, TRUE);

    // Remote INDATA and SASWindowProc() must exist
    if (!pDataRemote || !pSASWinProcRemote)
        return 0;

    // Open the process
    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID);
    if (hProcess == NULL)
        return 0;

    // Allocate memory in the remote process and write a copy of EjectFunc() to the allocated memory
    size = (PBYTE)AfterEjectFunc - (PBYTE)EjectFunc;
    pCodeRemote = (PDWORD) VirtualAllocEx(hProcess, 0, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
    if (!pCodeRemote)
    {
        CloseHandle(hProcess);
        return 0;
    }
    if (!WriteProcessMemory(hProcess, pCodeRemote, &EjectFunc, size, &dwNumBytesCopied) || dwNumBytesCopied != size)
    {
        VirtualFreeEx(hProcess, pCodeRemote, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return 0;
    }

    // Start execution of the remote EjectFunc()
    hThread = CreateRemoteThread(hProcess,
                                 NULL,
                                 0,
                                 (LPTHREAD_START_ROUTINE) pCodeRemote,
                                 pDataRemote,
                                 0 ,
                                 &dwThreadId);
    // Failed
    if (!hThread)
    {
        goto END;
    }

    // Wait for EjectFunc() to terminate and get return code
    WaitForSingleObject(hThread, INFINITE);
    GetExitCodeThread(hThread, (PDWORD) &nSuccess);

    // Failed to restore old window procedure ?
    // Then leave INJDATA and the SASWindowProc()
    if (nSuccess == 0)
        goto END;

    // Release memory for remote INJDATA and SASWindowProc()
    if (pDataRemote)
        VirtualFreeEx(hProcess, pDataRemote, 0, MEM_RELEASE);
    if (pSASWinProcRemote)
        VirtualFreeEx(hProcess, pSASWinProcRemote, 0, MEM_RELEASE);
    pDataRemote = NULL;
    pSASWinProcRemote = NULL;

//	MessageBeep(0);		// success

END:
    if (hThread)
        CloseHandle(hThread);

    // Release EjectFunc() memory
    if (pCodeRemote)
        VirtualFreeEx(hProcess, pCodeRemote, 0, MEM_RELEASE);

    CloseHandle(hProcess);

    // Disable the DEBUG privilege
    EnablePrivilege(SE_DEBUG_NAME, FALSE);

    return nSuccess;	// 0=failure; 1=success
}
Exemple #21
0
int InjectCode ()
{
    HANDLE		hProcess = 0;			// Process handle
    HMODULE		hUser32  = 0;			// Handle of user32.dll
    BYTE		*pCodeRemote;			// Address of InjectFunc() in the remote process.
    BYTE		*pGetSASWndRemote;		// Address of GetSASWnd() in the remote process.
    HANDLE		hThread	= 0;			// The handle and ID of the thread executing
    DWORD		dwThreadId = 0;			//   the remote InjectFunc().
    INJDATA		DataLocal;				// INJDATA structure
    BOOL		fUnicode;				// TRUE if remote process is Unicode
    int			nSuccess = 0;			// Subclassing succeded?
    DWORD		dwNumBytesCopied = 0;	// Number of bytes written to the remote process.
    DWORD		size;					// Calculated function size (= AfterFunc() - Func())
    int			SearchSize;				// SASWindowProc() dummy addr. search size
    int			nDummyOffset;			// Offset in SASWindowProc() of dummy addr.
    BOOL		FoundDummyAddr;			// Dummy INJDATA reference found in SASWindowProc() ?
    HWND		hSASWnd;				// Window handle of Winlogon process
    BYTE		*p;

    // Enable Debug privilege (needed for some processes)
    if (!EnablePrivilege(SE_DEBUG_NAME, TRUE))
        return 0;

    // Get handle of "USER32.DLL"
    hUser32 = GetModuleHandle("user32");
    if (!hUser32)
        return 0;

    // Get remote process ID
    PID = GetPIDFromName(szProcessName);
    if (PID == -1)
        return 0;

    // Open remote process
    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID);
    if (!hProcess)
        return 0;

    __try
    {
        // Initialize INJDATA for GetSASWnd() call
        strcpy(DataLocal.szClassName, "SAS Window class");
        strcpy(DataLocal.szWindowName, "SAS window");
        DataLocal.fnFindWindow = (FINDWINDOW) GetProcAddress(hUser32, "FindWindowA");
        if (DataLocal.fnFindWindow == NULL)
            __leave;

        // Allocate memory in the remote process and write a copy of initialized INJDATA into it
        size = sizeof(INJDATA);
        pDataRemote = (PBYTE) VirtualAllocEx(hProcess, 0, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
        if (!pDataRemote)
            __leave;
        if (!WriteProcessMemory(hProcess, pDataRemote, &DataLocal, size, &dwNumBytesCopied) || dwNumBytesCopied != size)
            __leave;

        // Allocate memory in remote process and write a copy of GetSASWnd() into it
        size = (PBYTE)AfterGetSASWnd - (PBYTE)GetSASWnd;
        pGetSASWndRemote = (PBYTE) VirtualAllocEx(hProcess, 0, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
        if (!pGetSASWndRemote)
            __leave;
        if (!WriteProcessMemory(hProcess, pGetSASWndRemote, &GetSASWnd, size, &dwNumBytesCopied) || dwNumBytesCopied != size)
            __leave;

        // Start execution of remote GetSASWnd()
        hThread = CreateRemoteThread(hProcess,
                                     NULL,
                                     0,
                                     (LPTHREAD_START_ROUTINE) pGetSASWndRemote,
                                     pDataRemote,
                                     0 ,
                                     &dwThreadId);
        // Failed
        if (!hThread)
            __leave;

        // Wait for GetSASWnd() to terminate and get return code (SAS Wnd handle)
        WaitForSingleObject(hThread, INFINITE);
        GetExitCodeThread(hThread, (PDWORD) &hSASWnd);

        // Didn't found "SAS window"
        if (!hSASWnd)
            __leave;

        // Cleanup
        VirtualFreeEx(hProcess, pGetSASWndRemote, 0, MEM_RELEASE);
        VirtualFreeEx(hProcess, pDataRemote, 0, MEM_RELEASE);
        pGetSASWndRemote = NULL;
        pDataRemote = NULL;

        // Allocate memory in remote process and write a copy of SASWindowProc() into it
        size = (PBYTE)AfterSASWindowProc - (PBYTE)SASWindowProc;
        pSASWinProcRemote = (PBYTE) VirtualAllocEx(hProcess, 0, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
        if (!pSASWinProcRemote)
            __leave;
        if (!WriteProcessMemory(hProcess, pSASWinProcRemote, &SASWindowProc, size, &dwNumBytesCopied) || dwNumBytesCopied != size)
            __leave;

        // Is remote process unicode ?
        fUnicode = IsWindowUnicode(hSASWnd);

        // Initialize the INJDATA structure
        DataLocal.fnSetWindowLong = (SETWINDOWLONG)  GetProcAddress(hUser32, fUnicode ? "SetWindowLongW" : "SetWindowLongA");
        DataLocal.fnCallWindowProc = (CALLWINDOWPROC) GetProcAddress(hUser32, fUnicode ? "CallWindowProcW": "CallWindowProcA");
        DataLocal.fnSASWndProc = (WNDPROC) pSASWinProcRemote;
        DataLocal.hwnd = hSASWnd;

        if (DataLocal.fnSetWindowLong  == NULL ||
                DataLocal.fnCallWindowProc == NULL)
        {
            __leave;
        }

        // Allocate memory in the remote process and write a copy of initialized INJDATA into it
        size = sizeof(INJDATA);
        pDataRemote = (PBYTE) VirtualAllocEx(hProcess, 0, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
        if (!pDataRemote)
            __leave;
        if (!WriteProcessMemory(hProcess, pDataRemote, &DataLocal, size, &dwNumBytesCopied) || dwNumBytesCopied != size)
            __leave;

        // Change dummy INJDATA address in SASWindowProc() by the real INJDATA pointer
        p = (PBYTE)&SASWindowProc;
        size = (PBYTE)AfterSASWindowProc - (PBYTE)SASWindowProc;
        SearchSize = size - sizeof(DWORD) + 1;
        FoundDummyAddr = FALSE;

        for (; SearchSize > 0; p++, SearchSize--)
        {
            if (*(DWORD *)p == DUMMY_ADDR)	// Found
            {
                nDummyOffset = p - (PBYTE)&SASWindowProc;
                if (!WriteProcessMemory(hProcess, pSASWinProcRemote + nDummyOffset, &pDataRemote, sizeof(pDataRemote), &dwNumBytesCopied) ||
                        dwNumBytesCopied != sizeof(pDataRemote))
                {
                    __leave;
                }
                FoundDummyAddr = TRUE;
                break;
            }
        }

        // Couldn't change the dummy INJDATA addr. by the real addr. in SASWindowProc() !?!
        // Don't execute the remote copy of SASWindowProc() because the pData pointer is invalid !
        if (!FoundDummyAddr)
        {
            __leave;
        }

        // Allocate memory in the remote process and write a copy of InjectFunc() to the allocated memory
        size = (PBYTE)AfterInjectFunc - (PBYTE)InjectFunc;
        pCodeRemote = (PBYTE) VirtualAllocEx(hProcess, 0, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
        if (!pCodeRemote)
            __leave;
        if (!WriteProcessMemory(hProcess, pCodeRemote, &InjectFunc, size, &dwNumBytesCopied) || dwNumBytesCopied != size)
            __leave;

        // Start execution of remote InjectFunc()
        hThread = CreateRemoteThread(hProcess,
                                     NULL,
                                     0,
                                     (LPTHREAD_START_ROUTINE) pCodeRemote,
                                     pDataRemote,
                                     0 ,
                                     &dwThreadId);
        if (!hThread)
            __leave;

        // Wait for InjectFunc() to terminate and get return code
        WaitForSingleObject(hThread, INFINITE);
        GetExitCodeThread(hThread, (PDWORD) &nSuccess);

        // InjectFunc() successfull
//		if (nSuccess)
//			MessageBeep(0);
    }

    __finally
    {
        // Failed ?
        if (!nSuccess)
        {
            // Release memory for INJDATA and SASWindowProc()
            if (pDataRemote)
                VirtualFreeEx(hProcess, pDataRemote, 0, MEM_RELEASE);
            if (pSASWinProcRemote)
                VirtualFreeEx(hProcess, pSASWinProcRemote, 0, MEM_RELEASE);
            pDataRemote = NULL;
            pSASWinProcRemote = NULL;
        }

        // Release remote GetSASWnd()
        if (pGetSASWndRemote)
            VirtualFreeEx(hProcess, pGetSASWndRemote, 0, MEM_RELEASE);

        // Release remote InjectFunc() (no longer needed)
        if (pCodeRemote)
            VirtualFreeEx(hProcess, pCodeRemote, 0, MEM_RELEASE);

        if (hThread)
            CloseHandle(hThread);

    }

    CloseHandle(hProcess);

    // Disable the DEBUG privilege
    EnablePrivilege(SE_DEBUG_NAME, FALSE);

    return nSuccess;	// 0=failure; 1=success
}
Exemple #22
0
//
//	Create a primary access token for specified user account
//
HANDLE CreateToken(LPCTSTR szUserName)
{
	SID_IDENTIFIER_AUTHORITY	nt   = SECURITY_NT_AUTHORITY;
	SECURITY_QUALITY_OF_SERVICE	sqos = { sizeof(sqos), SecurityAnonymous, SECURITY_STATIC_TRACKING, FALSE };

	HANDLE				hToken;
	PSID				sid;
	TOKEN_USER			user;

	LUID				authid	= SYSTEM_LUID;
	OBJECT_ATTRIBUTES	oa		= { sizeof(oa), 0, 0, 0, 0, &sqos };
	TOKEN_SOURCE		source	= {{'*', '*', 'A', 'N', 'O', 'N', '*', '*'}, {0, 0}};
	HANDLE				hToken2 = 0;
	PTOKEN_STATISTICS	stats;

	PVOID				tokarr[5];
	int					i;
	DWORD				status;

	// Get address of Nt/ZwCreateToken from NTDLL.DLL
	ZwCreateToken         = (PVOID)GetProcAddress(GetModuleHandle("ntdll.dll"), "ZwCreateToken");
	RtlNtStatusToDosError = (PVOID)GetProcAddress(GetModuleHandle("ntdll.dll"), "RtlNtStatusToDosError");

	if(ZwCreateToken == 0 || RtlNtStatusToDosError == 0)
		return 0;

	// Must have SeCreateToken privilege
	if(!EnablePrivilege(SE_CREATE_TOKEN_NAME, TRUE)){
		DBG("EnablePrivilege failed\n");
	}
	

	// Use an existing process token as our basic for a new token
	if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_QUERY_SOURCE, &hToken))
		return 0;
	
	// Convert username to a SID
	if((sid = GetUserSid(szUserName)) == 0)
	{
		CloseHandle(hToken);
		return 0;
	}

	user.User.Attributes	= 0;
	user.User.Sid			= sid;

	if(!AllocateLocallyUniqueId(&source.SourceIdentifier))
	{
		free(sid);
		CloseHandle(hToken);
		return 0;
	}

	if(!GetTokenInfo(hToken, TokenStatistics, &stats))
	{
		free(sid);
		CloseHandle(hToken);
		return 0;
	}
	

	//
	//	Undocumented ZwCreateToken service: will not work for us
	//  under WIN2003, will need to do this from WINLOGON process in future?
	//
	status = ZwCreateToken(&hToken2, TOKEN_ALL_ACCESS, &oa, TokenPrimary,
		(PLUID)&authid, 
		(PLARGE_INTEGER)&stats->ExpirationTime,
		&user,
		(PTOKEN_GROUPS)			GetTokenInfo(hToken, TokenGroups,		&tokarr[0]),
		(PTOKEN_PRIVILEGES)		GetTokenInfo(hToken, TokenPrivileges,	&tokarr[1]),
		(PTOKEN_OWNER)			GetTokenInfo(hToken, TokenOwner,		&tokarr[2]),
		(PTOKEN_PRIMARY_GROUP)	GetTokenInfo(hToken, TokenPrimaryGroup, &tokarr[3]),
		(PTOKEN_DEFAULT_DACL)	GetTokenInfo(hToken, TokenDefaultDacl,	&tokarr[4]),
		&source);

	for(i = 0; i < 5; i++)
		free(tokarr[i]);

	free(stats);
	free(sid);

	CloseHandle(hToken);

	SetLastError(RtlNtStatusToDosError(status));

	return hToken2;
}
Exemple #23
0
BOOL ExportRegistryFile(HWND hWnd)
{
    BOOL bRet = FALSE;
    OPENFILENAME ofn;
    WCHAR ExportKeyPath[_MAX_PATH] = {0};
    WCHAR Caption[128], szTitle[512], szText[512];
    HKEY hKeyRoot;
    LPCWSTR pszKeyPath;

    /* Figure out which key path we are exporting */
    pszKeyPath = GetItemPath(g_pChildWnd->hTreeWnd, 0, &hKeyRoot);
    GetKeyName(ExportKeyPath, COUNT_OF(ExportKeyPath), hKeyRoot, pszKeyPath);

    InitOpenFileName(hWnd, &ofn);
    LoadStringW(hInst, IDS_EXPORT_REG_FILE, Caption, COUNT_OF(Caption));
    ofn.lpstrTitle = Caption;

    /* Only set the path if a key (not the root node) is selected */
    if (hKeyRoot != 0)
    {
        ofn.lCustData = (LPARAM) ExportKeyPath;
    }
    ofn.Flags = OFN_ENABLETEMPLATE | OFN_EXPLORER | OFN_ENABLEHOOK | OFN_OVERWRITEPROMPT;
    ofn.lpfnHook = ExportRegistryFile_OFNHookProc;
    ofn.lpTemplateName = MAKEINTRESOURCEW(IDD_EXPORTRANGE);
    if (GetSaveFileName(&ofn))
    {
        switch (ofn.nFilterIndex)
        {
            case 2: /* Registry Hive Files */
            {
                LONG lResult;
                HKEY hSubKey;

                /* Open the subkey */
                lResult = RegOpenKeyExW(hKeyRoot, pszKeyPath, 0, KEY_READ, &hSubKey);
                if (lResult == ERROR_SUCCESS)
                {
                    /* Enable the 'backup' privilege, save the hive then disable the privilege */
                    EnablePrivilege(SE_BACKUP_NAME, NULL, TRUE);
                    lResult = RegSaveKeyW(hSubKey, ofn.lpstrFile, NULL);
                    if (lResult == ERROR_ALREADY_EXISTS)
                    {
                        /*
                         * We are here, that means that we already said "yes" to the confirmation dialog.
                         * So we absolutely want to replace the hive file.
                         */
                        if (DeleteFileW(ofn.lpstrFile))
                        {
                            /* Try again */
                            lResult = RegSaveKeyW(hSubKey, ofn.lpstrFile, NULL);
                        }
                    }
                    EnablePrivilege(SE_BACKUP_NAME, NULL, FALSE);

                    if (lResult != ERROR_SUCCESS)
                    {
                        /*
                         * If we are here, it's because RegSaveKeyW has failed for any reason.
                         * The problem is that even if it has failed, it has created or
                         * replaced the exported hive file with a new empty file. We don't
                         * want to keep this file, so we delete it.
                         */
                        DeleteFileW(ofn.lpstrFile);
                    }

                    /* Close the subkey */
                    RegCloseKey(hSubKey);
                }

                /* Set the return value */
                bRet = (lResult == ERROR_SUCCESS);

                /* Display error, if any */
                if (!bRet) ErrorMessageBox(hWnd, Caption, lResult);

                break;
            }

            case 1:  /* Windows Registry Editor Version 5.00 */
            case 3:  /* REGEDIT4 */
            default: /* All files ==> use Windows Registry Editor Version 5.00 */
            {
                if (!export_registry_key(ofn.lpstrFile, ExportKeyPath,
                                         (ofn.nFilterIndex == 3 ? REG_FORMAT_4
                                                                : REG_FORMAT_5)))
                {
                    /* Error creating the file */
                    LoadStringW(hInst, IDS_APP_TITLE, szTitle, COUNT_OF(szTitle));
                    LoadStringW(hInst, IDS_EXPORT_ERROR, szText, COUNT_OF(szText));
                    InfoMessageBox(hWnd, MB_OK | MB_ICONERROR, szTitle, szText, ofn.lpstrFile);
                    bRet = FALSE;
                }
                else
                {
                    bRet = TRUE;
                }

                break;
            }
        }
    }
    else
    {
        CheckCommDlgError(hWnd);
    }

    return bRet;
}
Exemple #24
0
static BOOL ImportRegistryFile(HWND hWnd)
{
    BOOL bRet = FALSE;
    OPENFILENAME ofn;
    WCHAR Caption[128], szTitle[512], szText[512];
    HKEY hKeyRoot;
    LPCWSTR pszKeyPath;

    /* Figure out in which key path we are importing */
    pszKeyPath = GetItemPath(g_pChildWnd->hTreeWnd, 0, &hKeyRoot);

    InitOpenFileName(hWnd, &ofn);
    LoadStringW(hInst, IDS_IMPORT_REG_FILE, Caption, COUNT_OF(Caption));
    ofn.lpstrTitle = Caption;
    ofn.Flags |= OFN_ENABLESIZING;
    /*    ofn.lCustData = ;*/
    if (GetOpenFileName(&ofn))
    {
        /* Look at the extension of the file to determine its type */
        if (ofn.nFileExtension >= 1 &&
            _wcsicmp(ofn.lpstrFile + ofn.nFileExtension, L"reg") == 0) /* REGEDIT4 or Windows Registry Editor Version 5.00 */
        {
            /* Open the file */
            FILE* fp = _wfopen(ofn.lpstrFile, L"r");

            /* Import it */
            if (fp == NULL || !import_registry_file(fp))
            {
                /* Error opening the file */
                LoadStringW(hInst, IDS_APP_TITLE, szTitle, COUNT_OF(szTitle));
                LoadStringW(hInst, IDS_IMPORT_ERROR, szText, COUNT_OF(szText));
                InfoMessageBox(hWnd, MB_OK | MB_ICONERROR, szTitle, szText, ofn.lpstrFile);
                bRet = FALSE;
            }
            else
            {
                /* Show successful import */
                LoadStringW(hInst, IDS_APP_TITLE, szTitle, COUNT_OF(szTitle));
                LoadStringW(hInst, IDS_IMPORT_OK, szText, COUNT_OF(szText));
                InfoMessageBox(hWnd, MB_OK | MB_ICONINFORMATION, szTitle, szText, ofn.lpstrFile);
                bRet = TRUE;
            }

            /* Close the file */
            if (fp) fclose(fp);
        }
        else /* Registry Hive Files */
        {
            LoadStringW(hInst, IDS_QUERY_IMPORT_HIVE_CAPTION, szTitle, COUNT_OF(szTitle));
            LoadStringW(hInst, IDS_QUERY_IMPORT_HIVE_MSG, szText, COUNT_OF(szText));

            /* Display a confirmation message */
            if (MessageBoxW(g_pChildWnd->hWnd, szText, szTitle, MB_ICONWARNING | MB_YESNO) == IDYES)
            {
                LONG lResult;
                HKEY hSubKey;

                /* Open the subkey */
                lResult = RegOpenKeyExW(hKeyRoot, pszKeyPath, 0, KEY_WRITE, &hSubKey);
                if (lResult == ERROR_SUCCESS)
                {
                    /* Enable the 'restore' privilege, restore the hive then disable the privilege */
                    EnablePrivilege(SE_RESTORE_NAME, NULL, TRUE);
                    lResult = RegRestoreKey(hSubKey, ofn.lpstrFile, REG_FORCE_RESTORE);
                    EnablePrivilege(SE_RESTORE_NAME, NULL, FALSE);

                    /* Flush the subkey and close it */
                    RegFlushKey(hSubKey);
                    RegCloseKey(hSubKey);
                }

                /* Set the return value */
                bRet = (lResult == ERROR_SUCCESS);

                /* Display error, if any */
                if (!bRet) ErrorMessageBox(hWnd, Caption, lResult);
            }
        }
    }
    else
    {
        CheckCommDlgError(hWnd);
    }

    /* refresh tree and list views */
    RefreshTreeView(g_pChildWnd->hTreeWnd);
    pszKeyPath = GetItemPath(g_pChildWnd->hTreeWnd, 0, &hKeyRoot);
    RefreshListView(g_pChildWnd->hListWnd, hKeyRoot, pszKeyPath);

    return bRet;
}
Exemple #25
0
//todo: grab the bug fixes from v2 to speed up and prevent can not close error in debug mode. ignore callback 
int __stdcall EnumMutex(char* outPath){
	
	int cnt=0;

    EnablePrivilege(SE_DEBUG_NAME);
    HMODULE hNtDll = LoadLibrary(TEXT("ntdll.dll"));
    if (!hNtDll) return -1;

    PZWQUERYSYSTEMINFORMATION ZwQuerySystemInformation =  (PZWQUERYSYSTEMINFORMATION)GetProcAddress(hNtDll, "ZwQuerySystemInformation");
    PZWDUPLICATEOBJECT ZwDuplicateObject = (PZWDUPLICATEOBJECT)GetProcAddress(hNtDll, "ZwDuplicateObject");
    PZWQUERYOBJECT ZwQueryObject = (PZWQUERYOBJECT)GetProcAddress(hNtDll, "ZwQueryObject");

	if( (int)ZwQuerySystemInformation == 0 || (int)ZwDuplicateObject  == 0 || (int)ZwQueryObject == 0) return -2;

	ULONG n = 0x1000;
    PULONG p = new ULONG[n];

	FILE *f = fopen(outPath,"w");
	if(f == NULL) return -3;

	while (ZwQuerySystemInformation(SystemHandleInformation, p, n * sizeof *p, 0) == STATUS_INFO_LENGTH_MISMATCH){
		delete [] p;
		p = new ULONG[n *= 2];
	}

    PSYSTEM_HANDLE_INFORMATION h = PSYSTEM_HANDLE_INFORMATION(p + 1);

	for (ULONG i = 0; i < *p; i++){

            HANDLE hObject;
			OBJECT_BASIC_INFORMATION obi;
            HANDLE hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, h[i].ProcessId);

			if (ZwDuplicateObject(hProcess, HANDLE(h[i].Handle), NtCurrentProcess(), &hObject, 0, 0, DUPLICATE_SAME_ATTRIBUTES)!= STATUS_SUCCESS){ 
                continue;
			}

            ZwQueryObject(hObject, ObjectBasicInformation, &obi, sizeof obi, &n);

            n = obi.TypeInformationLength + 2;
            POBJECT_TYPE_INFORMATION oti = POBJECT_TYPE_INFORMATION(new CHAR[n]);
            ZwQueryObject(hObject, ObjectTypeInformation, oti, n, &n);
            
			if(oti[0].Name.Length > 0 && wcscmp(oti[0].Name.Buffer,L"Mutant")==0){
				n = obi.NameInformationLength == 0 ? MAX_PATH * sizeof (WCHAR) : obi.NameInformationLength;
				POBJECT_NAME_INFORMATION oni = POBJECT_NAME_INFORMATION(new CHAR[n]);
				NTSTATUS rv = ZwQueryObject(hObject, ObjectNameInformation, oni, n, &n);
				if (NT_SUCCESS(rv)){
					if(oni[0].Name.Length > 0){
						fprintf(f,"%ld ", h[i].ProcessId);
						fprintf(f,"%.*ws\r\n", oni[0].Name.Length / 2, oni[0].Name.Buffer);
						cnt++;
					}
				}
			}

            CloseHandle(hObject);
            CloseHandle(hProcess);              
    }

    delete [] p;
	fclose(f);
	return cnt;

}
Exemple #26
0
int __stdcall EnumMutex2(_CollectionPtr *pColl, void* doEventsCallback){
		
	int cnt=0;
	char buf[600];
	NTSTATUS rv;
    vbCallback doEvents = (vbCallback)doEventsCallback; 

	if(pColl==0 || *pColl == 0) return -4;

    EnablePrivilege(SE_DEBUG_NAME);
    HMODULE hNtDll = LoadLibrary(TEXT("ntdll.dll"));
    if (!hNtDll) return -1;

    PZWQUERYSYSTEMINFORMATION ZwQuerySystemInformation =  (PZWQUERYSYSTEMINFORMATION)GetProcAddress(hNtDll, "ZwQuerySystemInformation");
    PZWDUPLICATEOBJECT ZwDuplicateObject = (PZWDUPLICATEOBJECT)GetProcAddress(hNtDll, "ZwDuplicateObject");
    PZWQUERYOBJECT ZwQueryObject = (PZWQUERYOBJECT)GetProcAddress(hNtDll, "ZwQueryObject");

	if( (int)ZwQuerySystemInformation == 0 || (int)ZwDuplicateObject  == 0 || (int)ZwQueryObject == 0) return -2;

	ULONG n = 0x1000;
    PULONG p = new ULONG[n];

	while (ZwQuerySystemInformation(SystemHandleInformation, p, n * sizeof *p, 0) == STATUS_INFO_LENGTH_MISMATCH){
		delete [] p;
		p = new ULONG[n *= 2];
	}

    PSYSTEM_HANDLE_INFORMATION h = PSYSTEM_HANDLE_INFORMATION(p + 1);

	for (ULONG i = 0; i < *p; i++){

            HANDLE hObject = 0;
			OBJECT_BASIC_INFORMATION obi;
            HANDLE hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, h[i].ProcessId);

			if(hProcess == 0)
				continue;

			//kept getting NtClose was called on a handle that was protected from close via NtSetInformationObject.
			//also this is much faster by eliminating the DUPLICATE_SAME_ATTRIBUTES flag..no need to use the doevents callback?
			if (ZwDuplicateObject(hProcess, HANDLE(h[i].Handle), NtCurrentProcess(), &hObject, 0, 0, /*DUPLICATE_SAME_ATTRIBUTES*/ NULL)!= STATUS_SUCCESS) 
                continue;

            rv = ZwQueryObject(hObject, ObjectBasicInformation, &obi, sizeof obi, &n);
			
			if(!NT_SUCCESS(rv)) 
				continue;

            n = obi.TypeInformationLength + 2;
            POBJECT_TYPE_INFORMATION oti = POBJECT_TYPE_INFORMATION(new CHAR[n]);
            rv = ZwQueryObject(hObject, ObjectTypeInformation, oti, n, &n);
            
			if(!NT_SUCCESS(rv)) 
				continue;

			if(oti[0].Name.Length > 0 && wcscmp(oti[0].Name.Buffer,L"Mutant")==0){
				n = obi.NameInformationLength == 0 ? MAX_PATH * sizeof (WCHAR) : obi.NameInformationLength;
				POBJECT_NAME_INFORMATION oni = POBJECT_NAME_INFORMATION(new CHAR[n]);
				rv = ZwQueryObject(hObject, ObjectNameInformation, oni, n, &n);
				if (NT_SUCCESS(rv)){
					if(oni[0].Name.Length > 0){
						_snprintf(buf, sizeof(buf)-1, "%ld %ls", h[i].ProcessId, oni[0].Name.Buffer);
						addStr(*pColl,buf);
						cnt++;
					}
				}
			}
			
			//_snprintf(buf, sizeof(buf), "i=%d hObject=%x hProcess=%x\r\n",i,hObject,hProcess);
			//OutputDebugString(buf);

			if( (int)doEvents != 0 && i > 0 && i%5 == 0 ) 
				doEvents("");

            if(hObject !=0) CloseHandle(hObject);
            if(hProcess!=0) CloseHandle(hProcess);              
    }

    delete [] p;
	return cnt;

}
HANDLE CreateUserToken(const char *userName, 
                           const char *domainName, const char *sourceName)
{
  debug2("-> CreateUserToken()...");
  
  HMODULE hNtDll = NULL;
  
  NtCreateTokenPtr NtCreateToken = NULL;
  
  HANDLE token = INVALID_HANDLE_VALUE;
  
  /*
   * These are compounds of user's access token structure.
   * The goal is setup these strutures and combine them
   * into one access token using NtCreateToken() WINAPI function.
   */
  
  LUID authId = SYSTEM_LUID;
  
  TOKEN_USER userToken;

  PTOKEN_GROUPS groupsToken = NULL;
  
  PTOKEN_PRIVILEGES pPrivToken = NULL;
  
  TOKEN_OWNER ownerToken;
  
  TOKEN_PRIMARY_GROUP primaryGroupToken;

  TOKEN_SOURCE sourceToken;  
  
  PTOKEN_DEFAULT_DACL pDaclToken = NULL;
  
  LARGE_INTEGER expirationTime = {0xFFFFFFFF, 0x7FFFFFFF};
  
  OBJECT_ATTRIBUTES oa;
  
  /*
   * Temporary variables
   */
  
  SECURITY_QUALITY_OF_SERVICE sqos = 
  {
    sizeof(sqos), 
    SecurityAnonymous, 
    SECURITY_STATIC_TRACKING,
    FALSE
  };
    
  int i;
  
  size_t size = 0;
  
  wchar_t *userNameW = NULL;
  
  DWORD cbSize;
  
  HANDLE hProcToken = NULL;
  
  /*
   * Variables to handle error codes.
   */
  
  int exitCode = 1;
  int ntStat   = 0;
  
  /*
   * Make wide char version of user's name.
   */
  
  size = (strlen(userName) + 1) * sizeof(wchar_t);
  
  userNameW = (wchar_t *) LocalAlloc(LPTR, size);;

  swprintf(userNameW, L"%hs", userName);
  
  /*
   * Give needed privilege to current running process
   */
  
  debug("Enabling privilege to current running process...");

  EnablePrivilege("SeTcbPrivilege", 1);
  EnablePrivilege("SeChangeNotifyPrivilege", 1);
  EnablePrivilege("SeIncreaseQuotaPrivilege", 1);
  EnablePrivilege("SeAssignPrimaryTokenPrivilege", 1);
  EnablePrivilege("SeCreateTokenPrivilege", 1);
  
  /*
   * Create TOKEN_USER part
   */
      
  debug("Setting up TOKEN_USER...");
  
  FAIL(GetSidW(&userToken.User.Sid, userNameW));

  userToken.User.Attributes = 0;
  
  /*
   * Create TOKEN_OWNER part. We assume Owner = User.
   */
  
  debug("Setting up TOKEN_OWNER...");
  
  FAIL(GetSidW(&ownerToken.Owner, userNameW));
  
  /*
   * Create TOKEN_SOURCE part
   */
  
  debug("Setting up TOKEN_SOURCE...");
  
  FAIL(AllocateLocallyUniqueId(&sourceToken.SourceIdentifier) == FALSE);
  
  size = min(strlen(sourceName), 8);
      
  memcpy(sourceToken.SourceName, "********", 8);
  memcpy(sourceToken.SourceName, sourceName, size);

  /*
   * Create TOKEN_GROUPS part
   */
  
  debug("Setting up TOKEN_GROUPS...");
  
  FAIL(SetupTokenGroups(&groupsToken, userNameW));
  
  /*
   * Create TOKEN_PRIVILEGES part
   */
  
  debug("Setting up TOKEN_PRIVILEGES...");
  
  FAIL(SetupTokenPrivileges(&pPrivToken, userToken.User.Sid));
  
  /*
   * Create TOKEN_PRIMARY_GROUP part
   */
  
  debug("Setting up TOKEN_PRIMARY GROUP...");
  
  primaryGroupToken.PrimaryGroup = EveryoneSID();
  
  /*
   * Setup object attributes
   */
  
  memset(&oa, 0, sizeof(oa));

  oa.Length = sizeof(oa);
  
  oa.SecurityQualityOfService = &sqos;

  /*
   * Setup TOKEN_DEFAULT_DACL part.
   */
  
  debug("Setting up TOKEN_DEFAULT_DACL...");
  
  debug("Opening current process's token...");

  FAIL(OpenProcessToken(GetCurrentProcess(),
                            TOKEN_QUERY | TOKEN_QUERY_SOURCE, 
                                &hProcToken) == FALSE);

  debug("Retrieving TOKEN_DEFAULT_DACL...");

  GetTokenInformation(hProcToken, TokenDefaultDacl, NULL, 0, &cbSize);
  
  pDaclToken = LocalAlloc(LPTR, cbSize);

  FAIL(GetTokenInformation(hProcToken, TokenDefaultDacl,
                               pDaclToken, cbSize, &cbSize) == FALSE);

  /*
   * Print debug info about parts
   */
  
  //PrintPartsInfo(&token, TOKEN_ALL_ACCESS, &oa, 
  //                            TokenPrimary, &authId, &expirationTime,
  //                                &userToken, groupsToken, pPrivToken,
  //                                    &ownerToken, &primaryGroupToken, 
  //                                        pDaclToken, &sourceToken);

  /*
   * Retrieve address of NtCreateToken() function.
   */

  debug("Retrieving NtCreateToken() address...");
  
  hNtDll = GetModuleHandle("ntdll.dll");
  
  FAIL(hNtDll == NULL);

  NtCreateToken = (NtCreateTokenPtr) GetProcAddress(hNtDll, "NtCreateToken");

  FAIL(NtCreateToken == NULL);

  /*
   * Create new user acces token from parts setted up above.
   */

  debug("Creating token from parts...");
  
  ntStat = NtCreateToken(&token, TOKEN_ALL_ACCESS, &oa,
                              TokenPrimary, &authId, &expirationTime,
                                  &userToken, groupsToken, pPrivToken,
                                      &ownerToken, &primaryGroupToken,
                                          pDaclToken, &sourceToken);                         
  FAIL(ntStat);

  /*
   * Add rights to use 'default' desktop and WinStation0.
   */

  if (AddRightsToDesktopBySid(userToken.User.Sid))
  {
    debug("WARNING. Cannot add rights to 'winsta0\\default'!");
  }

  exitCode = 0;
  
fail:

  /*
   * Free allocated memory
   */
  
  debug2("Freeing groupsToken...");
  
  if (groupsToken)
  {
    /*
     * We don't need to test were SIDs allocated correctly,
     * becouse FreeSid() do it.
     */
    
    for (i = 0; i < groupsToken -> GroupCount; i++)
    {
      FreeSid(groupsToken -> Groups[i].Sid);
    }

    LocalFree(groupsToken);
  }
  
  debug2("Freeing local buffers...");
  
  LocalFree(userNameW);
  LocalFree(pDaclToken);
  LocalFree(pPrivToken);
  
  debug2("Freeing SIDs...");
  
  FreeSid(userToken.User.Sid);
  FreeSid(ownerToken.Owner);
  FreeSid(primaryGroupToken.PrimaryGroup);
  
  debug2("Closing hProcToken...");
  
  CloseHandle(hProcToken);

  debug2("Closing hNtDll...");
  
  CloseHandle(hNtDll);
  
  /*
   * Something was wrong.
   */
  
  if (exitCode)
  {
    debug("ERROR. Cannot create user's acces token. (err = %u, ntStat = %x)",
              GetLastError(), ntStat);
  }

  debug2("<- CreateUserToken()...");
  
  return token;
}
Exemple #28
0
/*****************************************
 * Load a library into a remote process. *
 *****************************************/
int InjectDll()
{
    HANDLE	hThread;				// Thread handle
    HANDLE	hProcess;				// Process handle
    DWORD	dwPID;					// Process ID
    char	szLibPath[MAX_PATH];	// Full DLL path
    void	*pLibRemote;			// Address (in the remote process) where szLibPath will be copied to

    // Enable DEBUG privilege
    if (!EnablePrivilege(SE_DEBUG_NAME, TRUE))
        return 0;

    // Get remote process id
    dwPID = GetPIDFromName(szProcessName);
    if (dwPID == -1)
        return 0;

    // Open remote process
    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID);
    if (hProcess == NULL)
        return 0;

    // Get full path of the DLL
    if (!GetModuleFileName(hInst, szLibPath, MAX_PATH))
        return 0;
    strcpy(strrchr(szLibPath, '\\') + 1 , szDllName);

    // Allocate memory in the remote process to store the szLibPath string
    pLibRemote = VirtualAllocEx(hProcess, NULL, sizeof(szLibPath), MEM_COMMIT, PAGE_READWRITE);
    if (pLibRemote == NULL)
        return 0;
    // Copy the szLibPath string to the remote process.
    if (!WriteProcessMemory(hProcess, pLibRemote, (void*)szLibPath, sizeof(szLibPath), NULL))
        return 0;

    // Load the DLL into the remote process
    // (via CreateRemoteThread() & LoadLibrary())
    hThread = CreateRemoteThread(hProcess,
                                 NULL,
                                 0,
                                 (LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle("Kernel32"), "LoadLibraryA"),
                                 pLibRemote,
                                 0,
                                 NULL);
    // Failed
    if(hThread == NULL)
    {
        VirtualFreeEx(hProcess, pLibRemote, sizeof(szLibPath), MEM_RELEASE);
        return 0;
    }

    // Wait for LoadLibrary() to finish and get return code (handle of loaded library)
    WaitForSingleObject(hThread, INFINITE);
    GetExitCodeThread(hThread, &hLibModule);
    CloseHandle(hThread);
    CloseHandle(hProcess);

    // Free remote memory for szLibPath
    VirtualFreeEx(hProcess, pLibRemote, sizeof(szLibPath), MEM_RELEASE);

    // Remote LoadLibrary() failed
    if (!hLibModule)
        return 0;

    // Disable DEBUG privilege
    EnablePrivilege(SE_DEBUG_NAME, FALSE);

    return 1;
}
Exemple #29
0
int KillProcess(const wchar_t *process)
{
	int iReturnCode = RETURN_OK;

	LOG(L"Ask for killing %s\n",process);

	bool bNone= true;

    do 
	{
		bool bFound= false;
		DWORD pid=0;

		EnablePrivilege(SE_DEBUG_NAME);
		HANDLE hndl = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
		DWORD dwsma = GetLastError();

		PROCESSENTRY32  procEntry={0};
		procEntry.dwSize = sizeof( PROCESSENTRY32 );
		Process32First(hndl,&procEntry);
		do 
		{
			if(!_wcsicmp(procEntry.szExeFile,process))	
			{
				bFound = true;
				bNone = false;
				pid = procEntry.th32ProcessID;
				break;
			}
		} while(Process32Next(hndl,&procEntry));

		CloseHandle( hndl );

		//Kill the process
		if(bFound)
		{
			
			HANDLE hHandle = NULL;
			if(NULL != (hHandle = ::OpenProcess(PROCESS_TERMINATE,0,procEntry.th32ProcessID)))
			{
				DWORD dwExitCode = 0;

				if(::TerminateProcess(hHandle,dwExitCode))
				{
					::GetExitCodeProcess(hHandle,&dwExitCode);
					LOG(L" --> FOUND and KILLED pid=%ld (Return code = %ld)\n",pid,dwExitCode);
				}
				else
				{
					LOG(L" --> ERROR - Failed to kill pid=%ld (Error code from TerminateProcess = %ld)\n",pid,GetLastError());
					iReturnCode = RETURN_ERR_KILLPROCESS_FAILED;
				} 
				CloseHandle( hHandle );
				Sleep(500);
			}
			else
			{
				LOG(L" --> ERROR - Failed to kill pid=%ld (Error code from OpenProcess = %ld)\n",pid,GetLastError());
				iReturnCode = RETURN_ERR_KILLPROCESS_FAILED;
			}
		}
		else
		{
			break;
		}

		if(iReturnCode!=RETURN_OK)
			break;

	} while(1);

	if(bNone) LOG(L" --> NOT FOUND\n");

	LOG(L"\n");

	return iReturnCode;
}
Exemple #30
0
////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// PRIVATE FUNCTIONS ////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
int processFillList(Proc_LIST *processList, const wchar_t *processName)
{
	int iReturnCode = DIAGLIB_OK;

	if(processList == NULL)
	{
		return RETURN_LOG_BAD_FUNCTION_CALL;
	}

	if(processName)
	{
		LOG_TIME(L"Ask for process list (with name = %ls) --> ",processName);
	}
	else
	{
		LOG_TIME(L"Ask for list of all process --> ");
	}

	processList->clear();

	EnablePrivilege(SE_DEBUG_NAME);
	HANDLE hndl;
	if(INVALID_HANDLE_VALUE == ( hndl=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0)))
	{
		LOG_LASTERROR(L"CreateToolhelp32Snapshot failed");
		return RETURN_LOG_INTERNAL_ERROR;
	}

	PROCESSENTRY32  procEntry={0};
	procEntry.dwSize = sizeof( PROCESSENTRY32 );

	//Get progressMax if request
	int progressMax = 0;
	if (!Process32First(hndl, &procEntry))
	{
		LOG_LASTERROR(L"Process32First failed");
		if(!CloseHandle( hndl ))
		{
			LOG_LASTERROR(L"CloseHandle failed");
		}
		return RETURN_LOG_INTERNAL_ERROR;
	}
	do
	{
		progressMax++;
	} while (Process32Next(hndl, &procEntry));

	if(!Process32First(hndl,&procEntry))
	{
		LOG_LASTERROR(L"Process32First failed");
		if(!CloseHandle( hndl ))
		{
			LOG_LASTERROR(L"CloseHandle failed");
		}
		return RETURN_LOG_INTERNAL_ERROR;
	}

	progressInit(progressMax);

	do 
	{
		if(procEntry.th32ProcessID != 0)
		{
			if(processName == NULL)
			{
				processList->push_back(procEntry.th32ProcessID);
			}
			else if(0 == _wcsicmp(procEntry.szExeFile,processName))	
			{
				processList->push_back(procEntry.th32ProcessID);
			}
		}

		progressIncrement();

	} while(Process32Next(hndl,&procEntry));

	progressRelease();

	if(!CloseHandle( hndl ))
	{
		LOG_LASTERROR(L"CloseHandle failed");
	}

	if(processList->size() == 0)
	{
		LOG(L"NO PROCESS FOUND\n");
	}
	else
	{
		LOG(L"pid=");
		for (unsigned long i=0; i < processList->size() ; i++)
		{
			LOG(L"%ld,",processList->at(i));
		}
		LOG(L"DONE\n");
	}

	return iReturnCode;
}