bool InputDesktopSelected()
{

	DWORD dummy;
	char threadname[256];
	char inputname[256];
	HDESK threaddesktop = GetThreadDesktop(GetCurrentThreadId());
	HDESK inputdesktop = OpenInputDesktop(0, FALSE,
				DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW |
				DESKTOP_ENUMERATE | DESKTOP_HOOKCONTROL |
				DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS |
				DESKTOP_SWITCHDESKTOP | GENERIC_WRITE);

	if (inputdesktop == NULL) return FALSE;
	if (!GetUserObjectInformation(threaddesktop, UOI_NAME, &threadname, 256, &dummy)) {
			CloseDesktop(inputdesktop);
			return FALSE;
		}
	if (!GetUserObjectInformation(inputdesktop, UOI_NAME, &inputname, 256, &dummy)) {
			CloseDesktop(inputdesktop);
			return FALSE;
		}	
	CloseDesktop(inputdesktop);
	
	if (strcmp(threadname, inputname) != 0)
		{
			//if (strcmp(inputname, "Screen-saver") == 0)
			{
				return SelectDesktop();
			}
			return FALSE;
		}
	return TRUE;
}
Beispiel #2
1
BOOL
vncService::SelectHDESK(HDESK new_desktop)
{
	// Are we running on NT?
	if (IsWinNT())
	{
		HDESK old_desktop = GetThreadDesktop(GetCurrentThreadId());

		DWORD dummy;
		char new_name[256];

		if (!GetUserObjectInformation(new_desktop, UOI_NAME, &new_name, 256, &dummy)) {

			return FALSE;
		}



		// Switch the desktop
		if(!SetThreadDesktop(new_desktop)) {

			return FALSE;
		}

		// Switched successfully - destroy the old desktop
		CloseDesktop(old_desktop);

		return TRUE;
	}

	return TRUE;
}
BOOL
vncService::SelectHDESK(HDESK new_desktop)
{
	// Are we running on NT?
	if (IsWinNT())
	{
		HDESK old_desktop = GetThreadDesktop(GetCurrentThreadId());

		DWORD dummy;
		char new_name[256];

		if (!GetUserObjectInformation(new_desktop, UOI_NAME, &new_name, 256, &dummy)) {
			vnclog.Print(LL_INTERR, VNCLOG("!GetUserObjectInformation \n"));
			return FALSE;
		}

		vnclog.Print(LL_INTERR, VNCLOG("SelectHDESK to %s (%x) from %x\n"), new_name, new_desktop, old_desktop);

		// Switch the desktop
		if(!SetThreadDesktop(new_desktop)) {
			vnclog.Print(LL_INTERR, VNCLOG("SelectHDESK:!SetThreadDesktop \n"));
			return FALSE;
		}

		return TRUE;
	}

	return TRUE;
}
Beispiel #4
0
bool SwitchInputDesktop()
{
    BOOL	bRet = false;
    DWORD	dwLengthNeeded;

    HDESK	hOldDesktop, hNewDesktop;
    char	strCurrentDesktop[256], strInputDesktop[256];

    hOldDesktop = GetThreadDesktop(GetCurrentThreadId());
    memset(strCurrentDesktop, 0, sizeof(strCurrentDesktop));
    GetUserObjectInformation(hOldDesktop, UOI_NAME, &strCurrentDesktop, sizeof(strCurrentDesktop), &dwLengthNeeded);


    hNewDesktop = OpenInputDesktop(0, FALSE, MAXIMUM_ALLOWED);
    memset(strInputDesktop, 0, sizeof(strInputDesktop));
    GetUserObjectInformation(hNewDesktop, UOI_NAME, &strInputDesktop, sizeof(strInputDesktop), &dwLengthNeeded);

    if (lstrcmpi(strInputDesktop, strCurrentDesktop) != 0)
    {
        SetThreadDesktop(hNewDesktop);
        bRet = true;
    }
    CloseDesktop(hOldDesktop);

    CloseDesktop(hNewDesktop);


    return bRet;
}
// get the current input desktop name and compare with 
// the desktop the call thread attached ,if not equal,
// then switch to the input desktop
BOOL SwitchInputDesktop()
{
	
	
	HDESK threaddesk = GetThreadDesktop(GetCurrentThreadId());
	HDESK inputdesk  = OpenInputDesktop(0, DF_ALLOWOTHERACCOUNTHOOK,GENERIC_ALL);

	if (inputdesk == NULL)
	{
		DebugOutF(filelog::log_error,("OpenInputDesktop failed with %d"),GetLastError());
		return FALSE;
	}
	DWORD len=0;
	TCHAR szThread[MAX_PATH];
	TCHAR szInput[MAX_PATH];
	szThread[0] = _T('\0');
	szInput[0] = _T('\0');
	BOOL res = FALSE;
	try
	{
		// get desktop name
		if(!GetUserObjectInformation(threaddesk, UOI_NAME, szThread, MAX_PATH, &len)){
			DebugOutF(filelog::log_error,("GetUserObjectInformation failed with %d"),GetLastError());
			throw FALSE;
		}
		if (!GetUserObjectInformation(inputdesk, UOI_NAME, szInput, MAX_PATH, &len)) {
			DebugOutF(filelog::log_error,("GetUserObjectInformation failed with %d"),GetLastError());
			throw FALSE;
		}
		//compare,if not equal,then switch to the input desktop 
		if (_tcsicmp(szThread, szInput) != 0)
		{

			if(!SetThreadDesktop(inputdesk)){
				DebugOutF(filelog::log_error,("SetThreadDesktop %s failed with %d"),szInput,GetLastError());
				throw FALSE;
			}
			DebugOutF(filelog::log_info,("switch input desktop %s"),szInput);
			res = TRUE;

		}
	}
	catch(BOOL b1)
	{
		res = b1;
	}
	if(threaddesk)CloseDesktop(threaddesk);
	if(inputdesk)CloseDesktop(inputdesk);
	return res;
}
Beispiel #6
0
static PPH_STRING GetCurrentWinStaName(
    VOID
    )
{
    PPH_STRING string;

    string = PhCreateStringEx(NULL, 0x200);

    if (GetUserObjectInformation(
        GetProcessWindowStation(),
        UOI_NAME,
        string->Buffer,
        (ULONG)string->Length + 2,
        NULL
        ))
    {
        PhTrimToNullTerminatorString(string);
        return string;
    }
    else
    {
        PhDereferenceObject(string);
        return PhCreateString(L"WinSta0"); // assume the current window station is WinSta0
    }
}
Beispiel #7
0
BOOL
vncService::SelectHDESK(HDESK new_desktop)
{
	// Are we running on NT?
	if (IsWinNT())
	{
		HDESK old_desktop = GetThreadDesktop(GetCurrentThreadId());
		//You do not need to call the CloseDesktop function to close the returned handle.

		DWORD dummy;
		char new_name[256];

		if (!GetUserObjectInformation(new_desktop, UOI_NAME, &new_name, 256, &dummy)) {
			return FALSE;
		}

		//vnclog.Print(LL_INTERR, VNCLOG("SelectHDESK to %s (%x) from %x\n"), new_name, new_desktop, old_desktop);
		
		// Switch the desktop
		if(!SetThreadDesktop(new_desktop)) 
		{
			return FALSE;
		}

		return TRUE;
	}

	return TRUE;
}
Beispiel #8
0
BOOL
vncService::SelectHDESK(HDESK new_desktop)
{
	// Are we running on NT?
	if (IsWinNT())
	{
		HDESK old_desktop = GetThreadDesktop(GetCurrentThreadId());

		DWORD dummy;
		char new_name[256];

		if (!GetUserObjectInformation(new_desktop, UOI_NAME, &new_name, 256, &dummy)) {
			vnclog.Print(LL_INTERR, VNCLOG("GetUserObjectInformation() failed\n"));
			return FALSE;
		}

		vnclog.Print(LL_INTINFO, VNCLOG("SelectHDESK() to %s (%x) from %x\n"),
					 new_name, new_desktop, old_desktop);

		// Switch the desktop
		if(!SetThreadDesktop(new_desktop)) {
			vnclog.Print(LL_INTERR, VNCLOG("unable to SetThreadDesktop(), error=%d\n"), GetLastError());
			return FALSE;
		}

		// Switched successfully - destroy the old desktop
		if (!CloseDesktop(old_desktop))
			vnclog.Print(LL_INTERR, VNCLOG("SelectHDESK failed to close old desktop %x, error=%d\n"), old_desktop, GetLastError());

		return TRUE;
	}

	return TRUE;
}
bool SelectDesktop()
{
		HDESK desktop;
		HDESK old_desktop;
		DWORD dummy;
		char new_name[256];
		desktop = OpenInputDesktop(0, FALSE,
				DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW |
				DESKTOP_ENUMERATE | DESKTOP_HOOKCONTROL |
				DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS |
				DESKTOP_SWITCHDESKTOP | GENERIC_WRITE);
		if (desktop == NULL) return FALSE;
		old_desktop = GetThreadDesktop(GetCurrentThreadId());
		if (!GetUserObjectInformation(desktop, UOI_NAME, &new_name, 256, &dummy)) {
			CloseDesktop(desktop);
			return FALSE;
		}
		if(!SetThreadDesktop(desktop)) {
			CloseDesktop(desktop);
			return FALSE;
		}
		CloseDesktop(old_desktop);			
		return TRUE;

}
/*
 * Create the Metasploit Courtesy Shell
 */
