Пример #1
0
        /// <summary>
        /// Sends a command request to the service.
        /// </summary>
        /// <param name="clientID">Client ID of sender.</param>
        /// <param name="userInput">Request string.</param>
        public void SendRequest(Guid clientID, string userInput)
        {
            ClientRequest request = ClientRequest.Parse(userInput);

            if ((object)request != null)
            {
                ClientRequestHandler requestHandler = ServiceHelper.FindClientRequestHandler(request.Command);

                if (SecurityProviderUtility.IsResourceSecurable(request.Command) && !SecurityProviderUtility.IsResourceAccessible(request.Command, Thread.CurrentPrincipal))
                {
                    ServiceHelper.UpdateStatus(clientID, UpdateType.Alarm, $"Access to \"{request.Command}\" is denied.\r\n\r\n");
                    return;
                }

                if ((object)requestHandler != null)
                {
                    requestHandler.HandlerMethod(new ClientRequestInfo(new ClientInfo {
                        ClientID = clientID
                    }, request));
                }
                else
                {
                    ServiceHelper.UpdateStatus(clientID, UpdateType.Alarm, $"Command \"{request.Command}\" is not supported.\r\n\r\n");
                }
            }
        }
Пример #2
0
        private void Application_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            // Check if access to resource is to be secured.
            string resource = GetResourceName();

            if (!IsAccessSecured(resource))
            {
                return;
            }

            SecurityProviderCache.ValidateCurrentProvider();

            if (!m_application.User.Identity.IsAuthenticated)
            {
                // Failed to authenticate user.
                Redirect(HttpStatusCode.Unauthorized);
            }

            if (IsAccessRestricted() ||
                !SecurityProviderUtility.IsResourceAccessible(resource))
            {
                // User does not have access to the resource.
                Redirect(HttpStatusCode.Forbidden);
            }
        }
Пример #3
0
        /// <summary>
        /// Sends a command request to the service.
        /// </summary>
        /// <param name="clientID">Client ID of sender.</param>
        /// <param name="principal">The principal used for role-based security.</param>
        /// <param name="userInput">Request string.</param>
        public void SendRequest(Guid clientID, IPrincipal principal, string userInput)
        {
            ClientRequest request = ClientRequest.Parse(userInput);

            if (request is null)
            {
                return;
            }

            if (SecurityProviderUtility.IsResourceSecurable(request.Command) && !SecurityProviderUtility.IsResourceAccessible(request.Command, principal))
            {
                ServiceHelper.UpdateStatus(clientID, UpdateType.Alarm, $"Access to \"{request.Command}\" is denied.\r\n\r\n");
                return;
            }

            ClientRequestHandler requestHandler = ServiceHelper.FindClientRequestHandler(request.Command);

            if (requestHandler is null)
            {
                ServiceHelper.UpdateStatus(clientID, UpdateType.Alarm, $"Command \"{request.Command}\" is not supported.\r\n\r\n");
                return;
            }

            ClientInfo clientInfo = new ClientInfo {
                ClientID = clientID
            };

            clientInfo.SetClientUser(principal);

            ClientRequestInfo requestInfo = new ClientRequestInfo(clientInfo, request);

            requestHandler.HandlerMethod(requestInfo);
        }
Пример #4
0
        private void m_userAccounts_BeforeSave(object sender, CancelEventArgs e)
        {
            m_userAccounts.CurrentItem.UseADAuthentication = RadioButtonWindows.IsChecked.GetValueOrDefault();

            if (m_userAccounts.IsNewRecord)
            {
                if (RadioButtonDatabase.IsChecked.GetValueOrDefault())
                {
                    if (string.IsNullOrEmpty(TextBoxPassword.Password) || !Regex.IsMatch(TextBoxPassword.Password, m_passwordRequirementsRegex))
                    {
                        MessageBox.Show(m_passwordRequirementsError, "Invalid Password", MessageBoxButton.OK);
                        e.Cancel = true;
                    }
                    else
                    {
                        m_userAccounts.CurrentItem.Password = SecurityProviderUtility.EncryptPassword(TextBoxPassword.Password);
                    }
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(TextBoxPassword.Password))
                {
                    if (Regex.IsMatch(TextBoxPassword.Password, m_passwordRequirementsRegex))
                    {
                        m_userAccounts.CurrentItem.Password = SecurityProviderUtility.EncryptPassword(TextBoxPassword.Password);
                    }
                    else
                    {
                        MessageBox.Show("Please provide valid password value or leave it blank to retain old password." + Environment.NewLine + m_passwordRequirementsError, "Invalid Password", MessageBoxButton.OK);
                        e.Cancel = true;
                    }
                }
            }
        }
Пример #5
0
        /// <summary>
        /// Changes user password.
        /// </summary>
        /// <param name="sender">Source of this event.</param>
        /// <param name="e">Arguments of this event.</param>
        protected void ChangeButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Initialize the security provider.
                ISecurityProvider provider = SecurityProviderUtility.CreateProvider(ChangePasswordUsername.Text);

                if (provider.CanChangePassword)
                {
                    // Attempt to change password.
                    if (provider.ChangePassword(ChangePasswordOldPassword.Text, ChangePasswordNewPassword.Text))
                    {
                        // Password changed successfully.
                        if (provider.Authenticate(ChangePasswordNewPassword.Text))
                        {
                            // Password authenticated successfully.
                            SecurityProviderCache.CurrentProvider = provider;
                            Response.Redirect(GetReferrerUrl(), false);
                        }
                        else
                        {
                            // Show why authentication failed.
                            if (!ShowFailureReason(provider))
                            {
                                ShowMessage("Authentication was not successful.", true);
                            }
                        }
                    }
                    else
                    {
                        // Show why password change failed.
                        if (!ShowFailureReason(provider))
                        {
                            ShowMessage("Password change was not successful.", true);
                        }
                    }
                }
                else
                {
                    // Changing password is not supported.
                    ShowMessage("Account does not support password change.", true);
                }
            }
            catch (SecurityException ex)
            {
                // Show security related error messages.
                ShowMessage(ex.Message.EnsureEnd('.'), true);
            }
            catch (Exception ex)
            {
                // Show ambiguous message for other errors.
                ShowMessage("Password change failed due to an unexpected error.", true);
                System.Diagnostics.Trace.WriteLine(string.Format("Password change error: \r\n  {0}", ex));
            }
            finally
            {
                ChangePasswordOldPassword.Focus();
            }
        }
