Exemplo n.º 1
0
 public ClientMessage[] SetPromptForCredentialReply(string userName, char[] password)
 {
     ClientMessage[] clientMessages;
     PowwaEvents.PowwaEVENT_DEBUG_LOG0("SetPromptForCredentialReply(): Enter");
     try
     {
         lock (this.clientRequestLock)
         {
             lock (this.sessionStateLock)
             {
                 PromptForCredentialMessage promptForCredentialMessage = this.ValidateSessionStateForMessageReply <PromptForCredentialMessage>();
                 if (promptForCredentialMessage.DomainCredentials)
                 {
                     StringBuilder stringBuilder  = new StringBuilder(0x202);
                     StringBuilder stringBuilder1 = new StringBuilder(0x152);
                     uint          num            = PowwaSession.CredUIParseUserName(userName, stringBuilder, stringBuilder.Capacity, stringBuilder1, stringBuilder1.Capacity);
                     if (num != 0)
                     {
                         PowwaEvents.PowwaEVENT_DEBUG_LOG2("SetPromptForCredentialReply(): Invalid UserName", "userName", userName, "errorCode", num.ToString(CultureInfo.InvariantCulture));
                         throw PowwaException.CreateValidationErrorException(Resources.InvalidUserNameInDomainCredentials);
                     }
                 }
                 PSCredential pSCredential = new PSCredential(userName, PowwaSession.ToSecureString(password));
                 this.messageQueue.SetInputMessageReply(pSCredential);
             }
             clientMessages = this.GetClientMessages();
         }
     }
     finally
     {
         PowwaEvents.PowwaEVENT_DEBUG_LOG0("SetPromptForCredentialReply(): Exit");
     }
     return(clientMessages);
 }
Exemplo n.º 2
0
        public PowwaSession CreateSession(string sessionId, RunspaceConnectionInfo connectionInfo, ClientInfo clientInfo, string authenticatedUserName)
        {
            bool         flag = false;
            PowwaSession powwaSession;
            PowwaSession stringSid = new PowwaSession(sessionId, authenticatedUserName, connectionInfo, clientInfo);
            string       str       = null;

            stringSid.AuthenticatedUserSid = PowwaAuthorizationManager.Instance.activeDirectoryHelper.ConvertAccountNameToStringSid(authenticatedUserName, out flag, out str);
            lock (this.sessionsLock)
            {
                bool userActiveSessions = this.GetUserActiveSessions(stringSid.AuthenticatedUserSid) < PowwaAuthorizationManager.Instance.UserSessionsLimit;
                if (userActiveSessions)
                {
                    stringSid.Name = this.GetSessionName(stringSid);
                    try
                    {
                        this.sessions.Add(sessionId, stringSid);
                    }
                    catch (ArgumentException argumentException)
                    {
                        PowwaEvents.PowwaEVENT_DEBUG_LOG0("CreateSession: Attempt to create a session that already exists");
                        throw new ArgumentException("There is already a PowWA session with the given ID", "sessionId");
                    }
                    powwaSession = stringSid;
                }
                else
                {
                    object[] objArray = new object[1];
                    objArray[0] = authenticatedUserName;
                    throw new Exception(string.Format(CultureInfo.CurrentCulture, Resources.UserActiveSessionLimitReached, objArray));
                }
            }
            return(powwaSession);
        }
Exemplo n.º 3
0
 private static PSObject PromptReplyObjectToPsObject(object reply, PromptFieldDescription description)
 {
     if (description.PromptFieldTypeIsList)
     {
         object[] objArray = reply as object[];
         if (objArray != null)
         {
             ArrayList arrayLists = new ArrayList();
             object[]  objArray1  = objArray;
             for (int i = 0; i < (int)objArray1.Length; i++)
             {
                 object obj = objArray1[i];
                 arrayLists.Add(PowwaSession.PromptReplyObjectToObject(obj, description));
             }
             return(PSObject.AsPSObject(arrayLists));
         }
         else
         {
             throw new ArgumentException("Expected multiple values as an object[]", "reply");
         }
     }
     else
     {
         return(PSObject.AsPSObject(PowwaSession.PromptReplyObjectToObject(reply, description)));
     }
 }