VOID vncdll_courtesyshell( HDESK desk )
{
	DWORD dwResult         = ERROR_SUCCESS;
	HWND hShell            = NULL;
	STARTUPINFOA si        = {0};
	PROCESS_INFORMATION pi = {0};
	char name_win[256]     = {0};
	char name_des[256]     = {0};
	char name_all[1024]    = {0};
	
	do
	{
		dprintf( "[VNCDLL] vncdll_courtesyshell. desk=0x%08X", desk );

		memset(name_all, 0, sizeof(name_all));

		GetUserObjectInformation( GetProcessWindowStation(), UOI_NAME, &name_win, 256, NULL );
		GetUserObjectInformation( desk, UOI_NAME, &name_des, 256, NULL );

		_snprintf( name_all, sizeof(name_all)-1, "%s\\%s", name_win, name_des );

		memset( &pi, 0, sizeof(PROCESS_INFORMATION) );
		memset( &si, 0, sizeof(STARTUPINFOA) );

		si.cb              = sizeof(STARTUPINFOA);
		si.dwFlags         = STARTF_USESHOWWINDOW | STARTF_USEFILLATTRIBUTE;
		si.wShowWindow     = SW_NORMAL;
		si.lpDesktop       = name_all;
		si.lpTitle         = "Metasploit Courtesy Shell (TM)";
		si.dwFillAttribute = FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_GREEN|BACKGROUND_BLUE;
		
		if( !CreateProcess( NULL, "cmd.exe", 0, 0, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi ) )
			BREAK_ON_ERROR( "[VNCDLL] vncdll_courtesyshell. CreateProcess failed" );

		CloseHandle( pi.hThread );
		CloseHandle( pi.hProcess );
			
		Sleep( 1000 );
		
		hShell = FindWindow( NULL, "Metasploit Courtesy Shell (TM)" );
		if( !hShell )
			break;

		SetWindowPos( hShell, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE );

	} while( 0 );
}
Beispiel #11
0
BOOL kull_m_handle_GetUserObjectInformation(HANDLE hObj, int nIndex, PVOID *pvInfo, PDWORD nLength)
{
	BOOL status = FALSE;
	DWORD szNeeded;

	if(!GetUserObjectInformation(hObj, nIndex, NULL, 0, &szNeeded) && (GetLastError() == ERROR_INSUFFICIENT_BUFFER) && szNeeded)
	{
		if(*pvInfo = LocalAlloc(LPTR, szNeeded))
		{
			if(nLength)
				*nLength = szNeeded;
			if(!(status = GetUserObjectInformation(hObj, nIndex, *pvInfo, szNeeded, &szNeeded)))
				LocalFree(*pvInfo);
		}
	}
	return status;
}
Beispiel #12
0
BOOL
vncService::InputDesktopSelected()
{
	// Are we running on NT?
	if (IsWinNT())
	{
		// Get the input and thread desktops
		HDESK threaddesktop = GetThreadDesktop(GetCurrentThreadId());
		HDESK inputdesktop = OpenInputDesktop(0, FALSE,
				DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW |
				DESKTOP_ENUMERATE | DESKTOP_HOOKCONTROL |
				DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS |
				DESKTOP_SWITCHDESKTOP | GENERIC_WRITE);

		if (inputdesktop == NULL) {
			// Returning TRUE on ERROR_BUSY fixes the bug #1109102.
			// FIXME: Probably this is not the most correct way to do it.
			return (GetLastError() == ERROR_BUSY) ? TRUE : FALSE;
		}

		DWORD dummy;
		char threadname[256];
		char inputname[256];

		if (!GetUserObjectInformation(threaddesktop, UOI_NAME, &threadname, 256, &dummy)) {
			if (!CloseDesktop(inputdesktop))
				vnclog.Print(LL_INTWARN, VNCLOG("failed to close input desktop\n"));
			return FALSE;
		}
		_ASSERT(dummy <= 256);
		if (!GetUserObjectInformation(inputdesktop, UOI_NAME, &inputname, 256, &dummy)) {
			if (!CloseDesktop(inputdesktop))
				vnclog.Print(LL_INTWARN, VNCLOG("failed to close input desktop\n"));
			return FALSE;
		}
		_ASSERT(dummy <= 256);

		if (!CloseDesktop(inputdesktop))
			vnclog.Print(LL_INTWARN, VNCLOG("failed to close input desktop\n"));

		if (strcmp(threadname, inputname) != 0)
			return FALSE;
	}

	return TRUE;
}
Beispiel #13
0
void TitleWindow (HWND hWnd)
{
   TCHAR *szTitle, *szName;
   UINT nBytes = 0;

   //
   // How long is the desktop name?
   //
   GetUserObjectInformation (GetThreadDesktop(GetCurrentThreadId()),
                             UOI_NAME,
                             (LPVOID)&nBytes, // not used since cbInfo is 0
                             0,
                             &nBytes);
   szName = (LPTSTR)GlobalAlloc (GPTR, nBytes);
   if (!szName)
   {
      return;
   }
   //
   // Now get the desktop name
   //
   GetUserObjectInformation (GetThreadDesktop(GetCurrentThreadId()),
                             UOI_NAME,
                             (LPVOID)szName,
                             nBytes,
                             &nBytes);
   //
   // Now make the window title
   //
   szTitle = (LPTSTR)GlobalAlloc (
           GPTR,
           (lstrlen(szAppName)+lstrlen(TEXT(" - "))) * sizeof(TCHAR) + nBytes);

   if (!szTitle)
   {
      GlobalFree (szName);
      return;
   }
   wsprintf (szTitle, TEXT("%s - %s"), szAppName, szName);
   SetWindowText (hWnd, szTitle);
   //
   // Cleanup
   //
   GlobalFree (szName);
   GlobalFree (szTitle);
}
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;
}
bool Opc_client_ae_DriverThread::StartProcess(char* pCommandLine, char* pWorkingDir)
{ 
	STARTUPINFO startUpInfo = { sizeof(STARTUPINFO),NULL,"",NULL,0,0,0,0,0,0,0,STARTF_USESHOWWINDOW,0,0,NULL,0,0,0};  

	nIndex = 1;
	
	if(strlen(pCommandLine) > 4)
	{
		char pUserInterface[nBufferSize+1];

		//printf("%s\n", pCommandLine);
		
		strcpy(pUserInterface, "Y");

		BOOL bUserInterface = (pUserInterface[0]=='y'||pUserInterface[0]=='Y'||pUserInterface[0]=='1')?TRUE:FALSE;
		char CurrentDesktopName[512];

		// set the correct desktop for the process to be started
		if(bUserInterface)
		{
			//startUpInfo.wShowWindow = SW_SHOW;
			startUpInfo.wShowWindow = SW_SHOWMINIMIZED;
			startUpInfo.lpDesktop = NULL;
		}
		else
		{
			HDESK hCurrentDesktop = GetThreadDesktop(GetCurrentThreadId());
			DWORD len;

			GetUserObjectInformation(hCurrentDesktop,UOI_NAME,CurrentDesktopName,MAX_PATH,&len);
			startUpInfo.wShowWindow = SW_HIDE;
			startUpInfo.lpDesktop = CurrentDesktopName;
		}

		// create the process

		DWORD dwCreateFlg  = 0;
		dwCreateFlg |= CREATE_NEW_CONSOLE;

		memset(pProcInfo + nIndex, 0, sizeof(PROCESS_INFORMATION));

		if(CreateProcess(NULL,pCommandLine,NULL,NULL,TRUE,dwCreateFlg,NULL,strlen(pWorkingDir)==0?NULL:pWorkingDir,&startUpInfo,pProcInfo + nIndex))
		{
			Sleep(100);
			return TRUE;
		}
		else
		{
			fprintf(stderr,"Failed to start program '%s', error code = %d\n", pCommandLine, GetLastError());
			fflush(stderr);
			return FALSE;
		}
	}
	else
	{
		return FALSE;
	}
}
Beispiel #16
0
bool DesktopSelector::getDesktopName(HDESK desktop, StringStorage *desktopName)
{
  DWORD nameLength;
  GetUserObjectInformation(desktop, UOI_NAME, 0, 0, &nameLength);

  TCHAR *name = new TCHAR[nameLength];

  bool result = GetUserObjectInformation(desktop,
                                         UOI_NAME,
                                         name,
                                         nameLength,
                                         0) != 0;
  if (result) {
    desktopName->setString(name);
  }
  delete[] name;
  return result;
}
Beispiel #17
0
static void KillWallpaper()
{
	//only kill wallpaper if desktop is user desktop
	HDESK desktop = GetThreadDesktop(GetCurrentThreadId());
	DWORD dummy;
	char new_name[256];
	if (GetUserObjectInformation(desktop, UOI_NAME, &new_name, 256, &dummy))
	{
		if (strcmp(new_name,"Default")==NULL) HideDesktop();
	}	
}
Beispiel #18
0
void
vncDesktop::StartInitWindowthread()
{
	// Check if the input desktop == Default desktop
	// Hooking the winlogon is not needed, no clipboard
	// see if the threaddesktop== Default
	HDESK desktop = GetThreadDesktop(GetCurrentThreadId());
	DWORD dummy;
	char new_name[256];
	can_be_hooked=false;
	vnclog.Print(LL_INTINFO, VNCLOG("StartInitWindowthread \n"));
	if (GetUserObjectInformation(desktop, UOI_NAME, &new_name, 256, &dummy))
	{
		if (strcmp(new_name,"Default")==0)
		{
			vnclog.Print(LL_INTINFO, VNCLOG("StartInitWindowthread default desk\n"));
			if (InitWindowThreadh==NULL)
			{
				ResetEvent(restart_event);
				InitWindowThreadh=CreateThread(NULL,0,InitWindowThread,this,0,&pumpID);
				DWORD status=WaitForSingleObject(restart_event,10000);
				if (status==WAIT_TIMEOUT)
				{
					vnclog.Print(LL_INTINFO, VNCLOG("ERROR: initwindowthread failed to start \n"));
					if (InitWindowThreadh!=NULL)
					{
						TerminateThread(InitWindowThreadh,0);
						CloseHandle(InitWindowThreadh);
						m_hwnd=NULL;
						InitWindowThreadh=NULL;
					}
					can_be_hooked=false;
				}
				else
				{
					vnclog.Print(LL_INTINFO, VNCLOG("StartInitWindowthread started\n"));
					can_be_hooked=true;
				}
			}
			else
			{
				// initwindowthread is still running
				// make it back active
				vnclog.Print(LL_INTINFO, VNCLOG("StartInitWindowthread reactivate\n"));
				can_be_hooked=true;
			}
		}
		else
		{
			vnclog.Print(LL_INTINFO, VNCLOG("StartInitWindowthread no default desk\n"));
		}
	}
}
String
MSWindowsSession::getActiveDesktopName()
{
	String result;
	try {
		HDESK hd = OpenInputDesktop(0, TRUE, GENERIC_READ);
		if (hd != NULL) {
			DWORD size;
			GetUserObjectInformation(hd, UOI_NAME, NULL, 0, &size);
			TCHAR* name = (TCHAR*)alloca(size + sizeof(TCHAR));
			GetUserObjectInformation(hd, UOI_NAME, name, size, &size);
			result = name;
			CloseDesktop(hd);
		}
	}
	catch (std::exception error) {
		LOG((CLOG_ERR "failed to get active desktop name: %s", error.what()));
	}

	return result;
}
DWORD WINAPI BlackWindow(LPVOID lpParam)
{
 	// TODO: Place code here.
	HDESK desktop;
	desktop = OpenInputDesktop(0, FALSE,
								DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW |
								DESKTOP_ENUMERATE | DESKTOP_HOOKCONTROL |
								DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS |
								DESKTOP_SWITCHDESKTOP | GENERIC_WRITE
								);

	if (desktop == NULL)
		vnclog.Print(LL_INTERR, VNCLOG("OpenInputdesktop Error \n"));
	else 
		vnclog.Print(LL_INTERR, VNCLOG("OpenInputdesktop OK\n"));

	HDESK old_desktop = GetThreadDesktop(GetCurrentThreadId());
	DWORD dummy;

	char new_name[256];
	if (desktop)
	{
		if (!GetUserObjectInformation(desktop, UOI_NAME, &new_name, 256, &dummy))
		{
			vnclog.Print(LL_INTERR, VNCLOG("!GetUserObjectInformation \n"));
		}

		vnclog.Print(LL_INTERR, VNCLOG("SelectHDESK to %s (%x) from %x\n"), new_name, desktop, old_desktop);

		if (!SetThreadDesktop(desktop))
		{
			vnclog.Print(LL_INTERR, VNCLOG("SelectHDESK:!SetThreadDesktop \n"));
		}
	}

	create_window();
	MSG msg;
	while (GetMessage(&msg,0,0,0) != 0)
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	vnclog.Print(LL_INTERR, VNCLOG("end BlackWindow \n"));
	SetThreadDesktop(old_desktop);
	if (desktop) CloseDesktop(desktop);

	return 0;
}
Beispiel #21
0
void RunApp (HWND hWnd)
{
   TCHAR szDesk[100];          // data holder
   TCHAR szExec[100];       // Command line
   STARTUPINFO sui;         // Process startup info
   PROCESS_INFORMATION pi;  // info returned from CreateProcess
   ThreadData *ptd;

   ptd = (ThreadData*)GetWindowLong (hWnd, GWL_USERDATA);
   //
   // Most sui members will be 0
   //
   ZeroMemory ((PVOID)&sui, sizeof(sui));
   //
   //Get the command line to execute
   //
   GetDlgItemText (hWnd, IDC_RUNME, szExec, 100*sizeof(TCHAR));
   //
   //Get the current desktop name
   //
   GetUserObjectInformation (GetThreadDesktop (GetCurrentThreadId()),
                             UOI_NAME,
                             szDesk,
                             100*sizeof(TCHAR),
                             NULL);
   sui.cb = sizeof (sui);
   //
   // Need the lpDesktop member so the new process runs on this desktop
   // The lpDesktop member was reserved in previous versions of NT
   //
   sui.lpDesktop = szDesk;
   CreateProcess (NULL,   // image name
                  szExec, // command line
                  NULL,   // process security attributes
                  NULL,   // thread security attributes
                  TRUE,   // inherit handles
                  CREATE_DEFAULT_ERROR_MODE|CREATE_SEPARATE_WOW_VDM,
                  NULL,   // environment block
                  NULL,   // current directory
                  &sui,   // STARTUPINFO
                  &pi);   // PROCESS_INFORMATION

}
Beispiel #22
0
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;
}
Beispiel #23
0
/*
* propBasicQueryWindowStation
*
* Purpose:
*
* Set information values for WindowStation object type (managed by win32k services)
*
* If ExtendedInfoAvailable is FALSE then it calls propSetDefaultInfo to set Basic page properties
*
*/
VOID propBasicQueryWindowStation(
    _In_ PROP_OBJECT_INFO *Context,
    _In_ HWND hwndDlg,
    _In_ BOOL ExtendedInfoAvailable
)
{
    DWORD           bytesNeeded;
    HWINSTA         hObject;
    USEROBJECTFLAGS userFlags;

    SetDlgItemText(hwndDlg, ID_WINSTATIONVISIBLE, T_CannotQuery);

    if (Context == NULL) {
        return;
    }

    //
    // Open Winstation object.
    //
    hObject = NULL;
    if (!propOpenCurrentObject(Context, &hObject, WINSTA_READATTRIBUTES)) {
        return;
    }

    RtlSecureZeroMemory(&userFlags, sizeof(userFlags));
    if (GetUserObjectInformation(hObject, UOI_FLAGS, &userFlags,
        sizeof(USEROBJECTFLAGS), &bytesNeeded))
    {
        SetDlgItemText(hwndDlg, ID_WINSTATIONVISIBLE,
            (userFlags.dwFlags & WSF_VISIBLE) ? TEXT("Yes") : TEXT("No"));
    }

    //
    // Query object basic and type info if needed.
    //
    if (ExtendedInfoAvailable == FALSE) {
        propSetDefaultInfo(Context, hwndDlg, hObject);
    }
    CloseWindowStation(hObject);
}
Beispiel #24
0
//}}
//************************************************************************
int APIENTRY WinMain(HINSTANCE a_hInstance,
                     HINSTANCE,
                     LPSTR a_pszCmd,
                     int a_nCount)
{
    Util::TCommandLineInfo cmdLine(a_pszCmd);

    switch(cmdLine.m_eCommand)
    {
        case Util::TCommandLineInfo::eDebug:
            return RunAsApplication(a_hInstance);

		case Util::TCommandLineInfo::eInstall:
			return Service::Install() ? 0 : -1;

		case Util::TCommandLineInfo::eUnInstall:
			return Service::UnInstall() ? 0 : -1;

		case Util::TCommandLineInfo::eStart:
		{
			if(Service::Run())
				return 0;

			if (GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
				return RunAsApplication(a_hInstance);
		}

        case Util::TCommandLineInfo::eStop:
            return StopServer();
    }

    char buffer[256] = {0};
    DWORD length = 0;
    GetUserObjectInformation(GetProcessWindowStation(), UOI_NAME, buffer, 256, &length);
    if (stricmp(buffer, "WinSta0") == 0) 
    {
        MessageBox(NULL, "No argument", "Error", MB_ICONSTOP);
    }
    return 0;
}
BOOL vncService::IsWSLocked()
{
	if (!IsWinNT()) 
		return false;

	bool bLocked = false;


	HDESK hDesk;
	BOOL bRes;
	DWORD dwLen;
	char sName[200];
	
	hDesk = OpenInputDesktop(0, FALSE, 0);

	if (hDesk == NULL)
	{
		 bLocked = true;
	}
	else 
	{
		bRes = GetUserObjectInformation(hDesk, UOI_NAME, sName, sizeof(sName), &dwLen);

		if (bRes)
			sName[dwLen]='\0';
		else
			sName[0]='\0';


		if (_stricmp(sName,"Default") != 0)
			 bLocked = true; // WS is locked or screen saver active
		else
			 bLocked = false ;
	}
	if (hDesk != NULL)
		CloseDesktop(hDesk);

	return bLocked;
}
Beispiel #26
0
/*
* DesktopListEnumProc
*
* Purpose:
*
* EnumDesktops callback.
*
*/
BOOL CALLBACK DesktopListEnumProc(
	_In_  LPWSTR lpszDesktop,
	_In_  LPARAM lParam
	)
{
	PROP_OBJECT_INFO *Context;

	BOOL		bSucc;
	INT			nIndex;
	DWORD		bytesNeeded, dwDesktopHeapSize;
	LPWSTR		lpName;
	PSID		pSID;
	SIZE_T		sz;
	HDESK		hDesktop;
	LPWSTR		StringSid;
	LVITEMW		lvitem;
	WCHAR		szBuffer[MAX_PATH];

	Context = (PROP_OBJECT_INFO*)lParam;
	if (Context == NULL) {
		return FALSE;
	}

	sz = (_strlen(lpszDesktop) * sizeof(WCHAR)) +
		(_strlen(Context->lpObjectName) * sizeof(WCHAR)) +
		(2 * sizeof(WCHAR)) + sizeof(UNICODE_NULL);

	lpName = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sz);
	//not enough memory? cancel enum
	if (lpName == NULL) {
		return 0;
	}
	
	_strcpy(lpName, Context->lpObjectName);
	_strcat(lpName, L"\\");
	_strcat(lpName, lpszDesktop);

	//Name
	RtlSecureZeroMemory(&lvitem, sizeof(lvitem));
	lvitem.mask = LVIF_TEXT | LVIF_IMAGE;
	lvitem.iImage = 0;
	lvitem.iSubItem = 0;
	lvitem.pszText = lpName;
	lvitem.iItem = MAXINT;
	nIndex = ListView_InsertItem(DesktopList, &lvitem);

	HeapFree(GetProcessHeap(), 0, lpName);

	//Query desktop objects information
	bSucc = FALSE;
	StringSid = NULL;
	hDesktop = OpenDesktop(lpszDesktop, 0, FALSE, DESKTOP_READOBJECTS);
	if (hDesktop) {

		//Query SID
		bytesNeeded = 0;
		GetUserObjectInformation(hDesktop, UOI_USER_SID, NULL, 0, &bytesNeeded);
		//user associated with desktop present, query sid
		if (bytesNeeded) {
			//allocate memory for sid
			pSID = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, bytesNeeded);
			if (pSID) {
				if (GetUserObjectInformation(hDesktop,
					UOI_USER_SID, pSID, bytesNeeded, &bytesNeeded))
				{
					bSucc = ConvertSidToStringSid(pSID, &StringSid);
				}
				HeapFree(GetProcessHeap(), 0, pSID);
			}
		}

		//Add SID string to the list
		if (bSucc && StringSid) {
			lvitem.mask = LVIF_TEXT;
			lvitem.iSubItem = 1;
			lvitem.pszText = StringSid;
			lvitem.iItem = nIndex;
			ListView_SetItem(DesktopList, &lvitem);
			LocalFree(StringSid);
		}

		//Add Desktop Heap Size, returned in KBytes
		dwDesktopHeapSize = 0;
		if (GetUserObjectInformation(hDesktop, UOI_HEAPSIZE,
			&dwDesktopHeapSize, sizeof(dwDesktopHeapSize), &bytesNeeded)) {

			RtlSecureZeroMemory(szBuffer, sizeof(szBuffer));
			ultostr(dwDesktopHeapSize / 1024, szBuffer);
			_strcat(szBuffer, L" Mb");

			lvitem.mask = LVIF_TEXT;
			lvitem.iSubItem = 2;
			lvitem.pszText = szBuffer;
			lvitem.iItem = nIndex;
			ListView_SetItem(DesktopList, &lvitem);
		}
		CloseDesktop(hDesktop);
	}
	return TRUE;
}
Beispiel #27
0
/*
 * Setup and run the server. This is called from Init via the loader.
 */
