public void Connect(Kohl.Framework.Security.Credential credentials) { progress.Visible = true; splitContainer1.Visible = false; this.SelectedSession = null; this.dataGridView1.DataSource = null; this.dataGridView2.DataSource = null; this.propertyGrid1.SelectedObject = null; this.server = TerminalServer.LoadServer(this.ServerNameComboBox.Text, credentials); progress.Visible = false; splitContainer1.Visible = true; if (this.server.IsTerminalServer) { this.dataGridView1.DataSource = this.server.Sessions; if (this.dataGridView1.Columns.Count > 0) this.dataGridView1.Columns[1].Visible = false; if (this.server.Sessions == null) MessageBox.Show("Terminals was unable to enumerate your server's sessions." + (this.server.Errors != null & this.server.Errors.Count > 0 ? "\n" +this.server.Errors[0] : "" )); } else { MessageBox.Show("This machine does not appear to be a terminal server."); } }
public static void ShutdownSystem(TerminalServer Server, bool Reboot) { long action = WTS_WSD_REBOOT; if (!Reboot) { action = WTS_WSD_SHUTDOWN; } System.IntPtr server = WTSOpenServer(Server.ServerName); if (server != System.IntPtr.Zero) { TerminalServicesAPI.WTSShutdownSystem(server, action); } }
public static void ShutdownSystem(TerminalServer Server, bool Reboot) { var action = WTS_WSD_REBOOT; if (!Reboot) { action = WTS_WSD_SHUTDOWN; } var server = WTSOpenServer(Server.ServerName); if (server != IntPtr.Zero) { WTSShutdownSystem(server, action); } }
public static TerminalServer LoadServer(string serverName, Kohl.Framework.Security.Credential credentials) { TerminalServer server = null; System.Threading.Thread t = new System.Threading.Thread(() => server = TerminalServicesApi.GetSessions(serverName, credentials)); t.Start(); while (t.ThreadState == System.Threading.ThreadState.Running) { System.Windows.Forms.Application.DoEvents(); System.Threading.Thread.Sleep(100); } return(server); }
private void button1_Click(object sender, EventArgs e) { SelectedSession = null; dataGridView1.DataSource = null; dataGridView2.DataSource = null; this.propertyGrid1.SelectedObject = null; Application.DoEvents(); server = TerminalServices.TerminalServer.LoadServer(this.ServerNameComboBox.Text); if(server.IsATerminalServer) { dataGridView1.DataSource = server.Sessions; dataGridView1.Columns[1].Visible = false; } else { System.Windows.Forms.MessageBox.Show("This machine does not appear to be a Terminal Server"); } }
private static void GetClientInfos(TerminalServer terminalServer) { try { IntPtr ppSessionInfo = IntPtr.Zero; Int32 Count = 0; Int32 FRetVal = WTSEnumerateSessions(terminalServer.ServerPointer, 0, 1, ref ppSessionInfo, ref Count); if (FRetVal != 0) { terminalServer.Sessions = new List <Session>(); WTS_SESSION_INFO[] sessionInfo = new WTS_SESSION_INFO[Count + 1]; for (int i = 0; i <= Count - 1; i++) { IntPtr session_ptr = new IntPtr(ppSessionInfo.ToInt32() + (i * Marshal.SizeOf(sessionInfo[i]))); sessionInfo[i] = (WTS_SESSION_INFO)Marshal.PtrToStructure(session_ptr, typeof(WTS_SESSION_INFO)); Session session = new Session { SessionId = sessionInfo[i].SessionID, State = (ConnectionStates)(int)sessionInfo[i].State, WindowsStationName = string.IsNullOrWhiteSpace(sessionInfo[i].pWinStationName) ? "RPD-Tcp#?" : sessionInfo[i].pWinStationName, ServerName = terminalServer.ServerName }; session.Client = GetClientInfoForSession(terminalServer.ServerPointer, session.SessionId); session.Client.Status = Enum.GetName(typeof(ConnectionStates), session.State).Replace("WTS", ""); terminalServer.Sessions.Add(session); } WTSFreeMemory(ppSessionInfo); } } catch (Exception ex) { Log.Info("Error enumerating RDP sessions.", ex); terminalServer.Errors.Add(ex.Message + "\r\n" + Marshal.GetLastWin32Error()); } }
public static TerminalServer GetSessions(string ServerName) { TerminalServer Data = new TerminalServer(); Data.ServerName = ServerName; IntPtr ptrOpenedServer = IntPtr.Zero; try { ptrOpenedServer = WTSOpenServer(ServerName); if (ptrOpenedServer == System.IntPtr.Zero) { Data.IsATerminalServer = false; return(Data); } Data.ServerPointer = ptrOpenedServer; Data.IsATerminalServer = true; Int32 FRetVal; IntPtr ppSessionInfo = IntPtr.Zero; Int32 Count = 0; try { FRetVal = WTSEnumerateSessions(ptrOpenedServer, 0, 1, ref ppSessionInfo, ref Count); if (FRetVal != 0) { Data.Sessions = new List <Session>(); WTS_SESSION_INFO[] sessionInfo = new WTS_SESSION_INFO[Count + 1]; int i; System.IntPtr session_ptr; for (i = 0; i <= Count - 1; i++) { session_ptr = new System.IntPtr(ppSessionInfo.ToInt32() + (i * Marshal.SizeOf(sessionInfo[i]))); sessionInfo[i] = (WTS_SESSION_INFO)Marshal.PtrToStructure(session_ptr, typeof(WTS_SESSION_INFO)); Session s = new Session(); s.SessionID = sessionInfo[i].SessionID; s.State = (ConnectionStates)(int)sessionInfo[i].State; s.WindowsStationName = sessionInfo[i].pWinStationName; s.ServerName = ServerName; Data.Sessions.Add(s); } WTSFreeMemory(ppSessionInfo); strSessionsInfo[] tmpArr = new strSessionsInfo[sessionInfo.GetUpperBound(0) + 1]; for (i = 0; i <= tmpArr.GetUpperBound(0); i++) { tmpArr[i].SessionID = sessionInfo[i].SessionID; tmpArr[i].StationName = sessionInfo[i].pWinStationName; tmpArr[i].ConnectionState = GetConnectionState(sessionInfo[i].State); //MessageBox.Show(tmpArr(i).StationName & " " & tmpArr(i).SessionID & " " & tmpArr(i).ConnectionState) } // ERROR: Not supported in C#: ReDimStatement } } catch (Exception ex) { Logging.Error("Get Sessions Inner", ex); Data.Errors.Add(ex.Message + "\r\n" + System.Runtime.InteropServices.Marshal.GetLastWin32Error()); } } catch (Exception ex) { Logging.Info("Get Sessions Outer", ex); Data.Errors.Add(ex.Message + "\r\n" + System.Runtime.InteropServices.Marshal.GetLastWin32Error()); } WTS_PROCESS_INFO[] plist = WTSEnumerateProcesses(ptrOpenedServer, Data); //Get ProcessID of TS Session that executed this TS Session Int32 active_process = GetCurrentProcessId(); Int32 active_session = 0; bool success1 = ProcessIdToSessionId(active_process, ref active_session); if (active_session <= 0) { success1 = false; } if (Data != null && Data.Sessions != null) { foreach (Session s in Data.Sessions) { if (s.Client == null) { s.Client = new Client(); } WTS_CLIENT_INFO ClientInfo = LoadClientInfoForSession(Data.ServerPointer, s.SessionID); s.Client.Address = ClientInfo.Address; s.Client.AddressFamily = ClientInfo.AddressFamily; s.Client.ClientName = ClientInfo.WTSClientName; s.Client.DomianName = ClientInfo.WTSDomainName; s.Client.StationName = ClientInfo.WTSStationName; s.Client.Status = ClientInfo.WTSStatus; s.Client.UserName = ClientInfo.WTSUserName; s.IsTheActiveSession = false; if (success1 && s.SessionID == active_session) { s.IsTheActiveSession = true; } } } WTSCloseServer(ptrOpenedServer); return(Data); }
private void ConnectButton_Click(object sender, EventArgs e) { if (this.ParentForm != null) this.ParentForm.Cursor = Cursors.WaitCursor; this.selectedSession = null; dataGridView1.DataSource = null; dataGridView2.DataSource = null; this.propertyGrid1.SelectedObject = null; Application.DoEvents(); server = TerminalServer.LoadServer(this.ServerNameComboBox.Text); try { if (server.IsATerminalServer) { dataGridView1.DataSource = server.Sessions; dataGridView1.Columns[1].Visible = false; } else { MessageBox.Show("This machine does not appear to be a Terminal Server"); } } catch (Exception) { // Do nothing when error } if (this.ParentForm != null) this.ParentForm.Cursor = Cursors.Default; }
private static WTS_PROCESS_INFO[] WTSEnumerateProcesses(IntPtr WTS_CURRENT_SERVER_HANDLE, TerminalServer Data) { IntPtr pProcessInfo = IntPtr.Zero; int processCount = 0; if (!WTSEnumerateProcesses(WTS_CURRENT_SERVER_HANDLE, 0, 1, ref pProcessInfo, ref processCount)) return null; const int NO_ERROR = 0; const int ERROR_INSUFFICIENT_BUFFER = 122; IntPtr pMemory = pProcessInfo; WTS_PROCESS_INFO[] processInfos = new WTS_PROCESS_INFO[processCount]; for (int i = 0; i < processCount; i++) { processInfos[i] = (WTS_PROCESS_INFO) Marshal.PtrToStructure(pProcessInfo, typeof (WTS_PROCESS_INFO)); pProcessInfo = (IntPtr) ((int) pProcessInfo + Marshal.SizeOf(processInfos[i])); SessionProcess p = new SessionProcess { ProcessID = processInfos[i].ProcessID, ProcessName = Marshal.PtrToStringAnsi(processInfos[i].ProcessName) }; if (processInfos[i].UserSid != IntPtr.Zero) { byte[] Sid = new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Marshal.Copy(processInfos[i].UserSid, Sid, 0, 14); StringBuilder name = new StringBuilder(); uint cchName = (uint) name.Capacity; SID_NAME_USE sidUse; StringBuilder referencedDomainName = new StringBuilder(); uint cchReferencedDomainName = (uint) referencedDomainName.Capacity; if (LookupAccountSid(Data.ServerName, Sid, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse)) { int err = Marshal.GetLastWin32Error(); if (err == ERROR_INSUFFICIENT_BUFFER) { name.EnsureCapacity((int) cchName); referencedDomainName.EnsureCapacity((int) cchReferencedDomainName); err = NO_ERROR; if ( !LookupAccountSid(null, Sid, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse)) err = Marshal.GetLastWin32Error(); } p.UserType = sidUse.ToString(); p.User = name.ToString(); } } p.SessionID = processInfos[i].SessionID; foreach (Session s in Data.Sessions) { if (s.SessionId == p.SessionID) { if (s.Processes == null) s.Processes = new List<SessionProcess>(); s.Processes.Add(p); break; } } } WTSFreeMemory(pMemory); return processInfos; }
public static TerminalServer GetSessions(string ServerName) { TerminalServer Data = new TerminalServer {ServerName = ServerName}; IntPtr ptrOpenedServer = IntPtr.Zero; try { ptrOpenedServer = WTSOpenServer(ServerName); if (ptrOpenedServer == IntPtr.Zero) { Data.IsATerminalServer = false; return Data; } Data.ServerPointer = ptrOpenedServer; Data.IsATerminalServer = true; IntPtr ppSessionInfo = IntPtr.Zero; Int32 Count = 0; try { Int32 FRetVal = WTSEnumerateSessions(ptrOpenedServer, 0, 1, ref ppSessionInfo, ref Count); if (FRetVal != 0) { Data.Sessions = new List<Session>(); WTS_SESSION_INFO[] sessionInfo = new WTS_SESSION_INFO[Count + 1]; int i; for (i = 0; i <= Count - 1; i++) { IntPtr session_ptr = new IntPtr(ppSessionInfo.ToInt32() + (i*Marshal.SizeOf(sessionInfo[i]))); sessionInfo[i] = (WTS_SESSION_INFO) Marshal.PtrToStructure(session_ptr, typeof (WTS_SESSION_INFO)); Data.Sessions.Add(new Session { SessionId = sessionInfo[i].SessionID, State = (ConnectionStates) (int) sessionInfo[i].State, WindowsStationName = sessionInfo[i].pWinStationName, ServerName = ServerName }); } WTSFreeMemory(ppSessionInfo); strSessionsInfo[] tmpArr = new strSessionsInfo[sessionInfo.GetUpperBound(0) + 1]; for (i = 0; i <= tmpArr.GetUpperBound(0); i++) { tmpArr[i].SessionID = sessionInfo[i].SessionID; tmpArr[i].StationName = sessionInfo[i].pWinStationName; tmpArr[i].ConnectionState = GetConnectionState(sessionInfo[i].State); } // ERROR: Not supported in C#: ReDimStatement } } catch (Exception ex) { Log.Error("Get Sessions Inner", ex); Data.Errors.Add(ex.Message + "\r\n" + Marshal.GetLastWin32Error()); } } catch (Exception ex) { Log.Info("Get Sessions Outer", ex); Data.Errors.Add(ex.Message + "\r\n" + Marshal.GetLastWin32Error()); } WTS_PROCESS_INFO[] plist = WTSEnumerateProcesses(ptrOpenedServer, Data); //Get ProcessID of TS Session that executed this TS Session Int32 active_process = GetCurrentProcessId(); Int32 active_session = 0; bool success1 = ProcessIdToSessionId(active_process, ref active_session); if (active_session <= 0) success1 = false; if (Data != null && Data.Sessions != null) { foreach (Session s in Data.Sessions) { if (s.Client == null) s.Client = new Client(); WTS_CLIENT_INFO ClientInfo = LoadClientInfoForSession(Data.ServerPointer, s.SessionId); s.Client.Address = ClientInfo.Address; s.Client.AddressFamily = ClientInfo.AddressFamily; s.Client.ClientName = ClientInfo.WTSClientName; s.Client.DomianName = ClientInfo.WTSDomainName; s.Client.StationName = ClientInfo.WTSStationName; s.Client.Status = ClientInfo.WTSStatus; s.Client.UserName = ClientInfo.WTSUserName; s.IsTheActiveSession = false; if (success1 && s.SessionId == active_session) s.IsTheActiveSession = true; } } WTSCloseServer(ptrOpenedServer); return Data; }
public static void ShutdownSystem(TerminalServer Server, bool Reboot) { long action = WTS_WSD_REBOOT; if (!Reboot) action = WTS_WSD_SHUTDOWN; IntPtr server = WTSOpenServer(Server.ServerName); if (server != IntPtr.Zero) WTSShutdownSystem(server, action); }
private static void GetProcessInfos(TerminalServer terminalServer) { try { IntPtr pProcessInfo = IntPtr.Zero; int processCount = 0; IntPtr useProcessesExStructure = new IntPtr(1); if (WTSEnumerateProcessesEx(terminalServer.ServerPointer, ref useProcessesExStructure, WTS_ANY_SESSION, ref pProcessInfo, ref processCount)) { const int NO_ERROR = 0; const int ERROR_INSUFFICIENT_BUFFER = 122; WTS_PROCESS_INFO_EX[] processInfos = new WTS_PROCESS_INFO_EX[processCount]; for (int i = 0; i < processCount; i++) { processInfos[i] = (WTS_PROCESS_INFO_EX) Marshal.PtrToStructure(pProcessInfo, typeof (WTS_PROCESS_INFO_EX)); SessionProcess p = new SessionProcess { SessionID = processInfos[i].SessionID, ProcessID = processInfos[i].ProcessID, ProcessName = Marshal.PtrToStringAnsi(processInfos[i].ProcessName), NumberOfThreads = processInfos[i].NumberOfThreads, HandleCount = processInfos[i].HandleCount, PagefileUsage = processInfos[i].PagefileUsage, PeakPagefileUsage = processInfos[i].PeakPagefileUsage, WorkingSetSize = processInfos[i].WorkingSetSize, PeakWorkingSetSize = processInfos[i].PeakWorkingSetSize, KernelTime = processInfos[i].KernelTime, UserTime = processInfos[i].UserTime }; if (processInfos[i].UserSid != IntPtr.Zero) { byte[] Sid = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Marshal.Copy(processInfos[i].UserSid, Sid, 0, 14); StringBuilder name = new StringBuilder(); uint cchName = (uint) name.Capacity; SID_NAME_USE sidUse; StringBuilder referencedDomainName = new StringBuilder(); uint cchReferencedDomainName = (uint) referencedDomainName.Capacity; if (LookupAccountSid(terminalServer.ServerName, Sid, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse)) { int err = Marshal.GetLastWin32Error(); if (err == ERROR_INSUFFICIENT_BUFFER) { name.EnsureCapacity((int) cchName); referencedDomainName.EnsureCapacity((int) cchReferencedDomainName); err = NO_ERROR; if (!LookupAccountSid(null, Sid, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse)) err = Marshal.GetLastWin32Error(); } p.Sid = sidUse.ToString(); p.User = name.ToString(); } } terminalServer.Sessions.FirstOrDefault(s => s.SessionId == p.SessionID).Processes.Add(p); pProcessInfo = (IntPtr) ((int) pProcessInfo + Marshal.SizeOf(processInfos[i])); } } if (pProcessInfo != IntPtr.Zero) WTSFreeMemory(pProcessInfo); } catch (Exception ex) { Log.Info("Error enumerating remote processes for RDP sessions.", ex); terminalServer.Errors.Add(ex.Message + "\r\n" + Marshal.GetLastWin32Error()); } }
private static void GetProcessInfos(TerminalServer terminalServer) { try { IntPtr pProcessInfo = IntPtr.Zero; int processCount = 0; IntPtr useProcessesExStructure = new IntPtr(1); if (WTSEnumerateProcessesExW(terminalServer.ServerPointer, ref useProcessesExStructure, WTS_ANY_SESSION, ref pProcessInfo, ref processCount)) { const int NO_ERROR = 0; const int ERROR_INSUFFICIENT_BUFFER = 122; WTS_PROCESS_INFO_EX[] processInfos = new WTS_PROCESS_INFO_EX[processCount]; for (int i = 0; i < processCount; i++) { processInfos[i] = (WTS_PROCESS_INFO_EX)Marshal.PtrToStructure(pProcessInfo, typeof(WTS_PROCESS_INFO_EX)); SessionProcess p = new SessionProcess { SessionID = processInfos[i].SessionID, ProcessID = processInfos[i].ProcessID, ProcessName = processInfos[i].ProcessName, NumberOfThreads = processInfos[i].NumberOfThreads, HandleCount = processInfos[i].HandleCount, PagefileUsage = (processInfos[i].PagefileUsage / 1024.0 / 1024.0).ToString("##0.## MB"), PeakPagefileUsage = (processInfos[i].PeakPagefileUsage / 1024.0 / 1024.0).ToString("##0.## MB"), WorkingSetSize = (processInfos[i].WorkingSetSize / 1024.0 / 1024.0).ToString("##0.## MB"), PeakWorkingSetSize = (processInfos[i].PeakWorkingSetSize / 1024.0 / 1024.0).ToString("##0.## MB"), KernelTime = processInfos[i].KernelTime, UserTime = processInfos[i].UserTime }; if (processInfos[i].UserSid != IntPtr.Zero) { byte[] Sid = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; Marshal.Copy(processInfos[i].UserSid, Sid, 0, 14); StringBuilder name = new StringBuilder(); uint cchName = (uint)name.Capacity; SID_NAME_USE sidUse; StringBuilder referencedDomainName = new StringBuilder(); uint cchReferencedDomainName = (uint)referencedDomainName.Capacity; if (LookupAccountSid(terminalServer.ServerName, Sid, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse)) { int err = Marshal.GetLastWin32Error(); if (err == ERROR_INSUFFICIENT_BUFFER) { name.EnsureCapacity((int)cchName); referencedDomainName.EnsureCapacity((int)cchReferencedDomainName); err = NO_ERROR; if (!LookupAccountSid(null, Sid, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse)) { err = Marshal.GetLastWin32Error(); } } p.Sid = sidUse.ToString(); p.User = name.ToString(); } } terminalServer.Sessions.FirstOrDefault(s => s.SessionId == p.SessionID).Processes.Add(p); pProcessInfo = (IntPtr)((int)pProcessInfo + Marshal.SizeOf(processInfos[i])); } } if (pProcessInfo != IntPtr.Zero) { WTSFreeMemory(pProcessInfo); } } catch (Exception ex) { Log.Info("Error enumerating remote processes for RDP sessions.", ex); terminalServer.Errors.Add(ex.Message + "\r\n" + Marshal.GetLastWin32Error()); } }
private void CheckForTS(object state) { this.IsTerminalServer = false; IFavorite favorite = state as IFavorite; try { Thread.Sleep(3000); this.Server = TerminalServer.LoadServer(favorite.ServerName); this.IsTerminalServer = this.Server.IsATerminalServer; } catch (Exception exception) { string message = string.Format("Checked to see if {0} is a terminal server. {0} is not a terminal server", favorite.ServerName); Logging.Error(message, exception); } }
public static TerminalServer GetSessions(string serverName, Kohl.Framework.Security.Credential credential) { TerminalServer terminalServer = new TerminalServer {ServerName = serverName}; Kohl.Framework.Security.Impersonator impersonator = null; // Start impersonation if we requested to do so ... try { if (credential != null) impersonator = new Kohl.Framework.Security.Impersonator(credential); } catch (Exception ex) { Log.Warn("Error impersonating RDP session enumerator. Trying to query RDP session details without impersonation ...", ex); } // Open a WTS connection to the server to be able to get details about the sessions and processes running on it IntPtr ptrOpenedServer = IntPtr.Zero; try { ptrOpenedServer = WTSOpenServer(terminalServer.ServerName); } catch (Exception ex) { Log.Error("Error opening WTS server connection. Aborting to query RDP sessions.", ex); return terminalServer; } if (ptrOpenedServer == IntPtr.Zero) { terminalServer.IsTerminalServer = false; return terminalServer; } terminalServer.ServerPointer = ptrOpenedServer; terminalServer.IsTerminalServer = true; // Try to get information about the sessions and the clients connected to it. GetClientInfos(terminalServer); // Try to get information about the server's processes. GetProcessInfos(terminalServer); if (ptrOpenedServer != IntPtr.Zero) WTSCloseServer(ptrOpenedServer); if (impersonator != null) impersonator.Dispose(); return terminalServer; }
public static WTS_PROCESS_INFO[] WTSEnumerateProcesses(IntPtr WTS_CURRENT_SERVER_HANDLE, TerminalServer Data) { IntPtr pProcessInfo = IntPtr.Zero; int processCount = 0; if (!WTSEnumerateProcesses(WTS_CURRENT_SERVER_HANDLE, 0, 1, ref pProcessInfo, ref processCount)) { return(null); } const int NO_ERROR = 0; const int ERROR_INSUFFICIENT_BUFFER = 122; int err = NO_ERROR; IntPtr pMemory = pProcessInfo; WTS_PROCESS_INFO[] processInfos = new WTS_PROCESS_INFO[processCount]; for (int i = 0; i < processCount; i++) { processInfos[i] = (WTS_PROCESS_INFO)Marshal.PtrToStructure(pProcessInfo, typeof(WTS_PROCESS_INFO)); pProcessInfo = (IntPtr)((int)pProcessInfo + Marshal.SizeOf(processInfos[i])); SessionProcess p = new SessionProcess(); p.ProcessID = processInfos[i].ProcessID; p.ProcessName = Marshal.PtrToStringAnsi(processInfos[i].ProcessName); if (processInfos[i].UserSid != IntPtr.Zero) { byte[] Sid = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; Marshal.Copy(processInfos[i].UserSid, Sid, 0, 14); System.Text.StringBuilder name = new StringBuilder(); uint cchName = (uint)name.Capacity; SID_NAME_USE sidUse; StringBuilder referencedDomainName = new StringBuilder(); uint cchReferencedDomainName = (uint)referencedDomainName.Capacity; if (LookupAccountSid(Data.ServerName, Sid, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse)) { err = System.Runtime.InteropServices.Marshal.GetLastWin32Error(); if (err == ERROR_INSUFFICIENT_BUFFER) { name.EnsureCapacity((int)cchName); referencedDomainName.EnsureCapacity((int)cchReferencedDomainName); err = NO_ERROR; if (!LookupAccountSid(null, Sid, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse)) { err = System.Runtime.InteropServices.Marshal.GetLastWin32Error(); } } p.UserType = sidUse.ToString(); p.User = name.ToString(); } } //string userSID = Marshal.PtrToStringAuto(processInfos[i].UserSid); p.SessionID = processInfos[i].SessionID; //LookupAccountSid(Data.ServerName, //p.User = Marshal.PtrToStringAnsi(processInfos[i].UserSid); foreach (Session s in Data.Sessions) { if (s.SessionID == p.SessionID) { if (s.Processes == null) { s.Processes = new List <SessionProcess>(); } s.Processes.Add(p); break; } } } WTSFreeMemory(pMemory); return(processInfos); }
public static TerminalServer GetSessions(string serverName, Kohl.Framework.Security.Credential credential) { TerminalServer terminalServer = new TerminalServer { ServerName = serverName }; Kohl.Framework.Security.Impersonator impersonator = null; // Start impersonation if we requested to do so ... try { if (credential != null) { impersonator = new Kohl.Framework.Security.Impersonator(credential); } } catch (Exception ex) { Log.Warn("Error impersonating RDP session enumerator. Trying to query RDP session details without impersonation ...", ex); } // Open a WTS connection to the server to be able to get details about the sessions and processes running on it IntPtr ptrOpenedServer = IntPtr.Zero; try { ptrOpenedServer = WTSOpenServer(terminalServer.ServerName); } catch (Exception ex) { Log.Error("Error opening WTS server connection. Aborting to query RDP sessions.", ex); return(terminalServer); } if (ptrOpenedServer == IntPtr.Zero) { terminalServer.IsTerminalServer = false; return(terminalServer); } terminalServer.ServerPointer = ptrOpenedServer; terminalServer.IsTerminalServer = true; // Try to get information about the sessions and the clients connected to it. GetClientInfos(terminalServer); // Try to get information about the server's processes. GetProcessInfos(terminalServer); if (ptrOpenedServer != IntPtr.Zero) { WTSCloseServer(ptrOpenedServer); } if (impersonator != null) { impersonator.Dispose(); } return(terminalServer); }
private static void GetClientInfos(TerminalServer terminalServer) { try { IntPtr ppSessionInfo = IntPtr.Zero; Int32 Count = 0; Int32 FRetVal = WTSEnumerateSessions(terminalServer.ServerPointer, 0, 1, ref ppSessionInfo, ref Count); if (FRetVal != 0) { terminalServer.Sessions = new List<Session>(); WTS_SESSION_INFO[] sessionInfo = new WTS_SESSION_INFO[Count + 1]; for (int i = 0; i <= Count - 1; i++) { IntPtr session_ptr = new IntPtr(ppSessionInfo.ToInt32() + (i*Marshal.SizeOf(sessionInfo[i]))); sessionInfo[i] = (WTS_SESSION_INFO) Marshal.PtrToStructure(session_ptr, typeof (WTS_SESSION_INFO)); Session session = new Session { SessionId = sessionInfo[i].SessionID, State = (ConnectionStates) (int) sessionInfo[i].State, WindowsStationName = string.IsNullOrWhiteSpace(sessionInfo[i].pWinStationName) ? "RPD-Tcp#?" : sessionInfo[i].pWinStationName, ServerName = terminalServer.ServerName }; session.Client = GetClientInfoForSession(terminalServer.ServerPointer, session.SessionId); session.Client.Status = Enum.GetName(typeof(ConnectionStates), session.State).Replace("WTS", ""); terminalServer.Sessions.Add(session); } WTSFreeMemory(ppSessionInfo); } } catch (Exception ex) { Log.Info("Error enumerating RDP sessions.", ex); terminalServer.Errors.Add(ex.Message + "\r\n" + Marshal.GetLastWin32Error()); } }