Exemplo n.º 4
0
        private string GetSessionName(PowwaSession session)
        {
            string str;

            lock (this.sessionsLock)
            {
                DateTime now      = DateTime.Now;
                object[] userName = new object[7];
                userName[0] = session.UserName;
                userName[1] = now.Year % 100;
                userName[2] = now.Month;
                userName[3] = now.Day;
                userName[4] = now.Hour;
                userName[5] = now.Minute;
                userName[6] = now.Second;
                string str1 = string.Format(CultureInfo.InvariantCulture, "{0}.{1:00}{2:00}{3:00}.{4:00}{5:00}{6:00}", userName);
                string str2 = str1;
                long   num  = (long)2;
                while (true)
                {
                    if (this.sessions.Values.All <PowwaSession>((PowwaSession v) => string.Compare(v.Name, str2, StringComparison.OrdinalIgnoreCase) != 0))
                    {
                        break;
                    }
                    object[] objArray = new object[2];
                    objArray[0] = str1;
                    objArray[1] = num;
                    str2        = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", objArray);
                    num         = num + (long)1;
                }
                str = str2;
            }
            return(str);
        }
Exemplo n.º 5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            SessionHelper.DisablePageCaching(base.Response);
            PowwaSession session = null;

            try
            {
                session = PowwaSessionManager.Instance.GetSession(SessionHelper.GetSessionId());
            }
            catch (ArgumentException argumentException)
            {
                base.Response.Redirect("./timeout.aspx");
            }
            if (!session.InUse)
            {
                session.InUse = true;
            }
            else
            {
                base.Response.Redirect("./session.aspx");
            }
            if (FormsAuthentication.RequireSSL && !base.Request.IsSecureConnection)
            {
                base.Response.Redirect("./error.aspx");
            }
            this.sessionKey.Value = session.SessionKey;
        }
Exemplo n.º 6
0
 private static SecureString ToSecureString(object[] array)
 {
     char[] chr = new char[(int)array.Length];
     for (int i = 0; i < (int)array.Length; i++)
     {
         chr[i]   = Convert.ToChar(array[i], CultureInfo.InvariantCulture);
         array[i] = (char)0;
     }
     return(PowwaSession.ToSecureString(chr));
 }