Пример #6
0
        /// <summary>
        /// Evaluates the <paramref name="evaluationContext"/> and initializes security.
        /// </summary>
        /// <param name="evaluationContext">An <see cref="EvaluationContext"/> object.</param>
        /// <param name="state">Custom state of the <see cref="SecurityPolicy"/>.</param>
        /// <returns></returns>
        public virtual bool Evaluate(EvaluationContext evaluationContext, ref object state)
        {
            // In order for this to work properly security on the binding must be configured to use windows security.
            // When this is done the caller's windows identity is available to us here and can be used to derive from
            // it the security principal that can be used by WCF service code downstream for implementing security.
            object property;

            if (evaluationContext.Properties.TryGetValue("Identities", out property))
            {
                // Extract and assign the caller's windows identity to current thread if available.
                IList <IIdentity> identities = property as List <IIdentity>;

                if ((object)identities == null)
                {
                    throw new SecurityException(string.Format("Null Identities in Evaluation Context for '{0}'", Thread.CurrentPrincipal.Identity));
                }

                foreach (IIdentity identity in identities)
                {
                    if (identity is WindowsIdentity)
                    {
                        Thread.CurrentPrincipal = new WindowsPrincipal((WindowsIdentity)identity);
                        break;
                    }
                }
            }

            string resource = GetResourceName();

            if (SecurityProviderUtility.IsResourceSecurable(resource))
            {
                // Initialize the security principal from caller's windows identity if uninitialized.
                if (SecurityProviderCache.CurrentProvider == null)
                {
                    SecurityProviderCache.CurrentProvider = SecurityProviderUtility.CreateProvider(string.Empty);
                }

                // Setup the principal to be attached to the thread on which WCF service will execute.
                evaluationContext.Properties["Principal"] = Thread.CurrentPrincipal;

                // Verify that the current thread principal has been authenticated.
                if (!Thread.CurrentPrincipal.Identity.IsAuthenticated)
                {
                    throw new SecurityException(string.Format("Authentication failed for user '{0}'", Thread.CurrentPrincipal.Identity.Name));
                }

                // Perform a top-level permission check on the resource being accessed.
                if (!SecurityProviderUtility.IsResourceAccessible(resource))
                {
                    throw new SecurityException(string.Format("Access to '{0}' is denied", resource));
                }

                return(true);
            }

            // Setup the principal to be attached to the thread on which WCF service will execute.
            evaluationContext.Properties["Principal"] = Thread.CurrentPrincipal;
            return(true);
        }
Пример #7
0
        private bool IsResourceAccessible(string resource)
        {
            if (ResourceAccessiblity == ResourceAccessiblityMode.AlwaysIncluded)
            {
                return(SecurityPrincipal.IsInRole(IncludedRoles));
            }

            return(SecurityProviderUtility.IsResourceAccessible(resource, SecurityPrincipal));
        }
Пример #8
0
        /// <summary>
        /// Returns information about the current user.
        /// </summary>
        /// <returns>An <see cref="UserData"/> object of the user if user's security context has been initialized, otherwise null.</returns>
        public UserData GetUserData()
        {
            if (SecurityProviderCache.CurrentProvider == null)
            {
                SecurityProviderCache.CurrentProvider = SecurityProviderUtility.CreateProvider(string.Empty);
            }

            return(SecurityProviderCache.CurrentProvider.UserData);
        }
Пример #9
0
        public void UpdateUserAccount(UserAccount record)
        {
            if (!record.UseADAuthentication && !string.IsNullOrWhiteSpace(record.Password))
            {
                record.Password = SecurityProviderUtility.EncryptPassword(record.Password);
            }

            DataContext.Table <UserAccount>().UpdateRecord(record);
        }
Пример #10
0
        private void SecureForm_Load(object sender, EventArgs e)
        {
            try
            {
                // Don't proceed if the form is opened in design mode
                if (DesignMode)
                {
                    return;
                }

                // Check if the resource is excluded from being secured
                string resource = GetResourceName();

                if (!SecurityProviderUtility.IsResourceSecurable(resource))
                {
                    return;
                }

                // Set up security provider for passthrough authentication
                ISecurityProvider securityProvider = SecurityProviderCache.CreateProvider(WindowsIdentity.GetCurrent().Name);
                securityProvider.PassthroughPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
                securityProvider.Authenticate();

                // Setup the security principal for role-based security
                SecurityIdentity securityIdentity = new SecurityIdentity(securityProvider);
                SecurityPrincipal = new SecurityPrincipal(securityIdentity);

                // Verify that the current thread principal has been authenticated
                if (!SecurityPrincipal.Identity.IsAuthenticated)
                {
                    throw new SecurityException($"Authentication failed for user '{SecurityPrincipal.Identity.Name}'");
                }

                // Perform a top-level permission check on the resource being accessed
                if (!SecurityProviderUtility.IsResourceAccessible(resource, SecurityPrincipal))
                {
                    throw new SecurityException($"Access to '{resource}' is denied");
                }

                // Set up the current thread principal
                // NOTE: Provided for backwards compatibility;
                //       recommended to use the SecurityPrincipal instead
                Thread.CurrentPrincipal = SecurityPrincipal;
            }
            catch (Exception ex)
            {
                if (ExceptionHandler is null)
                {
                    throw;
                }

                ExceptionHandler(ex);
            }
        }
