public WindowsUserInfo(UserInfo parent) { m_parent = parent; // Attempt to attach to power mode changed system event try { SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged; } catch { // This event will not be raised when running from a Windows service since // a service does not establish a message loop. } }
/// <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"]); } 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; if (!m_authenticationFailure) { // If there has been no authentication // failure, connect normally Connect(); } else { UserInfo userInfo; StringBuilder username = new StringBuilder(); StringBuilder password = new StringBuilder(); // If there has been an authentication failure, // prompt the user for new credentials PromptForCredentials(username, password); try { // Attempt to set network credentials used when attempting AD authentication userInfo = new UserInfo(username.ToString()); userInfo.Initialize(); SetNetworkCredential(new NetworkCredential(userInfo.LoginID, password.ToString())); } catch { // Even if this fails, we can still pass along user credentials } Connect(username.ToString(), password.ToString()); } while (m_authenticated && m_clientHelper.Enabled && !string.Equals(userInput, "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_authenticated = false; m_authenticationFailure = true; 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(); } } } }
private void HomeUserControl_Loaded(object sender, RoutedEventArgs e) { if (!CommonFunctions.CurrentPrincipal.IsInRole("Administrator")) ButtonRestart.IsEnabled = false; //if (!CommonFunctions.CurrentPrincipal.IsInRole("Administrator,Editor")) // ButtonInputWizard.IsEnabled = false; m_windowsServiceClient = CommonFunctions.GetWindowsServiceClient(); if (m_windowsServiceClient == null || m_windowsServiceClient.Helper.RemotingClient.CurrentState != ClientState.Connected) { ButtonRestart.IsEnabled = false; } else { m_windowsServiceClient.Helper.ReceivedServiceResponse += Helper_ReceivedServiceResponse; CommonFunctions.SendCommandToService("Health -actionable"); CommonFunctions.SendCommandToService("Version -actionable"); CommonFunctions.SendCommandToService("Status -actionable"); CommonFunctions.SendCommandToService("Time -actionable"); m_eventHandlerRegistered = true; } m_refreshTimer = new DispatcherTimer(); m_refreshTimer.Interval = TimeSpan.FromSeconds(5); m_refreshTimer.Tick += RefreshTimer_Tick; m_refreshTimer.Start(); if (IntPtr.Size == 8) TextBlockInstance.Text = "64-bit"; else TextBlockInstance.Text = "32-bit"; TextBlockLocalTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"); Version appVersion = AssemblyInfo.EntryAssembly.Version; TextBlockManagerVersion.Text = appVersion.Major + "." + appVersion.Minor + "." + appVersion.Build + ".0"; try { using (AdoDataConnection database = new AdoDataConnection(CommonFunctions.DefaultSettingsCategory)) { TextBlockDatabaseType.Text = database.DatabaseType.ToString(); try { if (database.IsSqlite || database.IsJetEngine) { // Extract database file name from connection string for file centric databases TextBlockDatabaseName.Text = FilePath.GetFileName(database.Connection.ConnectionString.ParseKeyValuePairs()["Data Source"]); } else if (database.IsOracle) { // Extract user name from connection string for Oracle databases TextBlockDatabaseName.Text = database.Connection.ConnectionString.ParseKeyValuePairs()["User Id"]; } else { TextBlockDatabaseName.Text = database.Connection.Database; } } catch { // Fall back on database name if file anything fails TextBlockDatabaseName.Text = database.Connection.Database; } } } catch { TextBlockDatabaseName.Text = "Not Avaliable"; } try { using (UserInfo info = new UserInfo(CommonFunctions.CurrentUser)) { if (info.Exists) TextBlockUser.Text = info.LoginID; else TextBlockUser.Text = CommonFunctions.CurrentUser; } } catch { TextBlockUser.Text = CommonFunctions.CurrentUser; } ((HorizontalAxis)ChartPlotterDynamic.MainHorizontalAxis).LabelProvider.LabelStringFormat = ""; //Remove legend on the right. Panel legendParent = (Panel)ChartPlotterDynamic.Legend.ContentGrid.Parent; if (legendParent != null) legendParent.Children.Remove(ChartPlotterDynamic.Legend.ContentGrid); ChartPlotterDynamic.NewLegendVisible = false; m_xAxisDataCollection = new int[m_numberOfPointsToPlot]; for (int i = 0; i < m_numberOfPointsToPlot; i++) m_xAxisDataCollection[i] = i; m_xAxisBindingCollection = new EnumerableDataSource<int>(m_xAxisDataCollection); m_xAxisBindingCollection.SetXMapping(x => x); ComboBoxDevice.ItemsSource = Device.GetLookupList(null); if (ComboBoxDevice.Items.Count > 0) ComboBoxDevice.SelectedIndex = 0; }
/// <summary> /// Changes user password in the backend data store. /// </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> /// <remarks> /// This method always returns <c>false</c> under Mono deployments. /// </remarks> public override bool ChangePassword(string oldPassword, string newPassword) { // Check prerequisites if (!UserData.IsDefined || UserData.IsDisabled || UserData.IsLockedOut) return false; UserInfo user = null; WindowsImpersonationContext context = null; try { string ldapPath = GetLdapPath(); // Create user info object using specified LDAP path if provided if (string.IsNullOrEmpty(ldapPath)) user = new UserInfo(UserData.Username); else user = new UserInfo(UserData.Username, ldapPath); // Initialize user entry user.PersistSettings = true; user.Initialize(); // Impersonate privileged user context = user.ImpersonatePrivilegedAccount(); // Change user password user.ChangePassword(oldPassword, newPassword); return true; } catch (TargetInvocationException ex) { // Propagate password change error if ((object)ex.InnerException == null) throw new SecurityException(ex.Message, ex); else throw new SecurityException(ex.InnerException.Message, ex); } finally { if ((object)user != null) user.Dispose(); if ((object)context != null) UserInfo.EndImpersonation(context); RefreshData(); } }
/// <summary> /// Refreshes the <see cref="UserData"/> from the backend data store loading user groups into desired collection. /// </summary> /// <param name="groupCollection">Target collection for user groups.</param> /// <param name="providerID">Unique provider ID used to distinguish cached user data that may be different based on provider.</param> /// <returns>true if <see cref="SecurityProviderBase.UserData"/> is refreshed, otherwise false.</returns> protected virtual bool RefreshData(List<string> groupCollection, int providerID) { if ((object)groupCollection == null) throw new ArgumentNullException("groupCollection"); if (string.IsNullOrEmpty(UserData.Username)) return false; // Initialize user data UserData.Initialize(); // Populate user data UserInfo user = null; UserDataCache userDataCache = null; try { // Get current local user data cache if (m_enableOfflineCaching) { userDataCache = UserDataCache.GetCurrentCache(providerID); userDataCache.RetryDelayInterval = m_cacheRetryDelayInterval; userDataCache.MaximumRetryAttempts = m_cacheMaximumRetryAttempts; userDataCache.ReloadOnChange = false; userDataCache.AutoSave = true; userDataCache.Load(); } // Create user info object using specified LDAP path if provided string ldapPath = GetLdapPath(); if (string.IsNullOrEmpty(ldapPath)) user = new UserInfo(UserData.Username); else user = new UserInfo(UserData.Username, ldapPath); // Make sure to load privileged user credentials from config file if present. user.PersistSettings = true; // Attempt to determine if user exists (this will initialize user object if not initialized already) UserData.IsDefined = user.Exists; UserData.LoginID = user.LoginID; if (UserData.IsDefined) { // Fill in user information from domain data if it is available if (user.DomainRespondsForUser) { // Copy relevant user information UserData.FirstName = user.FirstName; UserData.LastName = user.LastName; UserData.CompanyName = user.Company; UserData.PhoneNumber = user.Telephone; UserData.EmailAddress = user.Email; try { UserData.IsLockedOut = user.AccountIsLockedOut; UserData.IsDisabled = user.AccountIsDisabled; } catch (SecurityException) { // AD may restrict information on account availability, if so, have to make a safe assumption: UserData.IsLockedOut = true; UserData.IsDisabled = true; } UserData.PasswordChangeDateTime = user.NextPasswordChangeDate; UserData.AccountCreatedDateTime = user.AccountCreationDate; // Assign all groups the user is a member of foreach (string groupName in user.Groups) { if (!groupCollection.Contains(groupName, StringComparer.OrdinalIgnoreCase)) groupCollection.Add(groupName); } if ((object)userDataCache != null) { // Cache user data so that information can be loaded later if domain is unavailable userDataCache[UserData.LoginID] = UserData; // Wait for pending serialization since cache is scoped locally to this method and will be disposed before exit userDataCache.WaitForSave(); } } else { // Attempt to load previously cached user information when domain is offline UserData cachedUserData; if ((object)userDataCache != null && userDataCache.TryGetUserData(UserData.LoginID, out cachedUserData)) { // Copy relevant cached user information UserData.FirstName = cachedUserData.FirstName; UserData.LastName = cachedUserData.LastName; UserData.CompanyName = cachedUserData.CompanyName; UserData.PhoneNumber = cachedUserData.PhoneNumber; UserData.EmailAddress = cachedUserData.EmailAddress; UserData.IsLockedOut = cachedUserData.IsLockedOut; UserData.IsDisabled = cachedUserData.IsDisabled; UserData.Roles.AddRange(cachedUserData.Roles); UserData.Groups.AddRange(cachedUserData.Groups); // If domain is offline, a password change cannot be initiated UserData.PasswordChangeDateTime = DateTime.MaxValue; UserData.AccountCreatedDateTime = cachedUserData.AccountCreatedDateTime; } else { // No previous user data was cached but Windows allowed authentication, so all we know is that user exists UserData.IsLockedOut = false; UserData.IsDisabled = false; UserData.PasswordChangeDateTime = DateTime.MaxValue; UserData.AccountCreatedDateTime = DateTime.MinValue; } } } return UserData.IsDefined; } finally { if ((object)user != null) { user.PersistSettings = false; user.Dispose(); } if ((object)userDataCache != null) userDataCache.Dispose(); } }
public UnixUserInfo(UserInfo parent) { m_parent = parent; }
public static ActionResult AuthenticateServiceAccountAction(Session session) { UserInfo serviceAccountInfo; IPrincipal servicePrincipal; string serviceAccount; string servicePassword; string[] splitServiceAccount; string serviceDomain = string.Empty; string serviceUser = string.Empty; bool isSystemAccount; bool isManagedServiceAccount; bool isManagedServiceAccountValid; session.Log("Begin AuthenticateServiceAccountAction"); serviceAccount = session["SERVICEACCOUNT"]; servicePassword = session["SERVICEPASSWORD"]; splitServiceAccount = serviceAccount.Split('\\'); switch (splitServiceAccount.Length) { case 1: serviceDomain = UserInfo.CurrentUserID.Split('\\')[0]; serviceUser = splitServiceAccount[0]; break; case 2: serviceDomain = splitServiceAccount[0]; serviceUser = splitServiceAccount[1]; break; } isSystemAccount = serviceAccount.Equals("LocalSystem", StringComparison.OrdinalIgnoreCase) || serviceAccount.StartsWith(@"NT AUTHORITY\", StringComparison.OrdinalIgnoreCase) || serviceAccount.StartsWith(@"NT SERVICE\", StringComparison.OrdinalIgnoreCase); isManagedServiceAccount = serviceAccount.EndsWith("$", StringComparison.Ordinal); if (isSystemAccount) { session["SERVICEPASSWORD"] = string.Empty; session["SERVICEAUTHENTICATED"] = "yes"; } else if (isManagedServiceAccount) { serviceAccountInfo = new UserInfo(serviceAccount); isManagedServiceAccountValid = serviceAccountInfo.Exists && !serviceAccountInfo.AccountIsDisabled && !serviceAccountInfo.AccountIsLockedOut && serviceAccountInfo.GetUserPropertyValue("msDS-HostServiceAccountBL").Split(',')[0].Equals("CN=" + Environment.MachineName, StringComparison.CurrentCultureIgnoreCase); if (isManagedServiceAccountValid) { session["SERVICEPASSWORD"] = string.Empty; session["SERVICEAUTHENTICATED"] = "yes"; } else { session["SERVICEAUTHENTICATED"] = null; } } else { servicePrincipal = UserInfo.AuthenticateUser(serviceDomain, serviceUser, servicePassword); if ((object)servicePrincipal != null && servicePrincipal.Identity.IsAuthenticated) session["SERVICEAUTHENTICATED"] = "yes"; else session["SERVICEAUTHENTICATED"] = null; } session.Log("End AuthenticateServiceAccountAction"); return ActionResult.Success; }
/// <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(); } } }
private static void PrincipalRefreshTimer_Elapsed(object sender, ElapsedEventArgs elapsedEventArgs) { UserInfo userInfo; ISecurityProvider provider; WindowsImpersonationContext impersonationContext; if ((object)s_currentPrincipal != null) { // If user is no longer authenticated, provider session may have expired so provider session will // now be reinitialized. This step will "re-validate" user's current state (e.g., locked-out). if (!SecurityProviderCache.TryGetCachedProvider(s_currentPrincipal.Identity.Name, out provider)) { impersonationContext = null; try { // Determine whether we need to try impersonating the user userInfo = new UserInfo(CurrentUser); // 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, GetCurrentUserPassword(), 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 } } Thread.CurrentPrincipal = s_currentPrincipal; SecurityProviderCache.ReauthenticateCurrentPrincipal(); CurrentPrincipal = Thread.CurrentPrincipal as SecurityPrincipal; } finally { if ((object)impersonationContext != null) { impersonationContext.Undo(); impersonationContext.Dispose(); } } // Rights may have changed -- notify for revalidation of menu commands Application.Current.Dispatcher.BeginInvoke(new Action(OnCurrentPrincipalRefreshed)); } } s_principalRefreshTimer.Start(); }