int _tmain(int argc, _TCHAR* argv[]) { PWTS_SESSION_INFO pSessionInfo; DWORD dwSessionInfo=0; WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE,0,1,&pSessionInfo,&dwSessionInfo); printf("[*] Windows DACL Enumeration Project - https://github.com/nccgroup/WindowsDACLEnumProject - WinStationsAndDesktopsPerms\n"); printf("[*] NCC Group Plc - http://www.nccgroup.com/ \n"); printf("[*] -h for help \n"); SetPrivilege(GetCurrentProcess(),SE_DEBUG_NAME); DWORD dwSessID = 0; ProcessIdToSessionId(GetCurrentProcessId(),&dwSessID); fprintf(stdout,"[i] Running in session %d\n",dwSessID); EnumWindowStations(&EnumWindowStationProc,NULL); return 0; }
static DWORD find_process(const char *targetExeName, DWORD targetSession) { PROCESSENTRY32 pe32 = {0}; HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnap == INVALID_HANDLE_VALUE) { return 0; } pe32.dwSize = sizeof(PROCESSENTRY32); if (!Process32First(hSnap, &pe32)) { CloseHandle(hSnap); return 0; } do { if (_stricmp(pe32.szExeFile, targetExeName) == 0) { DWORD sessId = 0; if (ProcessIdToSessionId(pe32.th32ProcessID, &sessId) && sessId == targetSession) { /* found target process */ CloseHandle(hSnap); return pe32.th32ProcessID; } } } while (Process32Next(hSnap, &pe32)); CloseHandle(hSnap); return 0; }
static BOOL IsRemote(DWORD pid, DWORD *exitTag, DWORD *lastErrorCode) { DWORD sessionId; if (FALSE == ProcessIdToSessionId(pid, &sessionId)) { *exitTag = 1; *lastErrorCode = GetLastError(); return FALSE; } OSVERSIONINFOW osvi; ZeroMemory(&osvi, sizeof(OSVERSIONINFOW)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW); GetVersionExW(&osvi); if (osvi.dwMajorVersion > 5) { // The case of Vista/Server 2008: 0 and 1 means local, greater than 1 - remote. return (0 != sessionId) && (1 != sessionId); } else if ((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion >= 1)) { // The case of XP/Server 2003: 0 is local, another value means remote. return (0 != sessionId); } else { *exitTag = 2; return FALSE; } }
int Temp_CalcSelfClientID(unsigned __int32 a1, unsigned __int32 *a2) { int result; // eax@2 char v3; // [sp+Ch] [bp-DCh]@1 unsigned __int32 v4; // [sp+D0h] [bp-18h]@3 DWORD pSessionId; // [sp+D4h] [bp-14h]@3 DWORD dwProcessId; // [sp+D8h] [bp-10h]@3 int v7; // [sp+DCh] [bp-Ch]@3 unsigned int v8; // [sp+E4h] [bp-4h]@1 int savedregs; // [sp+E8h] [bp+0h]@1 if ( a2 ) { pSessionId = 0; dwProcessId = 0; v7 = 0; v4 = a1; dwProcessId = GetCurrentProcessId(); ProcessIdToSessionId(dwProcessId, &pSessionId); v7 = 0; CalcClientID((PCLIENTINFO)&v4); *a2 = v4; result = 0; } else { result = -536863742; } return result; }
SessionChangesWatcher::SessionChangesWatcher(AnEventListener *extSessionChangesListener, LogWriter *log) : m_extSessionChangesListener(extSessionChangesListener), m_log(log) { ProcessIdToSessionId(GetCurrentProcessId(), &m_baseSessionId); resume(); }
std::string currentUserUid() { # ifdef _WIN32 DWORD sessId = 0; ProcessIdToSessionId(GetCurrentProcessId(), &sessId); return tfm::format("%d", sessId); # else return tfm::format("%d", ::getuid()); # endif }
bstr_t GetSessionPath() { std::wstringstream ss; WCHAR objPath[MAX_PATH + 1] = { 0 }; ULONG length = MAX_PATH; DWORD dwSessionId; if (ProcessIdToSessionId(GetCurrentProcessId(), &dwSessionId)) { ss << L"\\Sessions\\" << dwSessionId; return ss.str().c_str(); } return L""; }
static void test_SHCreateSessionKey(void) { static const WCHAR session_format[] = { 'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\', 'W','i','n','d','o','w','s','\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\', 'E','x','p','l','o','r','e','r','\\','S','e','s','s','i','o','n','I','n','f','o','\\','%','u',0}; HKEY hkey, hkey2; HRESULT hr; DWORD session; WCHAR sessionW[ARRAY_SIZE(session_format) + 16]; LONG ret; if (!pSHCreateSessionKey) { win_skip("SHCreateSessionKey is not implemented\n"); return; } if (0) /* crashes on native */ hr = pSHCreateSessionKey(KEY_READ, NULL); hkey = (HKEY)0xdeadbeef; hr = pSHCreateSessionKey(0, &hkey); ok(hr == E_ACCESSDENIED, "got 0x%08x\n", hr); ok(hkey == NULL, "got %p\n", hkey); hr = pSHCreateSessionKey(KEY_READ, &hkey); ok(hr == S_OK, "got 0x%08x\n", hr); hr = pSHCreateSessionKey(KEY_READ, &hkey2); ok(hr == S_OK, "got 0x%08x\n", hr); ok(hkey != hkey2, "got %p, %p\n", hkey, hkey2); RegCloseKey(hkey); RegCloseKey(hkey2); /* check the registry */ ProcessIdToSessionId( GetCurrentProcessId(), &session); if (session) { wsprintfW(sessionW, session_format, session); ret = RegOpenKeyW(HKEY_CURRENT_USER, sessionW, &hkey); ok(!ret, "key not found\n"); RegCloseKey(hkey); } }
std::wstring SYS_get_base_named_objects_path() { std::wstring base_name_objects_path; // get our terminal services session id DWORD session_id; ProcessIdToSessionId(GetCurrentProcessId(), &session_id); // create a path to the kernel BaseNamedObjects if( session_id == 0 ) { // there is no 0 session, this just means an OS without terminal services base_name_objects_path = L"\\BaseNamedObjects"; } else { wchar_t path_buffer[MAX_PATH]; wsprintf(path_buffer, L"\\Sessions\\%d\\BaseNamedObjects", session_id); base_name_objects_path = path_buffer; } return base_name_objects_path; }
BOOL CHooks::IsInRemoteDesktop() { BOOL bRet = FALSE; DWORD dwSectionId = 0, dwBytesReturned = 0; DWORD dwProcessId = GetCurrentProcessId(); ProcessIdToSessionId(dwProcessId, &dwSectionId); LPTSTR pBuffer = NULL; DWORD dwRet = WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, dwSectionId, WTSClientName, &pBuffer, &dwBytesReturned); if (dwRet != 0 && dwBytesReturned != 0 && pBuffer != NULL) { bRet = lstrlen(pBuffer) > 0; WTSFreeMemory(pBuffer); } return bRet; }
// Open a window station and a desktop in another session, grant access to those handles DWORD GrantRemoteSessionDesktopAccess( IN DWORD sessionId, IN const WCHAR *accountName, IN WCHAR *systemName ) { DWORD status = ERROR_UNIDENTIFIED_ERROR; HRESULT hresult; HANDLE token = NULL; HANDLE tokenDuplicate = NULL; WCHAR fullPath[MAX_PATH + 1] = { 0 }; WCHAR arguments[UNLEN + 1]; PROCESS_INFORMATION pi = { 0 }; STARTUPINFO si = { 0 }; DWORD currentSessionId; if (!accountName) return ERROR_INVALID_PARAMETER; if (!ProcessIdToSessionId(GetCurrentProcessId(), ¤tSessionId)) { return perror("ProcessIdToSessionId"); } if (currentSessionId == sessionId) { // We're in the same session, no need to run an additional process. LogInfo("Already running in the specified session"); status = GrantDesktopAccess(accountName, systemName); if (ERROR_SUCCESS != status) perror2(status, "GrantDesktopAccess"); return status; } if (!OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, TRUE, &token)) { if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &token)) { return perror("OpenProcessToken"); } } if (!DuplicateTokenEx( token, MAXIMUM_ALLOWED, NULL, SecurityIdentification, TokenPrimary, &tokenDuplicate)) { status = perror("DuplicateTokenEx"); goto cleanup; } CloseHandle(token); token = tokenDuplicate; if (!SetTokenInformation(token, TokenSessionId, &sessionId, sizeof(sessionId))) { status = perror("SetTokenInformation"); goto cleanup; } if (!GetModuleFileName(NULL, fullPath, RTL_NUMBER_OF(fullPath) - 1)) { status = perror("GetModuleFileName"); goto cleanup; } hresult = StringCchPrintf(arguments, RTL_NUMBER_OF(arguments), L"\"%s\" -a %s", fullPath, accountName); if (FAILED(hresult)) { LogError("StringCchPrintf failed"); goto cleanup; } si.cb = sizeof(si); LogDebug("CreateProcessAsUser(%s)", arguments); if (!CreateProcessAsUser( token, fullPath, arguments, NULL, NULL, TRUE, // handles are inherited 0, NULL, NULL, &si, &pi)) { status = perror("CreateProcessAsUser"); goto cleanup; } status = WaitForSingleObject(pi.hProcess, 1000); if (WAIT_OBJECT_0 != status) { if (WAIT_TIMEOUT == status) { status = ERROR_ACCESS_DENIED; LogInfo("WaitForSingleObject timed out"); } else { status = perror("WaitForSingleObject"); } } cleanup: if (pi.hThread) CloseHandle(pi.hThread); if (pi.hProcess) CloseHandle(pi.hProcess); if (token) CloseHandle(token); return status; }
int WINAPI WinMain(HINSTANCE instance, HINSTANCE prev_instance, LPSTR cmdline, int cmdshow) { int success = 0; HANDLE helper = NULL; HMODULE hookdll = NULL; SYSTEM_INFO si; set_hooks_proc_t set_hooks_fn; remove_hooks_proc_t remove_hooks_fn; get_instance_count_proc_t instance_count_fn; int check_counter; if (strlen(cmdline) == 0) { message("No command line specified."); return -1; } if (vchannel_open()) { message("Unable to set up the virtual channel."); return -1; } GetSystemInfo(&si); switch (si.wProcessorArchitecture) { case PROCESSOR_ARCHITECTURE_INTEL: hookdll = LoadLibrary("seamlessrdp32.dll"); break; case PROCESSOR_ARCHITECTURE_AMD64: hookdll = LoadLibrary("seamlessrdp64.dll"); break; default: message("Unsupported processor architecture."); break; } if (!hookdll) { message("Could not load hook DLL. Unable to continue."); goto close_vchannel; } set_hooks_fn = (set_hooks_proc_t) GetProcAddress(hookdll, "SetHooks"); remove_hooks_fn = (remove_hooks_proc_t) GetProcAddress(hookdll, "RemoveHooks"); instance_count_fn = (get_instance_count_proc_t) GetProcAddress(hookdll, "GetInstanceCount"); g_move_window_fn = (move_window_proc_t) GetProcAddress(hookdll, "SafeMoveWindow"); g_zchange_fn = (zchange_proc_t) GetProcAddress(hookdll, "SafeZChange"); g_focus_fn = (focus_proc_t) GetProcAddress(hookdll, "SafeFocus"); g_set_state_fn = (set_state_proc_t) GetProcAddress(hookdll, "SafeSetState"); if (!set_hooks_fn || !remove_hooks_fn || !instance_count_fn || !g_move_window_fn || !g_zchange_fn || !g_focus_fn || !g_set_state_fn) { message ("Hook DLL doesn't contain the correct functions. Unable to continue."); goto close_hookdll; } /* Check if the DLL is already loaded */ switch (instance_count_fn()) { case 0: message("Hook DLL failed to initialize."); goto close_hookdll; break; case 1: break; default: message("Another running instance of Seamless RDP detected."); goto close_hookdll; } helper = launch_helper(); ProcessIdToSessionId(GetCurrentProcessId(), &g_session_id); build_startup_procs(); g_connected = is_connected(); g_desktop_hidden = is_desktop_hidden(); vchannel_write("HELLO", "0x%08x", g_desktop_hidden ? SEAMLESS_HELLO_HIDDEN : 0); set_hooks_fn(); /* Since we don't see the entire desktop we must resize windows immediatly. */ SystemParametersInfo(SPI_SETDRAGFULLWINDOWS, TRUE, NULL, 0); /* Disable screen saver since we cannot catch its windows. */ SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, FALSE, NULL, 0); /* We don't want windows denying requests to activate windows. */ SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, 0, 0); if (!launch_app(cmdline)) { // CreateProcess failed. char msg[256]; _snprintf(msg, sizeof(msg), "Unable to launch the requested application:\n%s", cmdline); message(msg); goto unhook; } check_counter = 5; while (check_counter-- || !should_terminate()) { BOOL connected; MSG msg; connected = is_connected(); if (connected && !g_connected) { int flags; /* These get reset on each reconnect */ SystemParametersInfo(SPI_SETDRAGFULLWINDOWS, TRUE, NULL, 0); SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, FALSE, NULL, 0); SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, 0, 0); flags = SEAMLESS_HELLO_RECONNECT; if (g_desktop_hidden) flags |= SEAMLESS_HELLO_HIDDEN; vchannel_write("HELLO", "0x%08x", flags); } g_connected = connected; if (check_counter < 0) { BOOL hidden; hidden = is_desktop_hidden(); if (hidden && !g_desktop_hidden) vchannel_write("HIDE", "0x%08x", 0); else if (!hidden && g_desktop_hidden) vchannel_write("UNHIDE", "0x%08x", 0); g_desktop_hidden = hidden; check_counter = 5; } while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } process_cmds(); Sleep(100); } success = 1; unhook: remove_hooks_fn(); free_startup_procs(); if (helper) { // Terminate seamlessrdphook32.exe kill_15_9(helper, "SeamlessRDPHook", HELPER_TIMEOUT); } close_hookdll: FreeLibrary(hookdll); close_vchannel: vchannel_close(); // Logoff the user. This is necessary because the session may // have started processes that are not included in Microsofts // list of processes to ignore. Typically ieuser.exe. // FIXME: Only do this if WTSQuerySessionInformation indicates // that we are the initial program. ExitWindows(0, 0); if (success) return 1; else return -1; }
BOOL create_process_as_user(IN DWORD session_id, IN LPCWSTR application_name, IN LPWSTR command_line, IN LPSECURITY_ATTRIBUTES process_attributes, IN LPSECURITY_ATTRIBUTES thread_attributes, IN BOOL inherit_handles, IN DWORD creation_flags, IN LPVOID environment, IN LPCWSTR current_directory, IN LPSTARTUPINFOW startup_info, OUT LPPROCESS_INFORMATION process_information) { PROCESSENTRY32 proc_entry; DWORD winlogon_pid = 0; HANDLE winlogon_proc; HANDLE token = NULL; HANDLE token_dup; BOOL ret = FALSE; HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (snap == INVALID_HANDLE_VALUE) { vd_printf("CreateToolhelp32Snapshot() failed %lu", GetLastError()); return false; } ZeroMemory(&proc_entry, sizeof(proc_entry)); proc_entry.dwSize = sizeof(PROCESSENTRY32); if (!Process32First(snap, &proc_entry)) { vd_printf("Process32First() failed %lu", GetLastError()); CloseHandle(snap); return false; } do { if (_tcsicmp(proc_entry.szExeFile, WINLOGON_FILENAME) == 0) { DWORD winlogon_session_id = 0; if (ProcessIdToSessionId(proc_entry.th32ProcessID, &winlogon_session_id) && winlogon_session_id == session_id) { winlogon_pid = proc_entry.th32ProcessID; break; } } } while (Process32Next(snap, &proc_entry)); CloseHandle(snap); if (winlogon_pid == 0) { vd_printf("Winlogon not found"); return false; } winlogon_proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, winlogon_pid); if (!winlogon_proc) { vd_printf("OpenProcess() failed %lu", GetLastError()); return false; } ret = OpenProcessToken(winlogon_proc, TOKEN_DUPLICATE, &token); CloseHandle(winlogon_proc); if (!ret) { vd_printf("OpenProcessToken() failed %lu", GetLastError()); return false; } ret = DuplicateTokenEx(token, MAXIMUM_ALLOWED, NULL, SecurityIdentification, TokenPrimary, &token_dup); CloseHandle(token); if (!ret) { vd_printf("DuplicateTokenEx() failed %lu", GetLastError()); return false; } ret = CreateProcessAsUser(token_dup, application_name, command_line, process_attributes, thread_attributes, inherit_handles, creation_flags, environment, current_directory, startup_info, process_information); CloseHandle(token_dup); return ret; }
bool VDAgent::run() { DWORD session_id; DWORD event_thread_id; HANDLE event_thread; WNDCLASS wcls; if (!ProcessIdToSessionId(GetCurrentProcessId(), &session_id)) { vd_printf("ProcessIdToSessionId failed %lu", GetLastError()); return false; } vd_printf("***Agent started in session %lu***", session_id); log_version(); if (!SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS)) { vd_printf("SetPriorityClass failed %lu", GetLastError()); } if (!SetProcessShutdownParameters(0x100, 0)) { vd_printf("SetProcessShutdownParameters failed %lu", GetLastError()); } if (_system_version == SYS_VER_WIN_7_CLASS) { _user_lib = LoadLibrary(L"User32.dll"); if (!_user_lib) { vd_printf("LoadLibrary failed %lu", GetLastError()); return false; } _add_clipboard_listener = (PCLIPBOARD_OP)GetProcAddress(_user_lib, "AddClipboardFormatListener"); _remove_clipboard_listener = (PCLIPBOARD_OP)GetProcAddress(_user_lib, "RemoveClipboardFormatListener"); if (!_add_clipboard_listener || !_remove_clipboard_listener) { vd_printf("GetProcAddress failed %lu", GetLastError()); cleanup(); return false; } } _control_event = CreateEvent(NULL, FALSE, FALSE, NULL); if (!_control_event) { vd_printf("CreateEvent() failed: %lu", GetLastError()); cleanup(); return false; } _stop_event = OpenEvent(SYNCHRONIZE, FALSE, VD_AGENT_STOP_EVENT); memset(&wcls, 0, sizeof(wcls)); wcls.lpfnWndProc = &VDAgent::wnd_proc; wcls.lpszClassName = VD_AGENT_WINCLASS_NAME; if (!RegisterClass(&wcls)) { vd_printf("RegisterClass() failed: %lu", GetLastError()); cleanup(); return false; } _desktop_layout = new DesktopLayout(); if (_desktop_layout->get_display_count() == 0) { vd_printf("No QXL devices!"); } if (!init_vio_serial()) { cleanup(); return false; } if (!ReadFileEx(_vio_serial, _read_buf, sizeof(VDIChunk), &_read_overlapped, read_completion) && GetLastError() != ERROR_IO_PENDING) { vd_printf("vio_serial read error %lu", GetLastError()); cleanup(); return false; } _running = true; event_thread = CreateThread(NULL, 0, event_thread_proc, NULL, 0, &event_thread_id); if (!event_thread) { vd_printf("CreateThread() failed: %lu", GetLastError()); cleanup(); return false; } send_announce_capabilities(true); vd_printf("Connected to server"); while (_running) { input_desktop_message_loop(); if (_clipboard_owner == owner_guest) { set_clipboard_owner(owner_none); } } vd_printf("Agent stopped"); CloseHandle(event_thread); cleanup(); return true; }
BOOL CMSWindowsRelauncher::winlogonInSession(DWORD sessionId, PHANDLE process) { // first we need to take a snapshot of the running processes HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (snapshot == INVALID_HANDLE_VALUE) { LOG((CLOG_ERR "could not get process snapshot (error: %i)", GetLastError())); return 0; } PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); // get the first process, and if we can't do that then it's // unlikely we can go any further BOOL gotEntry = Process32First(snapshot, &entry); if (!gotEntry) { LOG((CLOG_ERR "could not get first process entry (error: %i)", GetLastError())); return 0; } // used to record process names for debug info std::list<std::string> nameList; // now just iterate until we can find winlogon.exe pid DWORD pid = 0; while(gotEntry) { // make sure we're not checking the system process if (entry.th32ProcessID != 0) { DWORD processSessionId; BOOL pidToSidRet = ProcessIdToSessionId( entry.th32ProcessID, &processSessionId); if (!pidToSidRet) { LOG((CLOG_ERR "could not get session id for process id %i (error: %i)", entry.th32ProcessID, GetLastError())); return 0; } // only pay attention to processes in the active session if (processSessionId == sessionId) { // store the names so we can record them for debug nameList.push_back(entry.szExeFile); if (_stricmp(entry.szExeFile, "winlogon.exe") == 0) { pid = entry.th32ProcessID; break; } } } // now move on to the next entry (if we're not at the end) gotEntry = Process32Next(snapshot, &entry); if (!gotEntry) { DWORD err = GetLastError(); if (err != ERROR_NO_MORE_FILES) { // only worry about error if it's not the end of the snapshot LOG((CLOG_ERR "could not get subsiquent process entry (error: %i)", GetLastError())); return 0; } } } std::string nameListJoin; for(std::list<std::string>::iterator it = nameList.begin(); it != nameList.end(); it++) { nameListJoin.append(*it); nameListJoin.append(", "); } LOG((CLOG_DEBUG "checked processes while looking for winlogon.exe: %s", nameListJoin.c_str())); CloseHandle(snapshot); if (pid) { // now get the process so we can get the process, with which // we'll use to get the process token. *process = OpenProcess(MAXIMUM_ALLOWED, FALSE, pid); return true; } else { LOG((CLOG_DEBUG "could not find winlogon.exe in session %i", sessionId)); return false; } }
BOOL GetProcessId(LPCTSTR pProgExe,DWORD sessionId,DWORD *pPid) { HANDLE hProcessSnap; //HANDLE hProcess; PROCESSENTRY32 pe32; //DWORD dwPriorityClass; // Take a snapshot of all processes in the system. hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hProcessSnap == INVALID_HANDLE_VALUE) { printError(TEXT("CreateToolhelp32Snapshot (of processes)")); return(FALSE); } // Set the size of the structure before using it. pe32.dwSize = sizeof(PROCESSENTRY32); // Retrieve information about the first process, // and exit if unsuccessful if (!Process32First(hProcessSnap, &pe32)) { printError(TEXT("Process32First")); // show cause of failure CloseHandle(hProcessSnap); // clean the snapshot object return(FALSE); } DWORD currentSessionId; // Now walk the snapshot of processes, and // display information about each process in turn do { _tprintf(TEXT("\n\n=====================================================")); _tprintf(TEXT("\nPROCESS NAME: %s"), pe32.szExeFile); _tprintf(TEXT("\n-------------------------------------------------------")); if (_tcscmp(pe32.szExeFile, pProgExe) != 0) continue; if (!ProcessIdToSessionId(pe32.th32ProcessID, ¤tSessionId)) continue; if (currentSessionId != sessionId) continue; // Retrieve the priority class. // dwPriorityClass = 0; // hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID); // if (hProcess == NULL) // printError(TEXT("OpenProcess")); // else // { // dwPriorityClass = GetPriorityClass(hProcess); // if (!dwPriorityClass) // printError(TEXT("GetPriorityClass")); // CloseHandle(hProcess); // } _tprintf(TEXT("\n Process ID = 0x%08X"), pe32.th32ProcessID); _tprintf(TEXT("\n Thread count = %d"), pe32.cntThreads); _tprintf(TEXT("\n Parent process ID = 0x%08X"), pe32.th32ParentProcessID); _tprintf(TEXT("\n Priority base = %d"), pe32.pcPriClassBase); // if (dwPriorityClass) // _tprintf(TEXT("\n Priority class = %d"), dwPriorityClass); // List the modules and threads associated with this process //ListProcessModules(pe32.th32ProcessID); //ListProcessThreads(pe32.th32ProcessID); } while (Process32Next(hProcessSnap, &pe32)); CloseHandle(hProcessSnap); return(TRUE); }
void _tmain(int argc, TCHAR *argv[]) { STARTUPINFO si; PROCESS_INFORMATION pi; DWORD processId; DWORD currentSessionId; DWORD currentProcessId = GetCurrentProcessId(); if (!ProcessIdToSessionId(currentProcessId, ¤tSessionId)) return ; Is_Win_Server(); if (IsWindowsWin10OrGreater()) { MessageBox(NULL, _T("You need at least Windows 10."), _T("Version Not Supported"), MB_OK); } ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); ZeroMemory(&pi, sizeof(pi)); // start the browser process now si.cb = sizeof(si); si.dwFlags = STARTF_FORCEONFEEDBACK | STARTF_USESHOWWINDOW; si.wShowWindow = SW_SHOWNORMAL; BOOL bStatus = CreateProcess(NULL, _T("C:\\Windows\\SystemApps\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\\MicrosoftEdge.exe www.baidu.com"), NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi); WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); ZeroMemory(&pi, sizeof(pi)); TCHAR test[] = _T("C:\\windows\\system32\\LaunchWinApp.exe www.baidu.com"); // Start the child process. BOOL bRet = CreateProcess(NULL, // No module name (use command line) test, // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE 0, // No creation flags NULL, // Use parent's environment block NULL, // Use parent's starting directory &si, // Pointer to STARTUPINFO structure &pi // Pointer to PROCESS_INFORMATION structure ); if(!bRet) { printf("CreateProcess failed (%d).\n", GetLastError()); return; } // Wait until child process exits. WaitForSingleObject(pi.hProcess, INFINITE); GetProcessId(_T("MicrosoftEdge.exe"), currentSessionId, &processId); // Close process and thread handles. CloseHandle(pi.hProcess); CloseHandle(pi.hThread); }
bool MSWindowsSession::isProcessInSession(const char* name, PHANDLE process = NULL) { // first we need to take a snapshot of the running processes HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (snapshot == INVALID_HANDLE_VALUE) { LOG((CLOG_ERR "could not get process snapshot")); throw XArch(new XArchEvalWindows()); } PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); // get the first process, and if we can't do that then it's // unlikely we can go any further BOOL gotEntry = Process32First(snapshot, &entry); if (!gotEntry) { LOG((CLOG_ERR "could not get first process entry")); throw XArch(new XArchEvalWindows()); } // used to record process names for debug info std::list<std::string> nameList; // now just iterate until we can find winlogon.exe pid DWORD pid = 0; while(gotEntry) { // make sure we're not checking the system process if (entry.th32ProcessID != 0) { DWORD processSessionId; BOOL pidToSidRet = ProcessIdToSessionId( entry.th32ProcessID, &processSessionId); if (!pidToSidRet) { // if we can not acquire session associated with a specified process, // simply ignore it LOG((CLOG_ERR "could not get session id for process id %i", entry.th32ProcessID)); gotEntry = nextProcessEntry(snapshot, &entry); continue; } else { // only pay attention to processes in the active session if (processSessionId == m_activeSessionId) { // store the names so we can record them for debug nameList.push_back(entry.szExeFile); if (_stricmp(entry.szExeFile, name) == 0) { pid = entry.th32ProcessID; } } } } // now move on to the next entry (if we're not at the end) gotEntry = nextProcessEntry(snapshot, &entry); } std::string nameListJoin; for(std::list<std::string>::iterator it = nameList.begin(); it != nameList.end(); it++) { nameListJoin.append(*it); nameListJoin.append(", "); } LOG((CLOG_DEBUG "processes in session %d: %s", m_activeSessionId, nameListJoin.c_str())); CloseHandle(snapshot); if (pid) { if (process != NULL) { // now get the process, which we'll use to get the process token. LOG((CLOG_DEBUG "found %s in session %i", name, m_activeSessionId)); *process = OpenProcess(MAXIMUM_ALLOWED, FALSE, pid); } return true; } else { LOG((CLOG_DEBUG "did not find %s in session %i", name, m_activeSessionId)); return false; } }
int WINAPI WinMain(HINSTANCE instance, HINSTANCE prev_instance, LPSTR cmdline, int cmdshow) { BOOL use_active_monitoring = DEFAULT_USE_ACTIVE_MONITORING; HMODULE hookdll; MSG msg; int check_counter; set_hooks_proc_t set_hooks_fn; remove_hooks_proc_t remove_hooks_fn; get_instance_count_proc_t instance_count_fn; g_instance = instance; load_configuration(&use_active_monitoring, &g_is_move_offscreen_forbidden); if (! use_active_monitoring) { hookdll = LoadLibrary("seamlessrdp.dll"); if (!hookdll) { message("Could not load hook DLL. Unable to continue."); return -1; } if (IsWow64()) { STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); // Start the child process. if (! CreateProcess(NULL, "hook_launcher_x64.exe", NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { message("CreateProcess failed.\n"); return -1; } CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } set_hooks_fn = (set_hooks_proc_t) GetProcAddress(hookdll, "SetHooks"); remove_hooks_fn = (remove_hooks_proc_t) GetProcAddress(hookdll, "RemoveHooks"); instance_count_fn = (get_instance_count_proc_t) GetProcAddress(hookdll, "GetInstanceCount"); if (!set_hooks_fn || !remove_hooks_fn || !instance_count_fn) { FreeLibrary(hookdll); message("Hook DLL doesn't contain the correct functions. Unable to continue."); return -1; } /* Check if the DLL is already loaded */ if (instance_count_fn() != 1) { FreeLibrary(hookdll); message("Another running instance of Seamless RDP detected."); return -1; } } ProcessIdToSessionId(GetCurrentProcessId(), &g_session_id); build_startup_procs(); if (! SeamlessChannel_init()) return -1; g_connected = is_connected(); g_desktop_hidden = is_desktop_hidden(); if (InternalWindow_create(instance, use_active_monitoring ? NULL : InternalWindow_processCopyData) == FALSE) SeamlessChannel_sendDebug("Failed to create seamless internal window"); SeamlessChannel_sendHello(g_desktop_hidden ? SEAMLESS_HELLO_HIDDEN : 0); if (use_active_monitoring) start_windows_monitoring(); else set_hooks_fn(); /* Since we don't see the entire desktop we must resize windows immediatly. */ SystemParametersInfo(SPI_SETDRAGFULLWINDOWS, TRUE, NULL, 0); /* Disable screen saver since we cannot catch its windows. */ SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, FALSE, NULL, 0); /* We don't want windows denying requests to activate windows. */ SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, 0, 0); check_counter = 5; while (1) { BOOL connected; char* line = NULL; int size = 0; connected = is_connected(); if (connected && !g_connected) { int flags; // We have to force reopening channel SeamlessChannel_uninit(); SeamlessChannel_init(); /* These get reset on each reconnect */ SystemParametersInfo(SPI_SETDRAGFULLWINDOWS, TRUE, NULL, 0); SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, FALSE, NULL, 0); SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, 0, 0); flags = SEAMLESS_HELLO_RECONNECT; if (g_desktop_hidden) flags |= SEAMLESS_HELLO_HIDDEN; SeamlessChannel_sendHello(flags); } g_connected = connected; if (check_counter < 0) { BOOL hidden; hidden = is_desktop_hidden(); if (hidden && !g_desktop_hidden) SeamlessChannel_sendHide(0); else if (!hidden && g_desktop_hidden) SeamlessChannel_sendUnhide(0); g_desktop_hidden = hidden; check_counter = 5; } while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } while (SeamlessChannel_recv(&line) >= 0) { SeamlessChannel_process(line); } Sleep(100); } if (use_active_monitoring) stop_windows_monitoring(); else { remove_hooks_fn(); FreeLibrary(hookdll); } SeamlessChannel_uninit(); free_startup_procs(); return 1; }
BOOL InjectDll(DWORD dwPID, char *szDllName) { HANDLE hProcess2 = NULL; LPVOID pRemoteBuf = NULL; FARPROC pThreadProc = NULL; PROCESS_INFORMATION pi; STARTUPINFO si; BOOL bResult = FALSE; DWORD dwSessionId = -1; DWORD winlogonPid = -1; HANDLE hUserToken,hUserTokenDup,hPToken,hProcess; DWORD dwCreationFlags; TCHAR wcQMountPath[256]; TCHAR wcQMountArgs[256]; memset(wcQMountPath,0,sizeof(wcQMountPath)); memset(wcQMountArgs,0,sizeof(wcQMountArgs)); //dwSessionId = WTSGetActiveConsoleSessionId(); HMODULE hModuleKern = LoadLibrary( TEXT("KERNEL32.dll") ); if( hModuleKern != NULL ) { DWORD (__stdcall *funcWTSGetActiveConsoleSessionId) (void); funcWTSGetActiveConsoleSessionId = (DWORD (__stdcall *)(void))GetProcAddress( hModuleKern, "WTSGetActiveConsoleSessionId" ); if( funcWTSGetActiveConsoleSessionId != NULL ) { dwSessionId = funcWTSGetActiveConsoleSessionId(); } } if( hModuleKern != NULL ) { // ¥í©`¥É¤·¤¿DLL¤ò½â·Å FreeLibrary( hModuleKern ); } OutputDebugStringA("LaunchAppIntoDifferentSession is called.\n"); // // Find the winlogon process // PROCESSENTRY32 procEntry; HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnap == INVALID_HANDLE_VALUE){ return FALSE; } procEntry.dwSize = sizeof(PROCESSENTRY32); if (!Process32First(hSnap, &procEntry)){ return FALSE; } do { if (stricmp(procEntry.szExeFile, "winlogon.exe") == 0) { // // We found a winlogon process...make sure it's running in the console session // DWORD winlogonSessId = 0; if (ProcessIdToSessionId(procEntry.th32ProcessID, &winlogonSessId) && winlogonSessId == dwSessionId){ winlogonPid = procEntry.th32ProcessID; break; } } } while (Process32Next(hSnap, &procEntry)); if (-1 == winlogonPid) { } //WTSQueryUserToken(dwSessionId,&hUserToken); BOOL (__stdcall *funcWTSQueryUserToken) (ULONG, PHANDLE); HMODULE hModuleWTS = LoadLibrary( TEXT("Wtsapi32.dll") ); if( hModuleWTS != NULL ) { BOOL (__stdcall *funcWTSQueryUserToken) (ULONG, PHANDLE); funcWTSQueryUserToken = (BOOL (__stdcall *)(ULONG, PHANDLE))GetProcAddress( hModuleWTS, "WTSQueryUserToken" ); if( funcWTSQueryUserToken != NULL ) { funcWTSQueryUserToken(dwSessionId,&hUserToken); } } if( hModuleWTS != NULL ) { // ¥í©`¥É¤·¤¿DLL¤ò½â·Å FreeLibrary( hModuleKern ); } dwCreationFlags = NORMAL_PRIORITY_CLASS|CREATE_NEW_CONSOLE; ZeroMemory(&si, sizeof(STARTUPINFO)); si.cb= sizeof(STARTUPINFO); si.lpDesktop = "winsta0\\default"; ZeroMemory(&pi, sizeof(pi)); TOKEN_PRIVILEGES tp; LUID luid; hProcess = OpenProcess(MAXIMUM_ALLOWED,FALSE,winlogonPid); if( !::OpenProcessToken(hProcess, TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY|TOKEN_DUPLICATE| TOKEN_ASSIGN_PRIMARY|TOKEN_ADJUST_SESSIONID|TOKEN_READ|TOKEN_WRITE, &hPToken)) { //OutputDebugPrintf("Failed[LaunchAppIntoDifferentSession]: OpenProcessToken(Error=%d)\n",GetLastError()); } if (!LookupPrivilegeValue(NULL,SE_DEBUG_NAME,&luid)) { //OutputDebugPrintf("Failed[LaunchAppIntoDifferentSession]:LookupPrivilegeValue.(Error=%d)\n",GetLastError()); } tp.PrivilegeCount =1; tp.Privileges[0].Luid =luid; tp.Privileges[0].Attributes =SE_PRIVILEGE_ENABLED; DuplicateTokenEx(hPToken,MAXIMUM_ALLOWED,NULL,SecurityIdentification,TokenPrimary,&hUserTokenDup); int dup = GetLastError(); // //Adjust Token privilege // SetTokenInformation(hUserTokenDup,TokenSessionId,(void*)dwSessionId,sizeof(DWORD)); if (!AdjustTokenPrivileges(hUserTokenDup,FALSE,&tp,sizeof(TOKEN_PRIVILEGES),(PTOKEN_PRIVILEGES)NULL,NULL)) { //OutputDebugPrintf("Failed[LaunchAppIntoDifferentSession]: AdjustTokenPrivileges.(Error=%d)\n",GetLastError()); } if (GetLastError()== ERROR_NOT_ALL_ASSIGNED) { //OutputDebugPrintf("Failed[LaunchAppIntoDifferentSession]: Token does not have the provilege\n"); } LPVOID pEnv =NULL; if(CreateEnvironmentBlock(&pEnv,hUserTokenDup,TRUE)){ dwCreationFlags |= CREATE_UNICODE_ENVIRONMENT; } else { pEnv=NULL; } DWORD dwBufSize = strlen(szDllName)+1; if ( !(hProcess2 = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID)) ) { printf("[´íÎó] OpenProcess(%d) µ÷ÓÃʧ°Ü£¡´íÎó´úÂë: [%d]/n", dwPID, GetLastError()); return FALSE; } pRemoteBuf = VirtualAllocEx(hProcess, NULL, dwBufSize, MEM_COMMIT, PAGE_READWRITE); WriteProcessMemory(hProcess, pRemoteBuf, (LPVOID)szDllName, dwBufSize, NULL); pThreadProc = GetProcAddress(GetModuleHandle("kernel32.dl"), "LoadLibraryA"); if( !MyCreateRemoteThread(hProcess, (LPTHREAD_START_ROUTINE)pThreadProc, pRemoteBuf) ) { printf("[´íÎó] CreateRemoteThread() µ÷ÓÃʧ°Ü£¡´íÎó´úÂë: [%d]/n", GetLastError()); return FALSE; } VirtualFreeEx(hProcess2, pRemoteBuf, 0, MEM_RELEASE); CloseHandle(hProcess2); CloseHandle(hProcess); CloseHandle(hUserToken); CloseHandle(hUserTokenDup); CloseHandle(hPToken); return TRUE; }