Пример #11
0
        /// <summary>
        /// Authenticates a user and caches the security context upon successful authentication for subsequent use.
        /// </summary>
        /// <param name="username">Username of the user.</param>
        /// <param name="password">Password of the user.</param>
        /// <returns>An <see cref="UserData"/> object of the user.</returns>
        public UserData Authenticate(string username, string password)
        {
            ISecurityProvider provider = SecurityProviderUtility.CreateProvider(username);

            if (provider.Authenticate(password))
            {
                SecurityProviderCache.CurrentProvider = provider;
            }

            return(provider.UserData);
        }
Пример #12
0
        public void UpdateUserAccount(UserAccount record)
        {
            if (!record.UseADAuthentication && !string.IsNullOrWhiteSpace(record.Password))
            {
                record.Password = SecurityProviderUtility.EncryptPassword(record.Password);
            }

            record.DefaultNodeID = DefaultNodeID;
            record.UpdatedBy     = UserInfo.CurrentUserID;
            record.UpdatedOn     = DateTime.UtcNow;
            DataContext.Table <UserAccount>().UpdateRecord(record);
        }
Пример #13
0
 /// <summary>
 /// Determines if access to the requested <paramref name="resource"/> is to be secured.
 /// </summary>
 /// <param name="resource">Name of the resource being requested.</param>
 /// <returns>True if access to the resource is to be secured, otherwise False.</returns>
 protected override bool IsAccessSecured(string resource)
 {
     if (SecurityProviderUtility.IsRegexMatch(s_webServicesPath, resource))
     {
         // Don't secure WCF services.
         return(false);
     }
     else
     {
         // Fallback to the base class for everything else.
         return(base.IsAccessSecured(resource));
     }
 }
Пример #14
0
        /// <summary>
        /// Refreshes and returns information about the current user.
        /// </summary>
        /// <returns>An <see cref="UserData"/> object of the user if user's security context has been initialized, otherwise null.</returns>
        public UserData RefreshUserData()
        {
            if (SecurityProviderCache.CurrentProvider == null)
            {
                SecurityProviderCache.CurrentProvider = SecurityProviderUtility.CreateProvider(string.Empty);
            }

            if (SecurityProviderCache.CurrentProvider.CanRefreshData)
            {
                SecurityProviderCache.CurrentProvider.RefreshData();
            }

            return(SecurityProviderCache.CurrentProvider.UserData);
        }
Пример #15
0
        /// <summary>
        /// Authenticates a user and caches the security context upon successful authentication for subsequent use.
        /// </summary>
        /// <param name="username">Username of the user.</param>
        /// <param name="password">Password of the user.</param>
        /// <returns>An <see cref="UserData"/> object of the user.</returns>
        public UserData Authenticate(string username, string password)
        {
            ISecurityProvider securityProvider = SecurityProviderUtility.CreateProvider(username);

            securityProvider.Password = password;

            if (securityProvider.Authenticate())
            {
                SecurityIdentity securityIdentity = new SecurityIdentity(securityProvider);
                Thread.CurrentPrincipal = new SecurityPrincipal(securityIdentity);
            }

            return(securityProvider.UserData);
        }
Пример #16
0
        /// <summary>
        /// Changes user password.
        /// </summary>
        /// <param name="oldPassword">User's current password.</param>
        /// <param name="newPassword">User's new password.</param>
        /// <returns>true if the password is changed, otherwise false.</returns>
        public bool ChangePassword(string oldPassword, string newPassword)
        {
            if (SecurityProviderCache.CurrentProvider == null)
            {
                SecurityProviderCache.CurrentProvider = SecurityProviderUtility.CreateProvider(string.Empty);
            }

            if (!SecurityProviderCache.CurrentProvider.CanChangePassword)
            {
                return(false);
            }
            else
            {
                return(SecurityProviderCache.CurrentProvider.ChangePassword(oldPassword, newPassword));
            }
        }
Пример #17
0
        /// <summary>
        /// Resets user password.
        /// </summary>
        /// <param name="securityAnswer">Answer to user's security question.</param>
        /// <returns>true if password is reset, otherwise false.</returns>
        public bool ResetPassword(string securityAnswer)
        {
            if (SecurityProviderCache.CurrentProvider == null)
            {
                SecurityProviderCache.CurrentProvider = SecurityProviderUtility.CreateProvider(string.Empty);
            }

            if (!SecurityProviderCache.CurrentProvider.CanResetPassword)
            {
                return(false);
            }
            else
            {
                return(SecurityProviderCache.CurrentProvider.ResetPassword(securityAnswer));
            }
        }
Пример #18
0
        /// <summary>
        /// Resets user password.
        /// </summary>
        /// <param name="sender">Source of this event.</param>
        /// <param name="e">Arguments of this event.</param>
        protected void ResetFinalButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Initialize the security provider.
                ISecurityProvider provider = SecurityProviderUtility.CreateProvider(ResetPasswordUsername.Text);

                if (provider.CanResetPassword)
                {
                    // Attempt to reset password.
                    if (provider.ResetPassword(ResetPasswordSecurityAnswer.Text))
                    {
                        // Password reset was successful.
                        ShowMessage("Password reset request has been processed.", false);
                    }
                    else
                    {
                        // Show why password reset failed.
                        if (!ShowFailureReason(provider))
                        {
                            ShowMessage("Password reset was not successful.", true);
                        }
                    }
                }
                else
                {
                    // Resetting password is not supported.
                    ShowMessage("Account does not support password reset.", true);
                }
            }
            catch (SecurityException ex)
            {
                // Show security related error messages.
                ShowMessage(ex.Message.EnsureEnd('.'), true);
            }
            catch (Exception ex)
            {
                // Show ambiguous message for other errors.
                ShowMessage("Password reset failed due to an unexpected error.", true);
                System.Diagnostics.Trace.WriteLine(string.Format("Password reset error: \r\n  {0}", ex));
            }
            finally
            {
                ResetPasswordSecurityAnswer.Focus();
            }
        }