DWORD server_setup( SOCKET fd )
{
	Remote * remote        = NULL;
	char cStationName[256] = {0};
	char cDesktopName[256] = {0};
	DWORD res              = 0;

	dprintf("[SERVER] Initializing...");

#ifdef _UNIX
	int local_error = 0;
#endif

	// if hAppInstance is still == NULL it means that we havent been
	// reflectivly loaded so we must patch in the hAppInstance value
	// for use with loading server extensions later.
	InitAppInstance();

	srand( (unsigned int)time(NULL) );
	
	__try 
	{
		do
		{
			dprintf( "[SERVER] module loaded at 0x%08X", hAppInstance );
			
			// Open a THREAD item for the servers main thread, we use this to manage migration later.
			serverThread = thread_open();

			dprintf( "[SERVER] main server thread: handle=0x%08X id=0x%08X sigterm=0x%08X", serverThread->handle, serverThread->id, serverThread->sigterm );

			if( !(remote = remote_allocate(fd)) )
			{
				SetLastError( ERROR_NOT_ENOUGH_MEMORY );
				break;
			}

			remote->url = global_meterpreter_url;

			if (strcmp(global_meterpreter_transport+12, "TRANSPORT_SSL") == 0) {
				remote->transport = METERPRETER_TRANSPORT_SSL;
				dprintf("[SERVER] Using SSL transport...");
			} else if (strcmp(global_meterpreter_transport+12, "TRANSPORT_HTTPS") == 0) {
				remote->transport = METERPRETER_TRANSPORT_HTTPS;
				dprintf("[SERVER] Using HTTPS transport...");
			} else if (strcmp(global_meterpreter_transport+12, "TRANSPORT_HTTP") == 0) {
				remote->transport = METERPRETER_TRANSPORT_HTTP;
				dprintf("[SERVER] Using HTTP transport...");
			}

			// Do not allow the file descriptor to be inherited by child processes
			SetHandleInformation((HANDLE)fd, HANDLE_FLAG_INHERIT, 0);

			dprintf("[SERVER] Initializing tokens...");

			// Store our thread handle
			remote->hServerThread = serverThread->handle;

#ifdef _WIN32
			// Store our process token
			if (!OpenThreadToken(remote->hServerThread, TOKEN_ALL_ACCESS, TRUE, &remote->hServerToken))
				OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &remote->hServerToken);

			// Copy it to the thread token
			remote->hThreadToken = remote->hServerToken;

			// Save the initial session/station/desktop names...
			remote->dwOrigSessionId      = server_sessionid();
			remote->dwCurrentSessionId   = remote->dwOrigSessionId;
			GetUserObjectInformation( GetProcessWindowStation(), UOI_NAME, &cStationName, 256, NULL );
			remote->cpOrigStationName    = _strdup( cStationName );
			remote->cpCurrentStationName = _strdup( cStationName );
			GetUserObjectInformation( GetThreadDesktop( GetCurrentThreadId() ), UOI_NAME, &cDesktopName, 256, NULL );
			remote->cpOrigDesktopName    = _strdup( cDesktopName );
			remote->cpCurrentDesktopName = _strdup( cDesktopName );
#endif




			// Process our default SSL-over-TCP transport
			if (remote->transport == METERPRETER_TRANSPORT_SSL) {
				dprintf("[SERVER] Flushing the socket handle...");
				server_socket_flush( remote );
		
				dprintf("[SERVER] Initializing SSL...");
				if( !server_initialize_ssl( remote ) )
					break;

				dprintf("[SERVER] Negotiating SSL...");
				if( !server_negotiate_ssl( remote ) )
					break;

				dprintf("[SERVER] Registering dispatch routines...");
				register_dispatch_routines();

				dprintf("[SERVER] Entering the main server dispatch loop for transport %d...", remote->transport);
				server_dispatch( remote );
		
				dprintf("[SERVER] Deregistering dispatch routines...");
				deregister_dispatch_routines( remote );
			}

			if (remote->transport == METERPRETER_TRANSPORT_HTTP || remote->transport == METERPRETER_TRANSPORT_HTTPS) {
				dprintf("[SERVER] Registering dispatch routines...");
				register_dispatch_routines();
				
				dprintf("[SERVER] Entering the main server dispatch loop for transport %d...", remote->transport);
#ifdef _WIN32
				server_dispatch_http_wininet( remote );
#else
				// XXX: Handle non-windows HTTP transport
#endif 

				dprintf("[SERVER] Deregistering dispatch routines...");
				deregister_dispatch_routines( remote );
			}

		} while (0);

		if (remote->transport == METERPRETER_TRANSPORT_SSL) {
			dprintf("[SERVER] Closing down SSL...");
			server_destroy_ssl( remote );
		}

		if( remote )
			remote_deallocate( remote );

	} 
	__except( exceptionfilter(GetExceptionCode(), GetExceptionInformation()) )
	{
		dprintf("[SERVER] *** exception triggered!");

		thread_kill( serverThread );
	}

	dprintf("[SERVER] Finished.");
	return res;
}
/*!
 * @brief Setup and run the server. This is called from Init via the loader.
 * @param fd The original socket descriptor passed in from the stager, or a pointer to stageless extensions.
 * @return Meterpreter exit code (ignored by the caller).
 */
