/// <summary> /// Create a session, the session URL returned can be given to external users to connect to a specific host using a URL /// </summary> /// <param name="sessionID"></param> /// <param name="hostID"></param> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> public string CreateUserSession(string sessionID, long hostID, string username, string password) { using (var db = new MyrtilleEnterpriseDBContext()) { if (!db.Session.Any(m => m.SessionID == sessionID && m.IsAdmin && m.Expire > DateTime.Now)) { return(null); } if (!db.Host.Any(m => m.ID == hostID)) { return(null); } string newSessionID = Guid.NewGuid().ToString(); string sessionKey = Guid.NewGuid().ToString("n"); var session = new Session { Username = username, Password = AES_Encrypt(RDPCryptoHelper.EncryptPassword(password), sessionKey), SessionID = newSessionID, IsAdmin = false, Expire = DateTime.Now.AddHours(1), OneTime = true }; db.Session.Add(session); db.SaveChanges(); return(string.Format("?SI={0}&SD={1}&SK={2}", newSessionID, hostID, sessionKey)); } }
/// <summary> /// retrieve the mouse cursor from the remote session and send it to the browser /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load( object sender, EventArgs e) { try { // retrieve params using (StreamWriter sw = new StreamWriter(Response.OutputStream)) { String password = Request.QueryString["Password"]; String encrypted = RDPCryptoHelper.EncryptPassword(password); sw.WriteLine(encrypted); } } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed"); } }
/// <summary> /// Add override credentials for specific session host /// </summary> /// <param name="credentials"></param> /// <returns></returns> public bool AddSessionHostCredentials(EnterpriseHostSessionCredentials credentials) { using (var db = new MyrtilleEnterpriseDBContext()) { var session = db.Session.FirstOrDefault(m => m.SessionID == credentials.SessionID); if (session == null) { return(false); } if (!db.Host.Any(m => m.ID == credentials.HostID)) { return(false); } var sessionHost = db.SessionHostCredentials.FirstOrDefault(m => m.SessionID == session.ID && m.HostID == m.HostID); if (sessionHost != null) { db.SessionHostCredentials.Remove(sessionHost); } sessionHost = new SessionHostCredential { SessionID = session.ID, HostID = credentials.HostID, Username = credentials.Username, Password = AES_Encrypt(RDPCryptoHelper.EncryptPassword(credentials.Password), credentials.SessionKey), }; db.SessionHostCredentials.Add(sessionHost); db.SaveChanges(); return(true); } }
/// <summary> /// start the rdp session /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void ConnectButtonClick( object sender, EventArgs e) { // remove the active remote session, if any (disconnected?) if (RemoteSession != null) { try { // unset the remote session for the current http session HttpContext.Current.Session[HttpSessionStateVariables.RemoteSession.ToString()] = null; } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to remove remote session ({0})", exc); } finally { RemoteSession = null; } } // create a new remote session try { HttpContext.Current.Application.Lock(); // auto-increment the remote sessions counter // note that it doesn't really count the active remote sessions... it's just an auto-increment for the remote session id, ensuring it's unique... var remoteSessionsCounter = (int)HttpContext.Current.Application[HttpApplicationStateVariables.RemoteSessionsCounter.ToString()]; remoteSessionsCounter++; // create the remote session RemoteSession = new RemoteSession { Id = remoteSessionsCounter, State = RemoteSessionState.NotConnected, ServerAddress = string.IsNullOrEmpty(server.Value) ? "localhost" : server.Value, UserDomain = domain.Value, UserName = user.Value, UserPassword = string.IsNullOrEmpty(passwordHash.Value) ? password.Value : RDPCryptoHelper.DecryptPassword(passwordHash.Value), ClientWidth = int.Parse(width.Value), ClientHeight = int.Parse(height.Value), Program = program.Value }; // set the remote session for the current http session HttpContext.Current.Session[HttpSessionStateVariables.RemoteSession.ToString()] = RemoteSession; // register the http session at application level var httpSessions = (IDictionary <string, HttpSessionState>)HttpContext.Current.Application[HttpApplicationStateVariables.HttpSessions.ToString()]; httpSessions[HttpContext.Current.Session.SessionID] = HttpContext.Current.Session; // update the remote sessions auto-increment counter HttpContext.Current.Application[HttpApplicationStateVariables.RemoteSessionsCounter.ToString()] = remoteSessionsCounter; } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to create remote session ({0})", exc); RemoteSession = null; } finally { HttpContext.Current.Application.UnLock(); } // connect it if (RemoteSession != null) { try { // update the remote session state RemoteSession.State = RemoteSessionState.Connecting; // create pipes for the web gateway and the rdp client to talk RemoteSession.Manager.Pipes.CreatePipes(); // the rdp client does connect the pipes when it starts; when it stops (either because it was closed, crashed or because the rdp session had ended), pipes are released // as the process command line can be displayed into the task manager / process explorer, the connection settings (including user credentials) are now passed to the rdp client through the inputs pipe // use http://technet.microsoft.com/en-us/sysinternals/dd581625 to track the existing pipes RemoteSession.Manager.Client.StartProcess( RemoteSession.Id, RemoteSession.ClientWidth, RemoteSession.ClientHeight); // update controls UpdateControls(); } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to connect the remote session {0} ({1})", RemoteSession.Id, exc); } } }
/// <summary> /// connect the remote server /// </summary> /// <remarks> /// authentication is delegated to the remote server or connection broker (if applicable) /// </remarks> private bool ConnectRemoteServer() { // connection parameters string loginHostName = null; var loginHostType = (HostTypeEnum)Convert.ToInt32(hostType.Value); var loginProtocol = (SecurityProtocolEnum)securityProtocol.SelectedIndex; var loginServer = string.IsNullOrEmpty(server.Value) ? "localhost" : server.Value; var loginVMGuid = vmGuid.Value; var loginVMEnhancedMode = vmEnhancedMode.Checked; var loginDomain = domain.Value; var loginUser = user.Value; var loginPassword = string.IsNullOrEmpty(passwordHash.Value) ? password.Value : RDPCryptoHelper.DecryptPassword(passwordHash.Value); var startProgram = program.Value; // connect an host from the hosts list or from a one time session url if (_enterpriseSession != null && Request["SD"] != null) { long hostId; if (!long.TryParse(Request["SD"], out hostId)) { hostId = 0; } try { // retrieve the host connection details var connection = _enterpriseClient.GetSessionConnectionDetails(_enterpriseSession.SessionID, hostId, _enterpriseSession.SessionKey); if (connection == null) { System.Diagnostics.Trace.TraceInformation("Unable to retrieve host {0} connection details (invalid host or one time session url already used?)", hostId); return(false); } loginHostName = connection.HostName; loginHostType = connection.HostType; loginProtocol = connection.Protocol; loginServer = !string.IsNullOrEmpty(connection.HostAddress) ? connection.HostAddress : connection.HostName; loginVMGuid = connection.VMGuid; loginVMEnhancedMode = connection.VMEnhancedMode; loginDomain = connection.Domain; loginUser = connection.Username; loginPassword = RDPCryptoHelper.DecryptPassword(connection.Password); startProgram = connection.StartRemoteProgram; } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to retrieve host {0} connection details ({1})", hostId, exc); return(false); } } // remove any active remote session (disconnected?) if (RemoteSession != null) { // unset the remote session for the current http session Session[HttpSessionStateVariables.RemoteSession.ToString()] = null; RemoteSession = null; } // create a new remote session try { // create the remote session RemoteSession = new RemoteSession( Guid.NewGuid(), RemoteSessionState.NotConnected, loginHostName, loginHostType, loginProtocol, loginServer, loginVMGuid, loginVMEnhancedMode, loginDomain, loginUser, loginPassword, int.Parse(width.Value), int.Parse(height.Value), startProgram, _allowRemoteClipboard, _allowFileTransfer, _allowPrintDownload, _allowSessionSharing, Session.SessionID ); // bind the remote session to the current http session Session[HttpSessionStateVariables.RemoteSession.ToString()] = RemoteSession; } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to create remote session ({0})", exc); RemoteSession = null; } // connect it if (RemoteSession != null) { try { // update the remote session state RemoteSession.State = RemoteSessionState.Connecting; // create pipes for the web gateway and the host client to talk RemoteSession.Manager.Pipes.CreatePipes(); // the host client does connect the pipes when it starts; when it stops (either because it was closed, crashed or because the remote session had ended), pipes are released // as the process command line can be displayed into the task manager / process explorer, the connection settings (including user credentials) are now passed to the host client through the inputs pipe // use http://technet.microsoft.com/en-us/sysinternals/dd581625 to track the existing pipes RemoteSession.Manager.HostClient.StartProcess( RemoteSession.Id, RemoteSession.HostType, RemoteSession.SecurityProtocol, RemoteSession.ServerAddress, RemoteSession.VMGuid, RemoteSession.UserDomain, RemoteSession.UserName, RemoteSession.StartProgram, RemoteSession.ClientWidth, RemoteSession.ClientHeight, RemoteSession.AllowRemoteClipboard, RemoteSession.AllowPrintDownload); } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to connect the remote session {0} ({1})", RemoteSession.Id, exc); connectError.InnerText = "Failed to connect! ensure myrtille services are running"; return(false); } } else { connectError.InnerText = "Failed to create remote session!"; return(false); } return(true); }
/// <summary> /// connect the rdp server /// </summary> /// <remarks> /// the rdp authentication is delegated to the rdp server or connection broker (if applicable) /// </remarks> private bool ConnectRemoteServer() { // connection parameters var loginServer = string.IsNullOrEmpty(server.Value) ? "localhost" : server.Value; var loginDomain = domain.Value; var loginUser = user.Value; var loginPassword = string.IsNullOrEmpty(passwordHash.Value) ? password.Value : RDPCryptoHelper.DecryptPassword(passwordHash.Value); var loginProtocol = SecurityProtocolEnum.auto; // connect an host from the hosts list or from a one time session url if (_enterpriseSession != null && Request["SD"] != null) { long hostId = 0; long lResult = 0; if (long.TryParse(Request["SD"], out lResult)) { hostId = lResult; } try { // retrieve the host connection details var connection = _enterpriseClient.GetSessionConnectionDetails(_enterpriseSession.SessionID, hostId, _enterpriseSession.SessionKey); if (connection == null) { System.Diagnostics.Trace.TraceInformation("Unable to retrieve host {0} connection details (invalid host or one time session url already used?)", hostId); return(false); } loginServer = !string.IsNullOrEmpty(connection.HostAddress) ? connection.HostAddress : connection.HostName; loginDomain = string.Empty; // domain is defined into myrtille services config loginUser = connection.Username; loginPassword = RDPCryptoHelper.DecryptPassword(connection.Password); loginProtocol = connection.Protocol; } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to retrieve host {0} connection details ({1})", hostId, exc); return(false); } } // remote clipboard access var allowRemoteClipboard = true; bool bResult = false; if (bool.TryParse(ConfigurationManager.AppSettings["allowRemoteClipboard"], out bResult)) { allowRemoteClipboard = bResult; } // remove any active remote session (disconnected?) if (RemoteSession != null) { // unset the remote session for the current http session HttpContext.Current.Session[HttpSessionStateVariables.RemoteSession.ToString()] = null; RemoteSession = null; } // create a new remote session try { HttpContext.Current.Application.Lock(); // auto-increment the remote sessions counter // note that it doesn't really count the active remote sessions... it's just an auto-increment for the remote session id, ensuring it's unique... var remoteSessionsCounter = (int)HttpContext.Current.Application[HttpApplicationStateVariables.RemoteSessionsCounter.ToString()]; remoteSessionsCounter++; // create the remote session RemoteSession = new RemoteSession { Id = remoteSessionsCounter, State = RemoteSessionState.NotConnected, ServerAddress = loginServer, UserDomain = loginDomain, UserName = loginUser, UserPassword = loginPassword, ClientWidth = int.Parse(width.Value), ClientHeight = int.Parse(height.Value), StartProgram = program.Value, AllowRemoteClipboard = allowRemoteClipboard, SecurityProtocol = loginProtocol }; // bind the remote session to the current http session HttpContext.Current.Session[HttpSessionStateVariables.RemoteSession.ToString()] = RemoteSession; // update the remote sessions auto-increment counter HttpContext.Current.Application[HttpApplicationStateVariables.RemoteSessionsCounter.ToString()] = remoteSessionsCounter; } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to create remote session ({0})", exc); RemoteSession = null; } finally { HttpContext.Current.Application.UnLock(); } // connect it if (RemoteSession != null) { try { // update the remote session state RemoteSession.State = RemoteSessionState.Connecting; // create pipes for the web gateway and the rdp client to talk RemoteSession.Manager.Pipes.CreatePipes(); // the rdp client does connect the pipes when it starts; when it stops (either because it was closed, crashed or because the rdp session had ended), pipes are released // as the process command line can be displayed into the task manager / process explorer, the connection settings (including user credentials) are now passed to the rdp client through the inputs pipe // use http://technet.microsoft.com/en-us/sysinternals/dd581625 to track the existing pipes RemoteSession.Manager.Client.StartProcess( RemoteSession.Id, RemoteSession.ServerAddress, RemoteSession.UserDomain, RemoteSession.UserName, RemoteSession.StartProgram, RemoteSession.ClientWidth, RemoteSession.ClientHeight, RemoteSession.AllowRemoteClipboard, RemoteSession.SecurityProtocol); } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to connect the remote session {0} ({1})", RemoteSession.Id, exc); connectError.InnerText = "Failed to connect! ensure myrtille services are running"; return(false); } } else { connectError.InnerText = "Failed to create remote session!"; return(false); } return(true); }
/// <summary> /// Authenticate user against an active directory /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <param name="adminGroup"></param> /// <param name="domain"></param> /// <returns></returns> public EnterpriseSession Authenticate(string username, string password, string adminGroup, string domain) { try { using (var context = new PrincipalContext(ContextType.Domain, domain, username, password)) { UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username); DirectoryEntry entry = (DirectoryEntry)user.GetUnderlyingObject(); if (user.IsAccountLockedOut()) { return(new EnterpriseSession { AuthenticationErrorCode = EnterpriseAuthenticationErrorCode.USER_ACCOUNT_LOCKED }); } if (user.Enabled != null && !(bool)user.Enabled) { return(new EnterpriseSession { AuthenticationErrorCode = EnterpriseAuthenticationErrorCode.ACCOUNT_DISABLED }); } if (user.AccountExpirationDate != null && (DateTime)user.AccountExpirationDate <= DateTime.Now) { return(new EnterpriseSession { AuthenticationErrorCode = EnterpriseAuthenticationErrorCode.ACCOUNT_EXPIRED }); } if (!user.PasswordNeverExpires) //&& !user.UserCannotChangePassword) { var expDate = (DateTime)entry.InvokeGet("PasswordExpirationDate"); if (expDate <= DateTime.Now) { return(new EnterpriseSession { AuthenticationErrorCode = EnterpriseAuthenticationErrorCode.PASSWORD_EXPIRED }); } } var directoryGroups = new List <string>(); try { directoryGroups.AddRange(user.GetGroups().Select(m => m.Name).ToList <string>()); } catch (Exception e) { //There is an issue accessing user primary ad group remotely, //Exception: Information about the domain could not be retrieved (1355). //in that case use another method which will exclude the primary domain // might need to find another way to do this! directoryGroups.AddRange(GetDirectoryGroups(entry)); } //Add user to directory group to allow restriction to host to specific username directoryGroups.Add(username); bool isAdmin = directoryGroups.Any(m => m.Equals(adminGroup, StringComparison.InvariantCultureIgnoreCase)); string sessionID = Guid.NewGuid().ToString(); string sessionKey = Guid.NewGuid().ToString("n"); using (var db = new MyrtilleEnterpriseDBContext()) { var session = db.Session.FirstOrDefault(m => m.Username == username); if (session != null) { db.Session.Remove(session); db.SaveChanges(); } session = new Session { Username = username, Password = AES_Encrypt(RDPCryptoHelper.EncryptPassword(password), sessionKey), SessionID = sessionID, IsAdmin = isAdmin }; db.Session.Add(session); db.SaveChanges(); var groups = directoryGroups.Select(x => new SessionGroup { SessionID = session.ID, DirectoryGroup = x }); db.SessionGroup.AddRange(groups); db.SaveChanges(); return(new EnterpriseSession { SessionID = sessionID, SessionKey = sessionKey, IsAdmin = isAdmin, SingleUseConnection = false }); } } } catch (DirectoryServicesCOMException e) { var formattedError = (DirectoryExceptionHelper)e; return(new EnterpriseSession { AuthenticationErrorCode = formattedError.ErrorCode }); } catch (PrincipalOperationException e) { return(null); } catch (Exception e) { return(new EnterpriseSession { AuthenticationErrorCode = EnterpriseAuthenticationErrorCode.UNKNOWN_ERROR }); } }
/// <summary> /// connect the remote server /// </summary> /// <remarks> /// authentication is delegated to the remote server or connection broker (if applicable) /// </remarks> private bool ConnectRemoteServer() { // connection parameters string loginHostName = null; var loginHostType = (HostType)Convert.ToInt32(hostType.Value); var loginProtocol = (SecurityProtocol)securityProtocol.SelectedIndex; var loginServer = string.IsNullOrEmpty(server.Value) ? "localhost" : server.Value; var loginVMGuid = vmGuid.Value; var loginVMAddress = string.Empty; var loginVMEnhancedMode = vmEnhancedMode.Checked; var loginDomain = domain.Value; var loginUser = user.Value; var loginPassword = string.IsNullOrEmpty(passwordHash.Value) ? password.Value : RDPCryptoHelper.DecryptPassword(passwordHash.Value); var startProgram = program.Value; // allowed features var allowRemoteClipboard = _allowRemoteClipboard; var allowFileTransfer = _allowFileTransfer; var allowPrintDownload = _allowPrintDownload; var allowSessionSharing = _allowSessionSharing; var allowAudioPlayback = _allowAudioPlayback; // sharing parameters int maxActiveGuests = int.MaxValue; var connectionId = Guid.NewGuid(); // connect an host from the hosts list or from a one time session url if (_enterpriseSession != null && (!string.IsNullOrEmpty(Request["SD"]))) { long hostId; if (!long.TryParse(Request["SD"], out hostId)) { hostId = 0; } try { // retrieve the host connection details var connection = _enterpriseClient.GetSessionConnectionDetails(_enterpriseSession.SessionID, hostId, _enterpriseSession.SessionKey); if (connection == null) { System.Diagnostics.Trace.TraceInformation("Unable to retrieve host {0} connection details (invalid host or one time session url already used?)", hostId); return(false); } loginHostName = connection.HostName; loginHostType = connection.HostType; loginProtocol = connection.Protocol; loginServer = !string.IsNullOrEmpty(connection.HostAddress) ? connection.HostAddress : connection.HostName; loginVMGuid = connection.VMGuid; loginVMEnhancedMode = connection.VMEnhancedMode; loginDomain = connection.Domain; loginUser = connection.Username; loginPassword = RDPCryptoHelper.DecryptPassword(connection.Password); startProgram = connection.StartRemoteProgram; } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to retrieve host {0} connection details ({1})", hostId, exc); return(false); } } // by using a connection service on a backend (connection API), the connection details can be hidden from querystring and mapped to a connection identifier else if (!string.IsNullOrEmpty(Request["cid"])) { if (!Guid.TryParse(Request["cid"], out connectionId)) { System.Diagnostics.Trace.TraceInformation("Invalid connection id {0}", Request["cid"]); return(false); } try { // retrieve the connection details var connection = _connectionClient.GetConnectionInfo(connectionId); if (connection == null) { System.Diagnostics.Trace.TraceInformation("Unable to retrieve connection info {0}", connectionId); return(false); } // ensure the user is allowed to connect the host if (!_connectionClient.IsUserAllowedToConnectHost(connection.User.Domain, connection.User.UserName, connection.Host.IPAddress, connection.VM != null ? connection.VM.Guid : Guid.Empty)) { System.Diagnostics.Trace.TraceInformation("User: domain={0}, name={1} is not allowed to connect host {2}", connection.User.Domain, connection.User.UserName, connection.Host.IPAddress); return(false); } loginHostType = connection.Host.HostType; loginProtocol = connection.Host.SecurityProtocol; loginServer = connection.Host.IPAddress; loginVMGuid = connection.VM != null?connection.VM.Guid.ToString() : string.Empty; loginVMAddress = connection.VM != null ? connection.VM.IPAddress : string.Empty; loginVMEnhancedMode = connection.VM != null ? connection.VM.EnhancedMode : false; loginDomain = connection.User.Domain; loginUser = connection.User.UserName; loginPassword = connection.User.Password; startProgram = connection.StartProgram; allowRemoteClipboard = allowRemoteClipboard && connection.AllowRemoteClipboard; allowFileTransfer = allowFileTransfer && connection.AllowFileTransfer; allowPrintDownload = allowPrintDownload && connection.AllowPrintDownload; allowSessionSharing = allowSessionSharing && connection.MaxActiveGuests > 0; allowAudioPlayback = allowAudioPlayback && connection.AllowAudioPlayback; maxActiveGuests = connection.MaxActiveGuests; } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to retrieve connection info {0} ({1})", connectionId, exc); return(false); } } // if the connection from login screen or url is disabled, the connection must be done either by using a connection API or from the enterprise mode else if (!_loginEnabled) { return(false); } // remove any active remote session (disconnected?) if (RemoteSession != null) { // unset the remote session for the current http session Session[HttpSessionStateVariables.RemoteSession.ToString()] = null; RemoteSession = null; } // create a new remote session try { Application.Lock(); // create the remote session RemoteSession = new RemoteSession( connectionId, loginHostName, loginHostType, loginProtocol, loginServer, loginVMGuid, loginVMAddress, loginVMEnhancedMode, loginDomain, loginUser, loginPassword, int.Parse(width.Value), int.Parse(height.Value), startProgram, allowRemoteClipboard, allowFileTransfer, allowPrintDownload, allowSessionSharing, allowAudioPlayback, maxActiveGuests, Session.SessionID, Request["cid"] != null ); // bind the remote session to the current http session Session[HttpSessionStateVariables.RemoteSession.ToString()] = RemoteSession; // register the remote session at the application level var remoteSessions = (IDictionary <Guid, RemoteSession>)Application[HttpApplicationStateVariables.RemoteSessions.ToString()]; remoteSessions.Add(RemoteSession.Id, RemoteSession); } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to create remote session ({0})", exc); RemoteSession = null; } finally { Application.UnLock(); } // connect it if (RemoteSession != null) { RemoteSession.State = RemoteSessionState.Connecting; } else { connectError.InnerText = "Failed to create remote session!"; return(false); } return(true); }
/// <summary> /// page load (postback data is now available) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load( object sender, EventArgs e) { // retrieve the active enterprise session, if any if (HttpContext.Current.Session[HttpSessionStateVariables.RemoteSession.ToString()] != null) { try { _remoteSession = (RemoteSession)HttpContext.Current.Session[HttpSessionStateVariables.RemoteSession.ToString()]; if (_remoteSession.DisableSessionSharing(HttpContext.Current.Session.SessionID)) { Response.Redirect("~/", true); } _remoteSession.SessionKey = Guid.NewGuid().ToString(); HttpContext.Current.Session[HttpSessionStateVariables.RemoteSession.ToString()] = _remoteSession; sessionUrl.Value = Request.Url.Scheme + "://" + Request.Url.Host + (Request.Url.Port != 80 && Request.Url.Port != 443 ? ":" + Request.Url.Port : "") + Request.ApplicationPath + "/?SSE=" + RDPCryptoHelper.GetSessionKey(_remoteSession.Id, HttpContext.Current.Session.SessionID, _remoteSession.SessionKey); } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to retrieve the remote session for the http session {0}, ({1})", HttpContext.Current.Session.SessionID, exc); } } else { Response.Redirect("~/", true); } }
/// <summary> /// connect the remote server /// </summary> /// <remarks> /// authentication is delegated to the remote server or connection broker (if applicable) /// </remarks> private bool ConnectRemoteServer() { // connection parameters string loginHostName = null; var loginHostType = (HostTypeEnum)Convert.ToInt32(hostType.Value); var loginProtocol = (SecurityProtocolEnum)securityProtocol.SelectedIndex; var loginServer = string.IsNullOrEmpty(server.Value) ? "localhost" : server.Value; var loginVMGuid = vmGuid.Value; var loginVMEnhancedMode = vmEnhancedMode.Checked; var loginDomain = domain.Value; var loginUser = user.Value; var loginPassword = string.IsNullOrEmpty(passwordHash.Value) ? password.Value : RDPCryptoHelper.DecryptPassword(passwordHash.Value); var startProgram = program.Value; // connect an host from the hosts list or from a one time session url if (_enterpriseSession != null && Request["SD"] != null) { long hostId; if (!long.TryParse(Request["SD"], out hostId)) { hostId = 0; } try { // retrieve the host connection details var connection = _enterpriseClient.GetSessionConnectionDetails(_enterpriseSession.SessionID, hostId, _enterpriseSession.SessionKey); if (connection == null) { System.Diagnostics.Trace.TraceInformation("Unable to retrieve host {0} connection details (invalid host or one time session url already used?)", hostId); return(false); } loginHostName = connection.HostName; loginHostType = connection.HostType; loginProtocol = connection.Protocol; loginServer = !string.IsNullOrEmpty(connection.HostAddress) ? connection.HostAddress : connection.HostName; loginVMGuid = connection.VMGuid; loginVMEnhancedMode = connection.VMEnhancedMode; loginDomain = connection.Domain; loginUser = connection.Username; loginPassword = RDPCryptoHelper.DecryptPassword(connection.Password); startProgram = connection.StartRemoteProgram; } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to retrieve host {0} connection details ({1})", hostId, exc); return(false); } } // remove any active remote session (disconnected?) if (RemoteSession != null) { // unset the remote session for the current http session Session[HttpSessionStateVariables.RemoteSession.ToString()] = null; RemoteSession = null; } // create a new remote session try { // create the remote session RemoteSession = new RemoteSession( Guid.NewGuid(), RemoteSessionState.NotConnected, loginHostName, loginHostType, loginProtocol, loginServer, loginVMGuid, loginVMEnhancedMode, loginDomain, loginUser, loginPassword, int.Parse(width.Value), int.Parse(height.Value), startProgram, _allowRemoteClipboard, _allowFileTransfer, _allowPrintDownload, _allowSessionSharing, Session.SessionID ); // bind the remote session to the current http session Session[HttpSessionStateVariables.RemoteSession.ToString()] = RemoteSession; } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to create remote session ({0})", exc); RemoteSession = null; } // connect it if (RemoteSession != null) { RemoteSession.State = RemoteSessionState.Connecting; } else { connectError.InnerText = "Failed to create remote session!"; return(false); } return(true); }
/// <summary> /// Retrieve shared session from remote host /// </summary> /// <param name="sessionURL"></param> /// <returns></returns> private RemoteSession GetSharedRemoteSession(string sessionURL) { var sessionDetails = sessionURL.Split(':'); if (sessionDetails.Length != 2) { return(null); } var httpSessions = (IDictionary <string, HttpSessionState>)HttpContext.Current.Application[HttpApplicationStateVariables.HttpSessions.ToString()]; foreach (var httpSession in httpSessions) { try { var remoteSession = (RemoteSession)httpSession.Value[HttpSessionStateVariables.RemoteSession.ToString()]; if (remoteSession.Id.ToString().Equals(sessionDetails[0])) { var sessionKey = RDPCryptoHelper.GetSessionKey(remoteSession.Id, remoteSession.OwnerSession, remoteSession.SessionKey); if (!sessionKey.Equals(sessionURL)) { return(null); } remoteSession.SessionKey = Guid.NewGuid().ToString(); httpSession.Value[HttpSessionStateVariables.RemoteSession.ToString()] = remoteSession; HttpContext.Current.Session[HttpSessionStateVariables.RemoteSession.ToString()] = remoteSession; return(remoteSession); } } catch { } } return(null); //var httpSession = httpSessions[sessionDetails[0]]; //if (httpSession == null) return null; //try //{ // var remoteSession = (RemoteSession)httpSession[HttpSessionStateVariables.RemoteSession.ToString()]; // var sessionKey = RDPCryptoHelper.GetSessionKey(sessionDetails[0], remoteSession.SessionKey); // if (!sessionKey.Equals(sessionURL)) return null; // remoteSession.SessionKey = Guid.NewGuid().ToString(); // httpSession[HttpSessionStateVariables.RemoteSession.ToString()] = remoteSession; // HttpContext.Current.Session[HttpSessionStateVariables.RemoteSession.ToString()] = remoteSession; // return remoteSession; //} //catch //{ // return null; //} }