Пример #19
0
        /// <summary>
        /// Checks if user password can be reset.
        /// </summary>
        /// <param name="sender">Source of this event.</param>
        /// <param name="e">Arguments of this event.</param>
        protected void ResetCheckButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Initialize the security provider.
                ISecurityProvider provider = SecurityProviderUtility.CreateProvider(ResetPasswordUsername.Text);

                if (provider.CanResetPassword)
                {
                    // Proceed to resetting password.
                    if (!string.IsNullOrEmpty(provider.UserData.SecurityQuestion) && !string.IsNullOrEmpty(provider.UserData.SecurityAnswer))
                    {
                        ViewState.Add(UsernameKey, ResetPasswordUsername.Text);
                        ViewState.Add("SecurityQuestion", provider.UserData.SecurityQuestion);

                        Page.ClientScript.RegisterStartupScript(Page.GetType(), "PostBack", Page.ClientScript.GetPostBackEventReference(Page, null), true);
                    }
                    else
                    {
                        ShowMessage("Security question and answer must be set to reset password.", true);
                    }
                }
                else
                {
                    // Resetting password is not supported.
                    ShowMessage("Account does not support password reset.", true);
                }
            }
            catch (SecurityException ex)
            {
                // Show security related error messages.
                ShowMessage(ex.Message.EnsureEnd('.'), true);
            }
            catch (Exception ex)
            {
                // Show ambiguous message for other errors.
                ShowMessage("Password reset failed due to an unexpected error.", true);
                System.Diagnostics.Trace.WriteLine(string.Format("Password reset error: \r\n  {0}", ex));
            }
            finally
            {
                ResetPasswordUsername.Focus();
            }
        }
Пример #20
0
        private void SecureForm_Load(object sender, EventArgs e)
        {
            // Don't proceed if the form is opened in design mode.
            if (DesignMode)
            {
                return;
            }

            // Check if the resource is excluded from being secured.
            string resource = GetResourceName();

            if (!SecurityProviderUtility.IsResourceSecurable(resource))
            {
                return;
            }

            // Setup thread principal to current windows principal.
            if (!(Thread.CurrentPrincipal is WindowsPrincipal))
            {
                Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
            }

            // Setup the security provider for role-based security.
            if ((object)SecurityProviderCache.CurrentProvider == null)
            {
                SecurityProviderCache.CurrentProvider = SecurityProviderUtility.CreateProvider(string.Empty);
            }

            // Verify that the current thread principal has been authenticated.
            if (!Thread.CurrentPrincipal.Identity.IsAuthenticated)
            {
                throw new SecurityException(string.Format("Authentication failed for user '{0}'", Thread.CurrentPrincipal.Identity.Name));
            }

            // Perform a top-level permission check on the resource being accessed.
            if (!SecurityProviderUtility.IsResourceAccessible(resource))
            {
                throw new SecurityException(string.Format("Access to '{0}' is denied", resource));
            }
        }
Пример #21
0
        private void Connect(string username, string password)
        {
            m_clientHelper.Username = username.ToNonNullString();

            // If the communications channel is secured or the user
            // has entered a blank password, send the password as-is
            if (string.IsNullOrEmpty(password) || m_clientHelper.RemotingClient is TlsClient)
            {
                m_clientHelper.Password = password.ToNonNullString();
                Connect();
            }

            // If the client fails to connect with the as-is password,
            // attempt to connect again with an encrypted password
            // because the server may only be authenticating against
            // the encrypted password
            if (!m_clientHelper.RemotingClient.Enabled && !string.IsNullOrEmpty(password))
            {
                m_clientHelper.Password = SecurityProviderUtility.EncryptPassword(password);
                Connect();
            }
        }
Пример #22
0
        private ActionResult ValidateAdminRequest()
        {
            string            username         = HttpContext.User.Identity.Name;
            ISecurityProvider securityProvider = SecurityProviderUtility.CreateProvider(username);

            securityProvider.PassthroughPrincipal = HttpContext.User;

            if (!securityProvider.Authenticate())
            {
                return(new HttpStatusCodeResult(HttpStatusCode.Forbidden));
            }

            SecurityIdentity  approverIdentity  = new SecurityIdentity(securityProvider);
            SecurityPrincipal approverPrincipal = new SecurityPrincipal(approverIdentity);

            if (!approverPrincipal.IsInRole("Administrator"))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.Forbidden));
            }

            return(null);
        }
Пример #23
0
        private void Application_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            // Check if access to resource is to be secured.
            string resource = GetResourceName();

            if (!IsAccessSecured(resource))
            {
                return;
            }

            SecurityPrincipal securityPrincipal = Thread.CurrentPrincipal as SecurityPrincipal;

            if ((object)securityPrincipal == null)
            {
                ISecurityProvider securityProvider = SecurityProviderCache.CreateProvider(Thread.CurrentPrincipal.Identity.Name);
                securityProvider.PassthroughPrincipal = Thread.CurrentPrincipal;
                securityProvider.Authenticate();

                SecurityIdentity securityIdentity = new SecurityIdentity(securityProvider);
                securityPrincipal = new SecurityPrincipal(securityIdentity);

                Thread.CurrentPrincipal = securityPrincipal;
            }

            if (!m_application.User.Identity.IsAuthenticated)
            {
                // Failed to authenticate user.
                Redirect(HttpStatusCode.Unauthorized);
            }

            if (IsAccessRestricted() ||
                !SecurityProviderUtility.IsResourceAccessible(resource, securityPrincipal))
            {
                // User does not have access to the resource.
                Redirect(HttpStatusCode.Forbidden);
            }
        }