Exemplo n.º 7
0
        private static PowwaReturnValue <T> HttpEndpointWrapper <T>(string sessionKey, Func <PowwaSession, T> function)
        {
            PowwaReturnValue <T> powwaReturnValue;
            PowwaSession         session = null;

            try
            {
                try
                {
                    session = PowwaSessionManager.Instance.GetSession(SessionHelper.GetSessionId());
                }
                catch (ArgumentException argumentException)
                {
                    powwaReturnValue = PowwaReturnValue <T> .CreateError(PowwaException.CreateInvalidSessionException());

                    return(powwaReturnValue);
                }
                if (string.Compare(sessionKey, session.SessionKey, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    if (string.Compare(SessionHelper.GetAuthenticatedUser(), session.UserName, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        powwaReturnValue = PowwaReturnValue <T> .CreateSuccess(function(session));
                    }
                    else
                    {
                        PowwaEvents.PowwaEVENT_INVALID_SESSION_USER(session.Name, SessionHelper.GetAuthenticatedUser(), session.UserName, SessionHelper.GetSourceIPAddressRemoteAddr(), SessionHelper.GetSourceIPAddressHttpXForwardedFor());
                        powwaReturnValue = PowwaReturnValue <T> .CreateError(PowwaException.CreateInvalidSessionException());
                    }
                }
                else
                {
                    PowwaEvents.PowwaEVENT_INVALID_SESSION_KEY(session.Name, SessionHelper.GetAuthenticatedUser(), SessionHelper.GetSourceIPAddressRemoteAddr(), SessionHelper.GetSourceIPAddressHttpXForwardedFor());
                    powwaReturnValue = PowwaReturnValue <T> .CreateError(PowwaException.CreateInvalidSessionException());
                }
            }
            catch (PowwaException powwaException1)
            {
                PowwaException powwaException = powwaException1;
                powwaReturnValue = PowwaReturnValue <T> .CreateError(powwaException);
            }
            catch (Exception exception1)
            {
                Exception exception = exception1;
                PowwaEvents.PowwaEVENT_GENERIC_FAILURE(session.Name, exception.Message);
                powwaReturnValue = PowwaReturnValue <T> .CreateGenericError(exception);
            }
            return(powwaReturnValue);
        }
Exemplo n.º 8
0
        public string TerminateSession(string sessionId)
        {
            string str = null;

            lock (this.sessionsLock)
            {
                PowwaSession session = this.GetSession(sessionId);
                if (session != null)
                {
                    string name = session.Name;
                    this.sessions.Remove(sessionId);
                    session.Close();
                    str = name;
                }
            }
            return(str);
        }
Exemplo n.º 9
0
        public PowwaSession GetSession(string sessionId)
        {
            PowwaSession item = null;

            lock (this.sessionsLock)
            {
                try
                {
                    if (this.sessions.ContainsKey(sessionId))
                    {
                        item = this.sessions[sessionId];
                    }
                }
                catch (KeyNotFoundException keyNotFoundException)
                {
                    throw new ArgumentException("Invalid sessionId", "sessionId");
                }
            }
            return(item);
        }
Exemplo n.º 10
0
 public ClientMessage[] SetReadLineAsSecureStringReply(char[] reply)
 {
     ClientMessage[] clientMessages;
     PowwaEvents.PowwaEVENT_DEBUG_LOG0("SetReadLineAsSecureStringReply(): Enter");
     try
     {
         lock (this.clientRequestLock)
         {
             lock (this.sessionStateLock)
             {
                 this.ValidateSessionStateForMessageReply <ReadLineAsSecureStringMessage>();
                 SecureString secureString = PowwaSession.ToSecureString(reply);
                 this.messageQueue.SetInputMessageReply(secureString);
             }
             clientMessages = this.GetClientMessages();
         }
     }
     finally
     {
         PowwaEvents.PowwaEVENT_DEBUG_LOG0("SetReadLineAsSecureStringReply(): Exit");
     }
     return(clientMessages);
 }
Exemplo n.º 11
0
 public ClientMessage[] SetPromptReply(object[] reply)
 {
     ClientMessage[] clientMessages;
     PowwaEvents.PowwaEVENT_DEBUG_LOG0("SetPromptReply(): Enter");
     try
     {
         lock (this.clientRequestLock)
         {
             lock (this.sessionStateLock)
             {
                 PromptMessage promptMessage = this.ValidateSessionStateForMessageReply <PromptMessage>();
                 if ((int)reply.Length == (int)promptMessage.Descriptions.Length)
                 {
                     Dictionary <string, PSObject> strs = new Dictionary <string, PSObject>();
                     for (int i = 0; i < (int)reply.Length; i++)
                     {
                         strs.Add(promptMessage.Descriptions[i].Name, PowwaSession.PromptReplyObjectToPsObject(reply[i], promptMessage.Descriptions[i]));
                     }
                     this.messageQueue.SetInputMessageReply(strs);
                 }
                 else
                 {
                     int length = (int)reply.Length;
                     int num    = (int)promptMessage.Descriptions.Length;
                     PowwaEvents.PowwaEVENT_DEBUG_LOG2("SetPromptReply(): Number of items in the reply does not match prompt message", "reply.Length", length.ToString(CultureInfo.InvariantCulture), "message.Descriptions.Length", num.ToString(CultureInfo.InvariantCulture));
                     throw new ArgumentException("The number of items in the reply does not match the prompt message", "reply");
                 }
             }
             clientMessages = this.GetClientMessages();
         }
     }
     finally
     {
         PowwaEvents.PowwaEVENT_DEBUG_LOG0("SetPromptReply(): Exit");
     }
     return(clientMessages);
 }
Exemplo n.º 12
0
        private void CreateSession(LogOn.FormInfo formInfo)
        {
            string str;
            string applicationName;
            string str1;
            string originalString;
            WSManConnectionInfo wSManConnectionInfo = null;

            if (formInfo.ConfigurationName.Length == 0)
            {
                str = null;
            }
            else
            {
                str = string.Concat("http://schemas.microsoft.com/powershell/", formInfo.ConfigurationName);
            }
            string       str2         = str;
            PSCredential pSCredential = new PSCredential(formInfo.DestinationUserName, formInfo.DestinationPassword);

            if (!formInfo.IsUriConnection)
            {
                if (string.Compare(formInfo.ApplicationName, "WSMAN", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    applicationName = null;
                }
                else
                {
                    applicationName = formInfo.ApplicationName;
                }
                string str3 = applicationName;
                try
                {
                    wSManConnectionInfo = new WSManConnectionInfo(formInfo.UseSsl, formInfo.ComputerName, formInfo.Port, str3, str2, pSCredential);
                }
                catch (UriFormatException uriFormatException)
                {
                    throw PowwaException.CreateValidationErrorException(Resources.LogonError_InvalidComputerNameUriFormat);
                }
                wSManConnectionInfo.AuthenticationMechanism = formInfo.AuthenticationType;
                PowwaEvents.PowwaEVENT_DEBUG_CONNECT_USING_COMPUTERNAME(formInfo.DestinationUserName, wSManConnectionInfo.ComputerName, wSManConnectionInfo.Port, wSManConnectionInfo.AppName, wSManConnectionInfo.ShellUri, wSManConnectionInfo.AuthenticationMechanism.ToString());
            }
            else
            {
                wSManConnectionInfo = new WSManConnectionInfo(formInfo.ConnectionUri, str2, pSCredential);
                if (!formInfo.AllowRedirection)
                {
                    wSManConnectionInfo.MaximumConnectionRedirectionCount = 0;
                }
                PowwaEvents.PowwaEVENT_DEBUG_CONNECT_USING_URI(formInfo.DestinationUserName, wSManConnectionInfo.ConnectionUri.AbsoluteUri, wSManConnectionInfo.ShellUri);
            }
            string sourceIPAddressRemoteAddr        = SessionHelper.GetSourceIPAddressRemoteAddr();
            string sourceIPAddressHttpXForwardedFor = SessionHelper.GetSourceIPAddressHttpXForwardedFor();

            if (formInfo.IsUriConnection)
            {
                str1 = null;
            }
            else
            {
                str1 = PswaHelper.TranslateLocalComputerName(formInfo.ComputerName);
            }
            string str4 = str1;

            PowwaAuthorizationManager.Instance.CheckLogOnCredential(formInfo.UserName, formInfo.Password, str4, formInfo.ConnectionUri, formInfo.ConfigurationName, sourceIPAddressRemoteAddr, sourceIPAddressHttpXForwardedFor);
            ClientInfo   clientInfo   = new ClientInfo(HttpContext.Current.Request.UserAgent, CultureInfo.CurrentCulture, CultureInfo.CurrentUICulture);
            PowwaSession powwaSession = PowwaSessionManager.Instance.CreateSession(this.Session.SessionID, wSManConnectionInfo, clientInfo, formInfo.UserName);
            string       name         = powwaSession.Name;
            string       userName     = formInfo.UserName;
            string       str5         = sourceIPAddressRemoteAddr;
            string       str6         = sourceIPAddressHttpXForwardedFor;

            if (formInfo.IsUriConnection)
            {
                originalString = wSManConnectionInfo.ConnectionUri.OriginalString;
            }
            else
            {
                originalString = wSManConnectionInfo.ComputerName;
            }
            PowwaEvents.PowwaEVENT_SESSION_START(name, userName, str5, str6, originalString, formInfo.DestinationUserName, wSManConnectionInfo.Port, wSManConnectionInfo.AppName, wSManConnectionInfo.ShellUri);
            HttpCookie item = base.Request.Cookies["ASP.NET_SessionId"];

            if (FormsAuthentication.RequireSSL && item != null)
            {
                item.Secure = true;
            }
            FormsAuthentication.SetAuthCookie(formInfo.UserName, false, "/");
            base.Response.Redirect("~/default.aspx");
            //FormsAuthentication.RedirectFromLoginPage(formInfo.UserName, false);
        }
Exemplo n.º 13
0
        private static object PromptReplyObjectToObject(object reply, PromptFieldDescription description)
        {
            PromptFieldType promptFieldType = description.PromptFieldType;

            switch (promptFieldType)
            {
            case PromptFieldType.String:
            {
                if (reply as string != null)
                {
                    return(reply);
                }
                else
                {
                    throw new ArgumentException("Expected a string", "reply");
                }
            }

            case PromptFieldType.SecureString:
            {
                object[] objArray = reply as object[];
                if (objArray != null)
                {
                    return(PowwaSession.ToSecureString(objArray));
                }
                else
                {
                    throw new ArgumentException("Expected an object[]", "reply");
                }
            }

            case PromptFieldType.Credential:
            {
                Dictionary <string, object> strs = reply as Dictionary <string, object>;
                if (strs == null || !strs.ContainsKey("username") || !strs.ContainsKey("password"))
                {
                    throw new ArgumentException("Expected an object with username and password properties", "reply");
                }
                else
                {
                    string item = strs["username"] as string;
                    if (item != null)
                    {
                        object[] item1 = strs["password"] as object[];
                        if (item1 != null)
                        {
                            return(new PSCredential(item, PowwaSession.ToSecureString(item1)));
                        }
                        else
                        {
                            throw new ArgumentException("The password should be an object[]", "reply");
                        }
                    }
                    else
                    {
                        throw new ArgumentException("The username should be a string", "reply");
                    }
                }
            }
            }
            throw new ArgumentException("Unknown reply type", "reply");
        }
Exemplo n.º 14
0
        internal PowwaSession(string sessionId, string sessionUser, RunspaceConnectionInfo connectionInfo, ClientInfo clientInfo)
        {
            EventHandler <MessageCreatedEventArgs> eventHandler  = null;
            EventHandler <MessageCreatedEventArgs> eventHandler1 = null;
            EventHandler <MessageCreatedEventArgs> eventHandler2 = null;

            if (sessionId != null)
            {
                if (connectionInfo != null)
                {
                    if (clientInfo != null)
                    {
                        this.Id       = sessionId;
                        this.Name     = string.Empty;
                        this.UserName = sessionUser;
                        this.host     = new PowwaHost(clientInfo);
                        this.host.UI.RawUI.WindowTitle = connectionInfo.ComputerName;
                        PowwaHost powwaHost = this.host;
                        if (eventHandler == null)
                        {
                            eventHandler = (object sender, MessageCreatedEventArgs e) => this.OnClientMessageCreated(e);
                        }
                        powwaHost.MessageCreated += eventHandler;
                        IMessageCreated uI = (IMessageCreated)this.host.UI;
                        if (eventHandler1 == null)
                        {
                            eventHandler1 = (object sender, MessageCreatedEventArgs e) => this.OnClientMessageCreated(e);
                        }
                        uI.MessageCreated += eventHandler1;
                        IMessageCreated rawUI = (IMessageCreated)this.host.UI.RawUI;
                        if (eventHandler2 == null)
                        {
                            eventHandler2 = (object sender, MessageCreatedEventArgs e) => this.OnClientMessageCreated(e);
                        }
                        rawUI.MessageCreated                    += eventHandler2;
                        this.Runspace                            = RunspaceFactory.CreateRunspace(connectionInfo, this.host, PowwaSession.TypeTableLoader.Instance.LoadDefaultTypeFiles());
                        this.Runspace.StateChanged              += new EventHandler <RunspaceStateEventArgs>(this.OnRunspaceStateChanged);
                        this.executingCommandPowerShell          = System.Management.Automation.PowerShell.Create();
                        this.executingCommandPowerShell.Runspace = this.Runspace;
                        this.executingCommandPowerShell.InvocationStateChanged += new EventHandler <PSInvocationStateChangedEventArgs>(this.OnExecutingCommandInvocationStateChanged);
                        this.messageQueue      = new MessageQueue();
                        this.clientRequestLock = new object();
                        this.cancelCommandLock = new object();
                        this.sessionStateLock  = new object();
                        this.SessionKey        = PowwaSession.CreateSessionKey();
                        this.State             = PowwaSession.SessionState.Available;
                        try {
                            this.Runspace.Open();
                        }
                        catch (Exception ex)
                        {
                            var stackTrace = ex.StackTrace;
                            System.Diagnostics.Debug.WriteLine(stackTrace);
                        }
                        this.exec = new Microsoft.PowerShell.Executor(this.host, false, false);
                        this.exec.OutputHandler += HandleOutputHandler;
                        if (this.messageQueue.GetMessageCount() > 0)
                        {
                            this.PostClientMessage(new CommandCompletedMessage(this.GetPowerShellPrompt()), false);
                        }
                        return;
                    }
                    else
                    {
                        throw new ArgumentNullException("clientInfo");
                    }
                }
                else
                {
                    throw new ArgumentNullException("connectionInfo");
                }
            }
            else
            {
                throw new ArgumentNullException("sessionId");
            }
        }