DWORD server_setup(MetsrvConfig* config)
{
	THREAD* serverThread = NULL;
	Remote* remote = NULL;
	char stationName[256] = { 0 };
	char desktopName[256] = { 0 };
	DWORD res = 0;

	dprintf("[SERVER] Initializing from configuration: 0x%p", config);
	dprintf("[SESSION] Comms Fd: %u", config->session.comms_fd);
	dprintf("[SESSION] Expiry: %u", config->session.expiry);

	dprintf("[SERVER] UUID: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
		config->session.uuid[0], config->session.uuid[1], config->session.uuid[2], config->session.uuid[3],
		config->session.uuid[4], config->session.uuid[5], config->session.uuid[6], config->session.uuid[7],
		config->session.uuid[8], config->session.uuid[9], config->session.uuid[10], config->session.uuid[11],
		config->session.uuid[12], config->session.uuid[13], config->session.uuid[14], config->session.uuid[15]);

	// if hAppInstance is still == NULL it means that we havent been
	// reflectivly loaded so we must patch in the hAppInstance value
	// for use with loading server extensions later.
	InitAppInstance();

	srand((unsigned int)time(NULL));

	__try
	{
		do
		{
			dprintf("[SERVER] module loaded at 0x%08X", hAppInstance);

			// Open a THREAD item for the servers main thread, we use this to manage migration later.
			serverThread = thread_open();

			dprintf("[SERVER] main server thread: handle=0x%08X id=0x%08X sigterm=0x%08X", serverThread->handle, serverThread->id, serverThread->sigterm);

			if (!(remote = remote_allocate()))
			{
				SetLastError(ERROR_NOT_ENOUGH_MEMORY);
				break;
			}

			setup_ssl_lib(&remote->ssl);

			remote->orig_config = config;
			remote->sess_expiry_time = config->session.expiry;
			remote->sess_start_time = current_unix_timestamp();
			remote->sess_expiry_end = remote->sess_start_time + config->session.expiry;

			dprintf("[DISPATCH] Session going for %u seconds from %u to %u", remote->sess_expiry_time, remote->sess_start_time, remote->sess_expiry_end);

			DWORD transportSize = 0;
			if (!create_transports(remote, config->transports, &transportSize))
			{
				// not good, bail out!
				SetLastError(ERROR_BAD_ARGUMENTS);
				break;
			}

			// the first transport should match the transport that we initially connected on.
			// If it's TCP comms, we need to wire that up.
			if (remote->transport->type == METERPRETER_TRANSPORT_SSL && config->session.comms_fd)
			{
				((TcpTransportContext*)remote->transport->ctx)->fd = (SOCKET)config->session.comms_fd;
			}

			// Set up the transport creation function pointer
			remote->trans_create = create_transport;
			// Set up the transport removal function pointer
			remote->trans_remove = remove_transport;
			// and the config creation pointer
			remote->config_create = config_create;

			// Store our thread handle
			remote->server_thread = serverThread->handle;

			dprintf("[SERVER] Registering dispatch routines...");
			register_dispatch_routines();

			// this has to be done after dispatch routine are registered
			load_stageless_extensions(remote, (MetsrvExtension*)((LPBYTE)config->transports + transportSize));

			// Store our process token
			if (!OpenThreadToken(remote->server_thread, TOKEN_ALL_ACCESS, TRUE, &remote->server_token))
			{
				OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &remote->server_token);
			}

			if (scheduler_initialize(remote) != ERROR_SUCCESS)
			{
				SetLastError(ERROR_BAD_ENVIRONMENT);
				break;
			}

			// Copy it to the thread token
			remote->thread_token = remote->server_token;

			// Save the initial session/station/desktop names...
			remote->orig_sess_id = server_sessionid();
			remote->curr_sess_id = remote->orig_sess_id;
			GetUserObjectInformation(GetProcessWindowStation(), UOI_NAME, &stationName, 256, NULL);
			remote->orig_station_name = _strdup(stationName);
			remote->curr_station_name = _strdup(stationName);
			GetUserObjectInformation(GetThreadDesktop(GetCurrentThreadId()), UOI_NAME, &desktopName, 256, NULL);
			remote->orig_desktop_name = _strdup(desktopName);
			remote->curr_desktop_name = _strdup(desktopName);

			remote->sess_start_time = current_unix_timestamp();

			// loop through the transports, reconnecting each time.
			while (remote->transport)
			{
				if (remote->transport->transport_init)
				{
					dprintf("[SERVER] attempting to initialise transport 0x%p", remote->transport);
					// Each transport has its own set of retry settings and each should honour
					// them individually.
					if (!remote->transport->transport_init(remote->transport))
					{
						dprintf("[SERVER] transport initialisation failed, moving to the next transport");
						remote->transport = remote->transport->next_transport;

						// when we have a list of transports, we'll iterate to the next one.
						continue;
					}
				}

				dprintf("[SERVER] Entering the main server dispatch loop for transport %x, context %x", remote->transport, remote->transport->ctx);
				DWORD dispatchResult = remote->transport->server_dispatch(remote, serverThread);

				dprintf("[DISPATCH] dispatch exited with result: %u", dispatchResult);
				if (remote->transport->transport_deinit)
				{
					dprintf("[DISPATCH] deinitialising transport");
					remote->transport->transport_deinit(remote->transport);
				}

				dprintf("[TRANS] resetting transport");
				if (remote->transport->transport_reset)
				{
					remote->transport->transport_reset(remote->transport, dispatchResult == ERROR_SUCCESS && remote->next_transport == NULL);
				}

				// If the transport mechanism failed, then we should loop until we're able to connect back again.
				if (dispatchResult == ERROR_SUCCESS)
				{
					dprintf("[DISPATCH] Server requested shutdown of dispatch");
					// But if it was successful, and this is a valid exit, then we should clean up and leave.
					if (remote->next_transport == NULL)
					{
						dprintf("[DISPATCH] No next transport specified, leaving");
						// we weren't asked to switch transports, so we exit.
						break;
					}

					// we need to change transports to the one we've been given. We will assume, for now,
					// that the transport has been created using the appropriate functions and that it is
					// part of the transport list.
					dprintf("[TRANS] Moving transport from 0x%p to 0x%p", remote->transport, remote->next_transport);
					remote->transport = remote->next_transport;
					remote->next_transport = NULL;

				}
				else
				{
					// move to the next one in the list
					dprintf("[TRANS] Moving transport from 0x%p to 0x%p", remote->transport, remote->transport->next_transport);
					remote->transport = remote->transport->next_transport;
				}

				// transport switching and failover both need to support the waiting functionality.
				if (remote->next_transport_wait > 0)
				{
					dprintf("[TRANS] Sleeping for %u seconds ...", remote->next_transport_wait);

					sleep(remote->next_transport_wait);

					// the wait is a once-off thing, needs to be reset each time
					remote->next_transport_wait = 0;
				}
			}

			// clean up the transports
			while (remote->transport)
			{
				remove_transport(remote, remote->transport);
			}

			dprintf("[SERVER] Deregistering dispatch routines...");
			deregister_dispatch_routines(remote);
		} while (0);

		dprintf("[DISPATCH] calling scheduler_destroy...");
		scheduler_destroy();

		dprintf("[DISPATCH] calling command_join_threads...");
		command_join_threads();

		remote_deallocate(remote);
	}
	__except (exceptionfilter(GetExceptionCode(), GetExceptionInformation()))
	{
		dprintf("[SERVER] *** exception triggered!");

		thread_kill(serverThread);
	}

	dprintf("[SERVER] Finished.");
	return res;
}
Beispiel #29
0
BOOL
vncDesktop::InitWindow()
{
	vnclog.Print(LL_INTERR, VNCLOG("InitWindow called\n"));

	HDESK desktop;
	desktop = OpenInputDesktop(0, FALSE,
								DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW |
								DESKTOP_ENUMERATE | DESKTOP_HOOKCONTROL |
								DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS |
								DESKTOP_SWITCHDESKTOP | GENERIC_WRITE
								);

	if (desktop == NULL)
		vnclog.Print(LL_INTERR, VNCLOG("InitWindow:OpenInputdesktop Error \n"));
	else
		vnclog.Print(LL_INTERR, VNCLOG("InitWindow:OpenInputdesktop OK\n"));

	HDESK old_desktop = GetThreadDesktop(GetCurrentThreadId());
	DWORD dummy;

	char new_name[256];

	if (!GetUserObjectInformation(desktop, UOI_NAME, &new_name, 256, &dummy))
	{
		vnclog.Print(LL_INTERR, VNCLOG("InitWindow:!GetUserObjectInformation \n"));
	}

	vnclog.Print(LL_INTERR, VNCLOG("InitWindow:SelectHDESK to %s (%x) from %x\n"), new_name, desktop, old_desktop);

	if (!SetThreadDesktop(desktop))
	{
		vnclog.Print(LL_INTERR, VNCLOG("InitWindow:SelectHDESK:!SetThreadDesktop \n"));
	}

	HMODULE  hUser32 = LoadLibrary("user32.dll");
	CHANGEWINDOWMESSAGEFILTER pfnFilter = NULL;
	pfnFilter =(CHANGEWINDOWMESSAGEFILTER)GetProcAddress(hUser32,"ChangeWindowMessageFilter");
	if (pfnFilter) pfnFilter(RFB_SCREEN_UPDATE, MSGFLT_ADD);
	if (pfnFilter) pfnFilter(RFB_COPYRECT_UPDATE, MSGFLT_ADD);
	if (pfnFilter) pfnFilter(RFB_MOUSE_UPDATE, MSGFLT_ADD);
	if (pfnFilter) pfnFilter(WM_QUIT, MSGFLT_ADD);
	if (pfnFilter) pfnFilter(WM_SHUTDOWN, MSGFLT_ADD);

	if (m_wndClass == 0) {
		// Create the window class
		WNDCLASSEX wndclass;

		wndclass.cbSize			= sizeof(wndclass);
		wndclass.style			= 0;
		wndclass.lpfnWndProc	= &DesktopWndProc;
		wndclass.cbClsExtra		= 0;
		wndclass.cbWndExtra		= 0;
		wndclass.hInstance		= hAppInstance;
		wndclass.hIcon			= NULL;
		wndclass.hCursor		= NULL;
		wndclass.hbrBackground	= (HBRUSH) GetStockObject(WHITE_BRUSH);
		wndclass.lpszMenuName	= (const char *) NULL;
		wndclass.lpszClassName	= szDesktopSink;
		wndclass.hIconSm		= NULL;

		// Register it
		m_wndClass = RegisterClassEx(&wndclass);
		if (!m_wndClass) {
			vnclog.Print(LL_INTERR, VNCLOG("failed to register window class\n"));
			SetEvent(restart_event);
			return FALSE;
		}
	}

	// And create a window
	m_hwnd = CreateWindow(szDesktopSink,
				"WinVNC",
				WS_OVERLAPPEDWINDOW,
				CW_USEDEFAULT,
				CW_USEDEFAULT,
				400, 200,
				NULL,
				NULL,
				hAppInstance,
				NULL);

	if (m_hwnd == NULL) {
		vnclog.Print(LL_INTERR, VNCLOG("failed to create hook window\n"));
		SetEvent(restart_event);
		return FALSE;
	}
	SetTimer(m_hwnd,1001,1000,NULL);
	// Set the "this" pointer for the window
    helper::SafeSetWindowUserData(m_hwnd, (LONG_PTR)this);

	// Enable clipboard hooking
	// adzm - 2010-07 - Fix clipboard hangs
	m_settingClipboardViewer = true;
	m_hnextviewer = SetClipboardViewer(m_hwnd);
	m_settingClipboardViewer = false;
	StopDriverWatches=false;
		DrvWatch mywatch;
		mywatch.stop=&StopDriverWatches;
		mywatch.hwnd=m_hwnd;
	if (VideoBuffer())
	{
		DWORD myword;
		HANDLE T1=NULL;
		T1=CreateThread(NULL,0,Driverwatch,m_hwnd,0,&myword);
		if (T1) CloseHandle(T1);
	}
	vnclog.Print(LL_INTERR, VNCLOG("OOOOOOOOOOOO load hookdll's\n"));
	////////////////////////
		hModule=NULL;
	char szCurrentDir[MAX_PATH];
		if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH))
		{
			char* p = strrchr(szCurrentDir, '\\');
			if (p == NULL) return 0;
			*p = '\0';
			strcat (szCurrentDir,"\\vnchooks.dll");
		}
	hSCModule=NULL;
	char szCurrentDirSC[MAX_PATH];
		if (GetModuleFileName(NULL, szCurrentDirSC, MAX_PATH))
		{
			char* p = strrchr(szCurrentDirSC, '\\');
			if (p == NULL) return 0;
			*p = '\0';
#ifdef _X64
			strcat (szCurrentDirSC,"\\schook64.dll");
#else
			strcat (szCurrentDirSC,"\\schook.dll");
#endif
		}
	hW8Module=NULL;
	char szCurrentDirW8[MAX_PATH];
	if (WIN8)
	{
		if (GetModuleFileName(NULL, szCurrentDirW8, MAX_PATH))
		{
			char* p = strrchr(szCurrentDirW8, '\\');
			if (p == NULL) return 0;
			*p = '\0';
#ifdef _X64
			strcat (szCurrentDirW8,"\\w8hook64.dll");
#else
			strcat (szCurrentDirW8,"\\w8hook.dll");
#endif
		}
	}

	UnSetHooks=NULL;
	SetMouseFilterHook=NULL;
	SetKeyboardFilterHook=NULL;
	SetMouseFilterHooks=NULL;
	SetKeyboardFilterHooks=NULL;
	SetHooks=NULL;

	UnSetHook=NULL;
	SetHook=NULL;

	hModule = LoadLibrary(szCurrentDir);
	hSCModule = LoadLibrary(szCurrentDirSC);//TOFIX resource leak
	if (WIN8) hW8Module = LoadLibrary(szCurrentDirW8);
	if (hModule)
		{
			strcpy_s(g_hookstring,"vnchook");
			UnSetHooks = (UnSetHooksFn) GetProcAddress( hModule, "UnSetHooks" );
			SetMouseFilterHook  = (SetMouseFilterHookFn) GetProcAddress( hModule, "SetMouseFilterHook" );
			SetKeyboardFilterHook  = (SetKeyboardFilterHookFn) GetProcAddress( hModule, "SetKeyboardFilterHook" );
			SetHooks  = (SetHooksFn) GetProcAddress( hModule, "SetHooks" );
		}
	if (hSCModule)
		{
			UnSetHook = (UnSetHookFn) GetProcAddress( hSCModule, "UnSetHook" );
			SetHook  = (SetHookFn) GetProcAddress( hSCModule, "SetHook" );
			SetMouseFilterHooks  = (SetMouseFilterHookFn) GetProcAddress( hSCModule, "SetMouseFilterHook" );
			SetKeyboardFilterHooks  = (SetKeyboardFilterHookFn) GetProcAddress( hSCModule, "SetKeyboardFilterHook" );
		}
	startw8=NULL;
	stopw8=NULL;
	capturew8=NULL;
	if (hW8Module)
		{
			startw8=(StartW8)GetProcAddress(hW8Module,"StartW8");
			stopw8=(StopW8)GetProcAddress(hW8Module,"StopW8");
			capturew8=(CaptureW8)GetProcAddress(hW8Module,"CaptureW8");
		}

	///////////////////////////////////////////////
	vnclog.Print(LL_INTERR, VNCLOG("OOOOOOOOOOOO start dispatch\n"));
	MSG msg;
	SetEvent(restart_event);
	while (TRUE)
	{
		
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))
		{
			vnclog.Print(LL_INTERR, VNCLOG("OOOOOOOOOOOO %i %i\n"),msg.message,msg.hwnd);
			if (msg.message==WM_TIMER)
			{
				if(msg.wParam==1001) keepalive();
			}			
			if (msg.message==WM_QUIT || fShutdownOrdered)
				{
					vnclog.Print(LL_INTERR, VNCLOG("OOOOOOOOOOOO called wm_quit\n"));
					DestroyWindow(m_hwnd);
					SetEvent(trigger_events[5]);
					break;
				}
			else if (msg.message==WM_SHUTDOWN)
				{
					vnclog.Print(LL_INTERR, VNCLOG("OOOOOOOOOOOO called wm_user+4\n"));
					DestroyWindow(m_hwnd);
					break;
				}
			else if (msg.message==RFB_SCREEN_UPDATE)
				{
					if (can_be_hooked)
					{
					vnclog.Print(LL_INTERR, VNCLOG("RFB_SCREEN_UPDATE  \n"));
					rfb::Rect rect;
					rect.tl = rfb::Point((SHORT)LOWORD(msg.wParam), (SHORT)HIWORD(msg.wParam));
					rect.br = rfb::Point((SHORT)LOWORD(msg.lParam), (SHORT)HIWORD(msg.lParam));
					//Buffer coordinates
					rect.tl.x-=m_ScreenOffsetx;
					rect.br.x-=m_ScreenOffsetx;
					rect.tl.y-=m_ScreenOffsety;
					rect.br.y-=m_ScreenOffsety;
					vnclog.Print(LL_INTERR, VNCLOG("REct3 %i %i %i %i  \n"),rect.tl.x,rect.br.x,rect.tl.y,rect.br.y);

					rect = rect.intersect(m_Cliprect);
					if (!rect.is_empty())
						{
							while (lock_region_add) Sleep(5);
							rgnpump.assign_union(rect);
							SetEvent(trigger_events[1]);
						}
					}
				}
			else if (msg.message==RFB_MOUSE_UPDATE)
				{
					if (can_be_hooked)
					{
					vnclog.Print(LL_INTERR, VNCLOG("RFB_MOUSE_UPDATE  \n"));
					SetCursor((HCURSOR) msg.wParam);
					SetEvent(trigger_events[2]);
					}
				}
			else
				{
					if (msg.message==WM_USER+3 )vnclog.Print(LL_INTERR, VNCLOG("OOOOOOOOOOOO called wm_user+3\n"));
					TranslateMessage(&msg);
					DispatchMessage(&msg);
				}
		}
		else WaitMessage();
	}
	KillTimer(m_hwnd,1001);
	if (hModule)FreeLibrary(hModule);
	if (hSCModule)FreeLibrary(hSCModule);
	if (hW8Module)FreeLibrary(hW8Module);
	SetThreadDesktop(old_desktop);
    CloseDesktop(desktop);
	///////////////////////
	vnclog.Print(LL_INTERR, VNCLOG("OOOOOOOOOOOO end dispatch\n"));
	m_hwnd = NULL;
	return TRUE;
}
Beispiel #30
0
DWORD WINAPI imp_desktop_thread(LPVOID lpParam)
{
	vncServer *server = (vncServer *)lpParam;
	HDESK desktop;
	//vnclog.Print(LL_INTERR, VNCLOG("SelectDesktop \n"));
	//vnclog.Print(LL_INTERR, VNCLOG("OpenInputdesktop2 NULL\n"));
	desktop = OpenInputDesktop(0, FALSE,
								DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW |
								DESKTOP_ENUMERATE | DESKTOP_HOOKCONTROL |
								DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS |
								DESKTOP_SWITCHDESKTOP | GENERIC_WRITE
								);

	if (desktop == NULL)
		vnclog.Print(LL_INTERR, VNCLOG("OpenInputdesktop Error \n"));
	else
		vnclog.Print(LL_INTERR, VNCLOG("OpenInputdesktop OK\n"));

	HDESK old_desktop = GetThreadDesktop(GetCurrentThreadId());
	DWORD dummy;

	char new_name[256];

	if (!GetUserObjectInformation(desktop, UOI_NAME, &new_name, 256, &dummy))
	{
		vnclog.Print(LL_INTERR, VNCLOG("!GetUserObjectInformation \n"));
	}

	vnclog.Print(LL_INTERR, VNCLOG("SelectHDESK to %s (%x) from %x\n"), new_name, desktop, old_desktop);

	if (!SetThreadDesktop(desktop))
	{
		vnclog.Print(LL_INTERR, VNCLOG("SelectHDESK:!SetThreadDesktop \n"));
	}

//	ImpersonateCurrentUser_();

	char m_username[UNLEN+1];
	HWINSTA station = GetProcessWindowStation();
	if (station != NULL)
	{
		DWORD usersize;
		GetUserObjectInformation(station, UOI_USER_SID, NULL, 0, &usersize);
		DWORD  dwErrorCode = GetLastError();
		SetLastError(0);
		if (usersize != 0)
		{
			DWORD length = sizeof(m_username);
			if (GetUserName(m_username, &length) == 0)
			{
				UINT error = GetLastError();
				if (error != ERROR_NOT_LOGGED_ON)
				{
					vnclog.Print(LL_INTERR, VNCLOG("getusername error %d\n"), GetLastError());
					SetThreadDesktop(old_desktop);
                	CloseDesktop(desktop);
					Sleep(500);
					return FALSE;
				}
			}
		}
	}
    vnclog.Print(LL_INTERR, VNCLOG("Username %s \n"),m_username);

	// Create tray icon and menu
	vncMenu *menu = new vncMenu(server);
	if (menu == NULL)
	{
		vnclog.Print(LL_INTERR, VNCLOG("failed to create tray menu\n"));
		PostQuitMessage(0);
	}

	// This is a good spot to handle the old PostAdd messages
	if (PostAddAutoConnectClient_bool)
		vncService::PostAddAutoConnectClient( pszId_char );
	if (PostAddAutoConnectClient_bool_null)
		vncService::PostAddAutoConnectClient( NULL );

	if (PostAddConnectClient_bool)
		vncService::PostAddConnectClient( pszId_char );
	if (PostAddConnectClient_bool_null)
		vncService::PostAddConnectClient( NULL );

	if (PostAddNewClient_bool)
	{
		PostAddNewClient_bool=false;
		vnclog.Print(LL_INTERR, VNCLOG("PostAddNewClient IIIII\n"));
		vncService::PostAddNewClient(address_vcard, port_int);
	}
	//adzm 2009-06-20
	if (PostAddNewRepeaterClient_bool)
	{
		PostAddNewRepeaterClient_bool=false;
		vnclog.Print(LL_INTERR, VNCLOG("PostAddNewRepeaterClient II\n"));
		vncService::PostAddNewRepeaterClient();
	}
	bool Runonce=false;
	MSG msg;
	while (GetMessage(&msg,0,0,0) != 0)
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
		if (fShutdownOrdered && !Runonce)
		{
			Runonce=true;
			if (menu) menu->Shutdown(true);
		}

		if (hShutdownEvent)
		{
			// vnclog.Print(LL_INTERR, VNCLOG("****************** SDTimer tic\n"));
			DWORD result = WaitForSingleObject(hShutdownEvent, 1);
			if (WAIT_OBJECT_0 == result)
			{
				ResetEvent(hShutdownEvent);
				fShutdownOrdered = true;
				vnclog.Print(LL_INTERR, VNCLOG("****************** WaitForSingleObject - Shutdown server\n"));
			}
		}
	}

	// sf@2007 - Close all (vncMenu,tray icon, connections...)

	if (menu != NULL)
		delete menu;

	//vnclog.Print(LL_INTERR, VNCLOG("GetMessage stop \n"));
	SetThreadDesktop(old_desktop);
	CloseDesktop(desktop);
//	RevertToSelf();
	return 0;
}