Пример #24
0
        private void VerifyAdminUser(IDbConnection connection, string nodeID)
        {
            // Lookup administrator role ID
            IDbCommand command = connection.CreateCommand();

            command.CommandText = string.Format("SELECT ID FROM ApplicationRole WHERE Name = 'Administrator' AND NodeID = {0}", nodeID);
            string adminRoleID  = command.ExecuteScalar().ToNonNullString();
            string databaseType = m_state["newDatabaseType"].ToString();

            adminRoleID = adminRoleID.StartsWith("'") ? adminRoleID : "'" + adminRoleID + "'";

            // Check if there is any user associated with the administrator role ID in the ApplicationRoleUserAccount table.
            // if so that means there is atleast one user associated with that role. So we do not need to take any action.
            // if not that means, user provided on the screen must be attached to this role. Also check if that user exists in
            // the UserAccount table. If so, then get the ID otherwise add user and retrieve ID.
            command.CommandText = string.Format("SELECT COUNT(*) FROM ApplicationRoleUserAccount WHERE ApplicationRoleID = {0}", adminRoleID);
            if (Convert.ToInt32(command.ExecuteScalar()) == 0)
            {
                if (m_state.ContainsKey("adminUserName")) //i.e. if security setup screen was displayed during setup.
                {
                    command.CommandText = string.Format("Select ID FROM UserAccount WHERE Name = '{0}'", m_state["adminUserName"].ToString());
                    string adminUserID = command.ExecuteScalar().ToNonNullString();

                    if (!string.IsNullOrEmpty(adminUserID)) //if user exists then attach it to admin role and we'll be done with it.
                    {
                        adminUserID         = adminUserID.StartsWith("'") ? adminUserID : "'" + adminUserID + "'";
                        command.CommandText = string.Format("INSERT INTO ApplicationRoleUserAccount(ApplicationRoleID, UserAccountID) VALUES({0}, {1})", adminRoleID, adminUserID);
                        command.ExecuteNonQuery();
                    }
                    else //we need to add user to the UserAccount table and then attach it to admin role.
                    {
                        bool databaseIsOracle = (databaseType == "Oracle");
                        char paramChar        = databaseIsOracle ? ':' : '@';

                        // Add Administrative User.
                        IDbCommand adminCredentialCommand = connection.CreateCommand();
                        if (m_state["authenticationType"].ToString() == "windows")
                        {
                            IDbDataParameter nameParameter      = adminCredentialCommand.CreateParameter();
                            IDbDataParameter createdByParameter = adminCredentialCommand.CreateParameter();
                            IDbDataParameter updatedByParameter = adminCredentialCommand.CreateParameter();

                            nameParameter.ParameterName      = paramChar + "name";
                            createdByParameter.ParameterName = paramChar + "createdBy";
                            updatedByParameter.ParameterName = paramChar + "updatedBy";

                            nameParameter.Value      = m_state["adminUserName"].ToString();
                            createdByParameter.Value = Thread.CurrentPrincipal.Identity.Name;
                            updatedByParameter.Value = Thread.CurrentPrincipal.Identity.Name;

                            adminCredentialCommand.Parameters.Add(nameParameter);
                            adminCredentialCommand.Parameters.Add(createdByParameter);
                            adminCredentialCommand.Parameters.Add(updatedByParameter);

                            if (databaseIsOracle)
                            {
                                adminCredentialCommand.CommandText = string.Format("INSERT INTO UserAccount(Name, DefaultNodeID, CreatedBy, UpdatedBy) VALUES(:name, {0}, :createdBy, :updatedBy)", nodeID);
                            }
                            else
                            {
                                adminCredentialCommand.CommandText = string.Format("INSERT INTO UserAccount(Name, DefaultNodeID, CreatedBy, UpdatedBy) VALUES(@name, {0}, @createdBy, @updatedBy)", nodeID);
                            }
                        }
                        else
                        {
                            IDbDataParameter nameParameter      = adminCredentialCommand.CreateParameter();
                            IDbDataParameter passwordParameter  = adminCredentialCommand.CreateParameter();
                            IDbDataParameter firstNameParameter = adminCredentialCommand.CreateParameter();
                            IDbDataParameter lastNameParameter  = adminCredentialCommand.CreateParameter();
                            IDbDataParameter createdByParameter = adminCredentialCommand.CreateParameter();
                            IDbDataParameter updatedByParameter = adminCredentialCommand.CreateParameter();

                            nameParameter.ParameterName      = paramChar + "name";
                            passwordParameter.ParameterName  = paramChar + "password";
                            firstNameParameter.ParameterName = paramChar + "firstName";
                            lastNameParameter.ParameterName  = paramChar + "lastName";
                            createdByParameter.ParameterName = paramChar + "createdBy";
                            updatedByParameter.ParameterName = paramChar + "updatedBy";

                            nameParameter.Value      = m_state["adminUserName"].ToString();
                            passwordParameter.Value  = SecurityProviderUtility.EncryptPassword(m_state["adminPassword"].ToString());
                            firstNameParameter.Value = m_state["adminUserFirstName"].ToString();
                            lastNameParameter.Value  = m_state["adminUserLastName"].ToString();
                            createdByParameter.Value = Thread.CurrentPrincipal.Identity.Name;
                            updatedByParameter.Value = Thread.CurrentPrincipal.Identity.Name;

                            adminCredentialCommand.Parameters.Add(nameParameter);
                            adminCredentialCommand.Parameters.Add(passwordParameter);
                            adminCredentialCommand.Parameters.Add(firstNameParameter);
                            adminCredentialCommand.Parameters.Add(lastNameParameter);
                            adminCredentialCommand.Parameters.Add(createdByParameter);
                            adminCredentialCommand.Parameters.Add(updatedByParameter);

                            if (databaseIsOracle)
                            {
                                adminCredentialCommand.CommandText = string.Format("INSERT INTO UserAccount(Name, Password, FirstName, LastName, DefaultNodeID, UseADAuthentication, CreatedBy, UpdatedBy) VALUES" +
                                                                                   "(:name, :password, :firstName, :lastName, {0}, 0, :createdBy, :updatedBy)", nodeID);
                            }
                            else
                            {
                                adminCredentialCommand.CommandText = string.Format("INSERT INTO UserAccount(Name, Password, FirstName, LastName, DefaultNodeID, UseADAuthentication, CreatedBy, UpdatedBy) VALUES" +
                                                                                   "(@name, @password, @firstName, @lastName, {0}, 0, @createdBy, @updatedBy)", nodeID);
                            }
                        }

                        adminCredentialCommand.ExecuteNonQuery();

                        // Get the admin user ID from the database.
                        IDataReader userIdReader = null;

                        IDbDataParameter newNameParameter = adminCredentialCommand.CreateParameter();

                        newNameParameter.ParameterName = paramChar + "name";
                        newNameParameter.Value         = m_state["adminUserName"].ToString();

                        adminCredentialCommand.CommandText = "SELECT ID FROM UserAccount WHERE Name = " + paramChar + "name";
                        adminCredentialCommand.Parameters.Clear();
                        adminCredentialCommand.Parameters.Add(newNameParameter);
                        using (userIdReader = adminCredentialCommand.ExecuteReader())
                        {
                            if (userIdReader.Read())
                            {
                                adminUserID = userIdReader["ID"].ToNonNullString();
                            }
                        }

                        // Assign Administrative User to Administrator Role.
                        if (!string.IsNullOrEmpty(adminRoleID) && !string.IsNullOrEmpty(adminUserID))
                        {
                            adminUserID = adminUserID.StartsWith("'") ? adminUserID : "'" + adminUserID + "'";
                            adminCredentialCommand.CommandText = string.Format("INSERT INTO ApplicationRoleUserAccount(ApplicationRoleID, UserAccountID) VALUES ({0}, {1})", adminRoleID, adminUserID);
                            adminCredentialCommand.ExecuteNonQuery();
                        }
                    }
                }
            }
        }
Пример #25
0
        /// <summary>
        /// Handles service start event.
        /// </summary>
        /// <param name="args">Service start arguments.</param>
        public virtual void Start(string[] args)
        {
            string    userInput = null;
            Arguments arguments = new Arguments(string.Join(" ", args));

            if (arguments.Exists("OrderedArg1") && arguments.Exists("restart"))
            {
                string serviceName = arguments["OrderedArg1"];

                if (Common.IsPosixEnvironment)
                {
                    string serviceCommand = FilePath.GetAbsolutePath(serviceName);

                    try
                    {
                        Command.Execute(serviceCommand, "stop");
                    }
                    catch (Exception ex)
                    {
                        WriteLine("Failed to stop the {0} daemon: {1}\r\n", serviceName, ex.Message);
                    }

                    try
                    {
                        Command.Execute(serviceCommand, "start");
                    }
                    catch (Exception ex)
                    {
                        WriteLine("Failed to restart the {0} daemon: {1}\r\n", serviceName, ex.Message);
                    }
                }
                else
                {
                    // Attempt to access service controller for the specified Windows service
                    ServiceController serviceController = ServiceController.GetServices().SingleOrDefault(svc => string.Compare(svc.ServiceName, serviceName, StringComparison.OrdinalIgnoreCase) == 0);

                    if (serviceController != null)
                    {
                        try
                        {
                            if (serviceController.Status == ServiceControllerStatus.Running)
                            {
                                WriteLine("Attempting to stop the {0} Windows service...", serviceName);

                                serviceController.Stop();

                                // Can't wait forever for service to stop, so we time-out after 20 seconds
                                serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(20.0D));

                                if (serviceController.Status == ServiceControllerStatus.Stopped)
                                {
                                    WriteLine("Successfully stopped the {0} Windows service.", serviceName);
                                }
                                else
                                {
                                    WriteLine("Failed to stop the {0} Windows service after trying for 20 seconds...", serviceName);
                                }

                                // Add an extra line for visual separation of service termination status
                                WriteLine("");
                            }
                        }
                        catch (Exception ex)
                        {
                            WriteLine("Failed to stop the {0} Windows service: {1}\r\n", serviceName, ex.Message);
                        }
                    }

                    // If the service failed to stop or it is installed as stand-alone debug application, we try to forcibly stop any remaining running instances
                    try
                    {
                        Process[] instances = Process.GetProcessesByName(serviceName);

                        if (instances.Length > 0)
                        {
                            int total = 0;
                            WriteLine("Attempting to stop running instances of the {0}...", serviceName);

                            // Terminate all instances of service running on the local computer
                            foreach (Process process in instances)
                            {
                                process.Kill();
                                total++;
                            }

                            if (total > 0)
                            {
                                WriteLine("Stopped {0} {1} instance{2}.", total, serviceName, total > 1 ? "s" : "");
                            }

                            // Add an extra line for visual separation of process termination status
                            WriteLine("");
                        }
                    }
                    catch (Exception ex)
                    {
                        WriteLine("Failed to terminate running instances of the {0}: {1}\r\n", serviceName, ex.Message);
                    }

                    // Attempt to restart Windows service...
                    if (serviceController != null)
                    {
                        try
                        {
                            // Refresh state in case service process was forcibly stopped
                            serviceController.Refresh();

                            if (serviceController.Status != ServiceControllerStatus.Running)
                            {
                                serviceController.Start();
                            }
                        }
                        catch (Exception ex)
                        {
                            WriteLine("Failed to restart the {0} Windows service: {1}\r\n", serviceName, ex.Message);
                        }
                    }
                }
            }
            else
            {
                if (arguments.Exists("server"))
                {
                    // Override default settings with user provided input.
                    m_clientHelper.PersistSettings    = false;
                    m_remotingClient.PersistSettings  = false;
                    m_remotingClient.ConnectionString = string.Format("Server={0}", arguments["server"]);
                }

                string password           = null;
                long   lastConnectAttempt = 0;

                // Connect to service and send commands.
                while (!string.Equals(userInput, "Exit", StringComparison.OrdinalIgnoreCase))
                {
                    try
                    {
                        // Do not reattempt connection too quickly
                        while (DateTime.UtcNow.Ticks - lastConnectAttempt < Ticks.PerSecond)
                        {
                            Thread.Sleep(200);
                        }

                        lastConnectAttempt = DateTime.UtcNow.Ticks;
                        m_clientHelper.Connect();

                        if (!m_clientHelper.RemotingClient.Enabled)
                        {
                            continue;
                        }

                        // If connection attempt failed with provided credentials, try once more with direct authentication
                        // but only when transport is secured
                        if (!m_authenticated && !string.IsNullOrEmpty(password) && m_clientHelper.RemotingClient is TlsClient)
                        {
                            m_clientHelper.Disconnect();
                            m_clientHelper.Password = password;
                            m_clientHelper.Connect();
                        }

                        if (!m_authenticated)
                        {
                            string         username;
                            UserInfo       userInfo;
                            StringBuilder  passwordBuilder = new StringBuilder();
                            StringBuilder  prompt          = new StringBuilder();
                            ConsoleKeyInfo key;

                            lock (m_displayLock)
                            {
                                prompt.AppendLine();
                                prompt.AppendLine();
                                prompt.AppendLine("Connection to the service was rejected due to authentication failure.");
                                prompt.AppendLine("Enter the credentials to be used for authentication with the service.");
                                prompt.AppendLine();
                                Write(prompt.ToString());

                                // Capture the user name.
                                Write("Enter user name: ");

                                username = System.Console.ReadLine();

                                // Capture the password.
                                Write("Enter password: "******"Exit", StringComparison.OrdinalIgnoreCase))
                        {
                            // Wait for a command from the user.
                            userInput = System.Console.ReadLine();

                            // Write a blank line to the console.
                            WriteLine();

                            if (!string.IsNullOrWhiteSpace(userInput))
                            {
                                // The user typed in a command and didn't just hit <ENTER>.
                                switch (userInput.ToUpper())
                                {
                                case "CLS":
                                    // User wants to clear the console window.
                                    System.Console.Clear();
                                    break;

                                case "EXIT":
                                    // User wants to exit the telnet session with the service.
                                    if (m_telnetActive)
                                    {
                                        userInput = string.Empty;
                                        m_clientHelper.SendRequest("Telnet -disconnect");
                                    }
                                    break;

                                case "LOGIN":
                                    m_clientHelper.Username = null;
                                    m_clientHelper.Password = null;
                                    m_authenticated         = false;
                                    break;

                                default:
                                    // User wants to send a request to the service.
                                    m_clientHelper.SendRequest(userInput);
                                    if (string.Compare(userInput, "Help", StringComparison.OrdinalIgnoreCase) == 0)
                                    {
                                        DisplayHelp();
                                    }

                                    break;
                                }
                            }
                        }

                        m_clientHelper.Disconnect();
                    }
                    catch (Exception)
                    {
                        // Errors during the outer connection loop
                        // should simply force an attempt to reconnect
                        m_clientHelper.Disconnect();
                    }
                }
            }
        }
Пример #26
0
        private void SecureWindow_Initialized(object sender, EventArgs e)
        {
            // Don't proceed if the window is opened in design mode
            if (DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }

            // Check if the resource is excluded from being secured
            string resource = GetResourceName();

            if (ResourceAccessiblity != ResourceAccessiblityMode.AlwaysIncluded &&
                (ResourceAccessiblity == ResourceAccessiblityMode.AlwaysExcluded ||
                 !SecurityProviderUtility.IsResourceSecurable(resource)))
            {
                return;
            }

            try
            {
                // Setup the security provider for role-based security
                ISecurityProvider securityProvider = SecurityProviderCache.CreateProvider(WindowsIdentity.GetCurrent().Name);
                securityProvider.PassthroughPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
                securityProvider.Authenticate();

                SecurityIdentity securityIdentity = new SecurityIdentity(securityProvider);
                SecurityPrincipal = new SecurityPrincipal(securityIdentity);
            }
            catch (Exception ex)
            {
                ShowSecurityDialog(DisplayType.AccessDenied, "Error loading security provider: " + ex.Message);
                return;
            }

            // Verify that the security principal has been authenticated
            if (!SecurityPrincipal.Identity.IsAuthenticated || ForceLoginDisplay)
            {
                ISecurityProvider securityProvider = SecurityPrincipal.Identity.Provider;

                // See if user's password has expired
                if (securityProvider.UserData.IsDefined && securityProvider.UserData.PasswordChangeDateTime <= DateTime.UtcNow)
                {
                    ShowSecurityDialog(DisplayType.ChangePassword, string.Format("Your password has expired. {0} You must change your password to continue.", securityProvider.AuthenticationFailureReason));
                }
                else
                {
                    ShowSecurityDialog(DisplayType.Login);
                }
            }

            // Perform a top-level permission check on the resource being accessed
            if (!string.IsNullOrEmpty(resource))
            {
                // Stay in a dialog display loop until either access to resource is available or user exits
                while (!m_shutdownRequested && !IsResourceAccessible(resource))
                {
                    // Access to resource is denied
                    ShowSecurityDialog(DisplayType.AccessDenied);
                }
            }
        }
Пример #27
0
        /// <summary>
        /// Logins the user.
        /// </summary>
        /// <param name="sender">Source of this event.</param>
        /// <param name="e">Arguments of this event.</param>
        private void ButtonLogin_Click(object sender, RoutedEventArgs e)
        {
            UserInfo userInfo;
            WindowsImpersonationContext impersonationContext = null;
            ISecurityProvider           provider;

            try
            {
                // Determine whether we need to try impersonating the user
                userInfo = new UserInfo(TextBoxUserName.Text);

                // If the application is unable to access the domain, possibly because the local user
                // running the application does not have access to domain objects, it's possible that
                // the user logging in does have access to the domain. So we attempt to impersonate the
                // user logging in to allow authentication to proceed
                if (!userInfo.DomainRespondsForUser && TryImpersonate(userInfo.LoginID, TextBoxPassword.Password, out impersonationContext))
                {
                    try
                    {
                        // Working around a known issue - DirectorySearcher will often throw
                        // an exception the first time it is used after impersonating another
                        // user so we get that out of the way here
                        userInfo.Initialize();
                    }
                    catch (InitializationException)
                    {
                        // Exception is expected so we ignore it
                    }
                }

                // Initialize the security provider
                provider = SecurityProviderUtility.CreateProvider(TextBoxUserName.Text);

                // Attempt to authenticate user
                if (provider.Authenticate(TextBoxPassword.Password))
                {
                    // Setup security provider for subsequent uses
                    SecurityProviderCache.CurrentProvider = provider;
                    ClearErrorMessage();
                    ExitSuccess = true;
                }
                else
                {
                    // Verify their password hasn't expired
                    if (provider.UserData.IsDefined && provider.UserData.PasswordChangeDateTime <= DateTime.UtcNow)
                    {
                        // Display password expired message
                        DisplayErrorMessage(string.Format("Your password has expired. {0} You must change your password to continue.", provider.AuthenticationFailureReason));
                        m_displayType = DisplayType.ChangePassword;
                        ManageScreenVisualization();
                        TextBoxPassword.Password = "";
                    }
                    else
                    {
                        // Display login failure message
                        DisplayErrorMessage("The username or password is invalid. " + provider.AuthenticationFailureReason);

                        if (string.IsNullOrWhiteSpace(TextBoxUserName.Text))
                        {
                            TextBoxUserName.Focus();
                        }
                        else
                        {
                            TextBoxPassword.Focus();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayErrorMessage("Login failed: " + ex.Message);

                if (string.IsNullOrWhiteSpace(TextBoxUserName.Text))
                {
                    TextBoxUserName.Focus();
                }
                else
                {
                    TextBoxPassword.Focus();
                }
            }
            finally
            {
                if ((object)impersonationContext != null)
                {
                    impersonationContext.Undo();
                    impersonationContext.Dispose();
                }
            }
        }
Пример #28
0
        /// <summary>
        /// Logins the user.
        /// </summary>
        /// <param name="sender">Source of this event.</param>
        /// <param name="e">Arguments of this event.</param>
        protected void LoginButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Initialize the security provider.
                ISecurityProvider provider = SecurityProviderUtility.CreateProvider(LoginUsername.Text);

                if (provider.Authenticate(LoginPassword.Text))
                {
                    // Credentials were authenticated successfully.
                    SecurityProviderCache.CurrentProvider = provider;
                    if (RememberUsername.Checked)
                    {
                        Response.Cookies[CookieName][UsernameKey] = LoginUsername.Text;
                        Response.Cookies[CookieName].Expires      = DateTime.Now.AddYears(1);
                    }
                    else
                    {
                        Response.Cookies[CookieName][UsernameKey] = string.Empty;
                        Response.Cookies[CookieName].Expires      = DateTime.Now.AddYears(-1);
                    }

                    // Redirect to the referring page.
                    Response.Redirect(GetReferrerUrl(), false);
                }
                else
                {
                    // Check why authentication failed.
                    if (provider.UserData.PasswordChangeDateTime != DateTime.MinValue &&
                        provider.UserData.PasswordChangeDateTime <= DateTime.UtcNow)
                    {
                        // User must change password.
                        if (provider.CanChangePassword)
                        {
                            Response.Redirect(GetRedirectUrl(PasswordChangeStatusCode), false);
                        }
                        else
                        {
                            ShowMessage("Account password has expired.", true);
                        }
                    }
                    else
                    {
                        // Show why login failed.
                        if (!ShowFailureReason(provider))
                        {
                            ShowMessage("Authentication was not successful.", true);
                        }
                    }
                }
            }
            catch (SecurityException ex)
            {
                // Show security related error messages.
                ShowMessage(ex.Message.EnsureEnd('.'), true);
            }
            catch (Exception ex)
            {
                // Show ambiguous message for other errors.
                ShowMessage("Login failed due to an unexpected error.", true);
                System.Diagnostics.Trace.WriteLine(string.Format("Login error: \r\n  {0}", ex));
            }
            finally
            {
                LoginPassword.Focus();
            }
        }
Пример #29
0
        /// <summary>
        /// Attempts to change user's password.
        /// </summary>
        /// <param name="sender">Source of this event.</param>
        /// <param name="e">Arguments of this event.</param>
        private void ButtonChange_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Check if old and new password are different
                if (TextBoxOldPassword.Password == TextBoxNewPassword.Password)
                {
                    throw new Exception("New password cannot be same as old password.");
                }

                // Check is new password and confirm password are same
                if (TextBoxNewPassword.Password != TextBoxConfirmPassword.Password)
                {
                    throw new Exception("New password and confirm password should be same.");
                }

                ISecurityProvider provider = SecurityProviderUtility.CreateProvider(TextBoxChangePasswordUserName.Text);

                if (provider.CanChangePassword)
                {
                    // Attempt to change password
                    if (provider.ChangePassword(TextBoxOldPassword.Password, TextBoxNewPassword.Password) &&
                        provider.Authenticate(TextBoxNewPassword.Password))
                    {
                        // Password changed and authenticated successfully
                        DisplayErrorMessage("Password changed successfully.");

                        // Setup security provider for subsequent uses
                        SecurityProviderCache.CurrentProvider = provider;
                        ClearErrorMessage();
                        ExitSuccess = true;
                    }
                    else
                    {
                        // Show why password change failed
                        if (!ShowFailureReason(provider))
                        {
                            if (!provider.UserData.IsAuthenticated)
                            {
                                DisplayErrorMessage("Authentication was not successful.");
                            }
                            else
                            {
                                DisplayErrorMessage("Password change was not successful.");
                            }

                            if (string.IsNullOrWhiteSpace(TextBoxChangePasswordUserName.Text))
                            {
                                TextBoxChangePasswordUserName.Focus();
                            }
                            else
                            {
                                TextBoxOldPassword.Focus();
                            }
                        }
                    }
                }
                else
                {
                    DisplayErrorMessage("Account does not support password change.");
                }
            }
            catch (Exception ex)
            {
                DisplayErrorMessage("Change password failed: " + ex.Message);
                TextBoxOldPassword.Focus();
            }
        }
Пример #30
0
 /// <summary>
 /// Determines if access to the requested <paramref name="resource"/> is to be secured.
 /// </summary>
 /// <param name="resource">Name of the resource being requested.</param>
 /// <returns>True if access to the resource is to be secured, otherwise False.</returns>
 protected virtual bool IsAccessSecured(string resource)
 {
     return(SecurityProviderUtility.IsResourceSecurable(GetResourceName()));
 }