Esempio n. 1
0
        /// <summary>
        /// Submits a request for administrator rights to the specified host.
        /// </summary>
        /// <param name="hostName">
        /// The name of the host to which the request is submitted.
        /// </param>
        private void RequestAdminRights(string hostName)
        {
            // The address of the remote computer's service host.
            string remoteHostAddress = string.Format("net.tcp://{0}/MakeMeAdmin/Service", hostName);

            // Open a connection to the remote host.
            NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);
            ChannelFactory <IAdminGroup> namedPipeFactory = new ChannelFactory <IAdminGroup>(binding, remoteHostAddress);
            IAdminGroup channel = namedPipeFactory.CreateChannel();

            // Submit a request for administrator rights on the remote host.
            try
            {
                channel.AddUserToAdministratorsGroup();
            }
            catch (System.ServiceModel.EndpointNotFoundException)
            {
                throw;
            }
            catch (Exception)
            {
                throw;
                // TODO: What do we do with this error?
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Occurs when the background operation has completed, has been canceled, or has raised an exception.
        /// </summary>
        /// <param name="sender">
        /// The button state BackgroundWorker object, which triggered the event.
        /// </param>
        /// <param name="e">
        /// Data specific to this event.
        /// </param>
        private void ButtonStateWorkCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            NetNamedPipeBinding          binding          = new NetNamedPipeBinding(NetNamedPipeSecurityMode.Transport);
            ChannelFactory <IAdminGroup> namedPipeFactory = new ChannelFactory <IAdminGroup>(binding, Settings.NamedPipeServiceBaseAddress);
            IAdminGroup channel = namedPipeFactory.CreateChannel();
            bool        userIsAuthorizedLocally = false;

            try
            {
                userIsAuthorizedLocally = channel.UserIsAuthorized(Settings.LocalAllowedEntities, Settings.LocalDeniedEntities);
                namedPipeFactory.Close();
            }
            catch (EndpointNotFoundException exception)
            {
                System.Text.StringBuilder message = new System.Text.StringBuilder(exception.Message);
                if (null != exception.InnerException)
                {
                    message.Append(Environment.NewLine);
                    message.Append("Inner Exception:");
                    message.Append(Environment.NewLine);
                    message.Append(exception.InnerException.Message);
                }
                MessageBox.Show(this, exception.Message, Properties.Resources.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
            }
            catch (CommunicationObjectFaultedException)
            {
                // This typically happens when trying to dispose of the ChannelFactory<> object.
            }

            // Enable the "grant admin rights" button, if the user is not already
            // an administrator and is authorized to obtain those rights.
            this.addMeButton.Enabled = !this.userIsAdmin && userIsAuthorizedLocally;
            if (addMeButton.Enabled)
            {
                addMeButton.Text = Properties.Resources.GrantRightsButtonText;
            }
            else if (this.userIsAdmin)
            {
                addMeButton.Text = Properties.Resources.UIMessageAlreadyHaveRights;
            }
            else if (!userIsAuthorizedLocally)
            {
                addMeButton.Text = Properties.Resources.UIMessageUnauthorized;
            }

            // Enable the rights removal button if the user is directly a
            // member of the administrators group.
            this.removeMeButton.Enabled = this.userIsDirectAdmin;

            this.appStatus.Text = Properties.Resources.ApplicationIsReady;

            if (this.addMeButton.Enabled)
            {
                this.addMeButton.Focus();
            }
            else if (this.removeMeButton.Enabled)
            {
                this.removeMeButton.Focus();
            }
        }
Esempio n. 3
0
        /// <summary>
        /// This function runs when RunWorkerAsync() is called by the rights removal BackgroundWorker object.
        /// </summary>
        /// <param name="sender">
        /// The BackgroundWorker that triggered the event.
        /// </param>
        /// <param name="e">
        /// Data specific to this event.
        /// </param>
        private void removeUserBackgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            NetNamedPipeBinding          binding          = new NetNamedPipeBinding(NetNamedPipeSecurityMode.Transport);
            ChannelFactory <IAdminGroup> namedPipeFactory = new ChannelFactory <IAdminGroup>(binding, Settings.NamedPipeServiceBaseAddress);
            IAdminGroup channel = namedPipeFactory.CreateChannel();

            channel.RemoveUserFromAdministratorsGroup(RemovalReason.UserRequest);
            namedPipeFactory.Close();
        }
        /// <summary>
        /// Occurs when the background operation has completed, has been canceled, or has raised an exception.
        /// </summary>
        /// <param name="sender">
        /// The button state BackgroundWorker object, which triggered the event.
        /// </param>
        /// <param name="e">
        /// Data specific to this event.
        /// </param>
        private void ButtonStateWorkCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            NetNamedPipeBinding          binding          = new NetNamedPipeBinding(NetNamedPipeSecurityMode.Transport);
            ChannelFactory <IAdminGroup> namedPipeFactory = new ChannelFactory <IAdminGroup>(binding, Settings.NamedPipeServiceBaseAddress);
            IAdminGroup channel = namedPipeFactory.CreateChannel();
            bool        userIsAuthorizedLocally = channel.UserIsAuthorized(Settings.LocalAllowedEntities, Settings.LocalDeniedEntities);

            namedPipeFactory.Close();



            // Enable the "grant admin rights" button, if the user is not already
            // an administrator and is authorized to obtain those rights.
            if (!userIsAuthorizedLocally)
            {
                requestButton.Text = Properties.Resources.UIMessageUnauthorized;
            }
            else
            {
                if (!this.userIsAdmin)
                {
                    this.Icon               = Properties.Resources.Locked;
                    this.notifyIcon.Icon    = Properties.Resources.Locked;
                    this.requestButton.Text = "Request Privileges";
                    this.pictureBox1.Image  = Properties.Resources.Locked_Img;
                    messageLabel.Text       = Properties.Resources.GrantRightsButtonText;

                    settingsToolStripMenuItem.Enabled = true;
                }
                else if (this.userIsAdmin)
                {
                    this.Icon              = Properties.Resources.Unlocked;
                    this.notifyIcon.Icon   = Properties.Resources.Unlocked;
                    requestButton.Text     = "Remove Privileges";
                    this.pictureBox1.Image = Properties.Resources.Unlocked_Img;
                    messageLabel.Text      = Properties.Resources.UIMessageAlreadyHaveRights;

                    settingsToolStripMenuItem.Enabled = false;
                }

                /* If the edit menu is disable, disable everything within it */
                foreach (ToolStripMenuItem item in settingsToolStripMenuItem.DropDownItems)
                {
                    item.Enabled = settingsToolStripMenuItem.Enabled;
                }

                this.requestButton.Enabled = true;
                this.cancelButton.Enabled  = true;

                this.requestButton.Focus();
            }

            this.appStatus.Text = Properties.Resources.ApplicationIsReady;
        }
Esempio n. 5
0
        /// <summary>
        /// Occurs when the background operation has completed, has been canceled, or has raised an exception.
        /// </summary>
        /// <param name="sender">
        /// The button state BackgroundWorker object, which triggered the event.
        /// </param>
        /// <param name="e">
        /// Data specific to this event.
        /// </param>
        private void ButtonStateWorkCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            NetNamedPipeBinding          binding          = new NetNamedPipeBinding(NetNamedPipeSecurityMode.Transport);
            ChannelFactory <IAdminGroup> namedPipeFactory = new ChannelFactory <IAdminGroup>(binding, Settings.NamedPipeServiceBaseAddress);
            IAdminGroup channel = namedPipeFactory.CreateChannel();
            bool        userIsAuthorizedLocally = channel.UserIsAuthorized(Settings.LocalAllowedEntities, Settings.LocalDeniedEntities);

            namedPipeFactory.Close();

            /*
             * bool userIsAuthorizedLocally = UserIsAuthorized(WindowsIdentity.GetCurrent(), Settings.LocalAllowedEntities, Settings.LocalDeniedEntities);
             */

            // Enable the "grant admin rights" button, if the user is not already
            // an administrator and is authorized to obtain those rights.
            this.addMeButton.Enabled = !this.userIsAdmin && userIsAuthorizedLocally;
            if (addMeButton.Enabled)
            {
                addMeButton.Text = Properties.Resources.GrantRightsButtonText;
            }
            else if (this.userIsAdmin)
            {
                addMeButton.Text = Properties.Resources.UIMessageAlreadyHaveRights;
            }
            else if (!userIsAuthorizedLocally)
            {
                addMeButton.Text = Properties.Resources.UIMessageUnauthorized;
            }

            // Enable the rights removal button if the user is directly a
            // member of the administrators group.
            this.removeMeButton.Enabled = this.userIsDirectAdmin;

            this.appStatus.Text = Properties.Resources.ApplicationIsReady;

            if (this.addMeButton.Enabled)
            {
                this.addMeButton.Focus();
            }
            else if (this.removeMeButton.Enabled)
            {
                this.removeMeButton.Focus();
            }
        }
        void NotifyIconTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            this.UpdateUserAdministratorStatus();

            if (this.userIsAdmin != this.userWasAdminOnLastCheck)
            {
                NetNamedPipeBinding          namedPipeBinding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.Transport);
                ChannelFactory <IAdminGroup> namedPipeFactory = new ChannelFactory <IAdminGroup>(namedPipeBinding, Shared.NamedPipeServiceBaseAddress);
                IAdminGroup namedPipeChannel = namedPipeFactory.CreateChannel();

                this.userWasAdminOnLastCheck = this.userIsAdmin;
                if ((!this.userIsAdmin) && (!namedPipeChannel.PrincipalIsInList()))
                {
                    this.notifyIconTimer.Stop();
                    notifyIcon.ShowBalloonTip(5000, Properties.Resources.ApplicationName, string.Format(Properties.Resources.UIMessageRemovedFromGroup, LocalAdministratorGroup.LocalAdminGroupName), ToolTipIcon.Info);
                }
                namedPipeFactory.Close();
            }
        }
Esempio n. 7
0
        /// <summary>
        /// This function runs when RunWorkerAsync() is called by the "grant admin rights" BackgroundWorker object.
        /// </summary>
        /// <param name="sender">
        /// The BackgroundWorker that triggered the event.
        /// </param>
        /// <param name="e">
        /// Data specific to this event.
        /// </param>
        private void addUserBackgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            NetNamedPipeBinding          binding          = new NetNamedPipeBinding(NetNamedPipeSecurityMode.Transport);
            ChannelFactory <IAdminGroup> namedPipeFactory = new ChannelFactory <IAdminGroup>(binding, Settings.NamedPipeServiceBaseAddress);
            IAdminGroup channel = namedPipeFactory.CreateChannel();

            try
            {
                channel.AddUserToAdministratorsGroup();
            }
            catch (System.ServiceModel.EndpointNotFoundException)
            {
                throw;
            }
            catch (Exception)
            {
                throw;
                // TODO: What do we do with this error?
            }

            namedPipeFactory.Close();
        }
        private void RequestAdminRights(string hostName)
        {
            string remoteHostAddress = string.Format("net.tcp://{0}/MakeMeAdmin/Service", hostName);

            NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);
            ChannelFactory <IAdminGroup> namedPipeFactory = new ChannelFactory <IAdminGroup>(binding, remoteHostAddress);
            IAdminGroup channel = namedPipeFactory.CreateChannel();

            try
            {
                channel.AddPrincipalToAdministratorsGroup();
            }
            catch (System.ServiceModel.EndpointNotFoundException)
            {
                throw;
            }
            catch (Exception)
            {
                throw;
                // TODO: What do we do with this error?
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Executes when a change event is received from a Terminal Server session.
        /// </summary>
        /// <param name="changeDescription">
        /// Identifies the type of session change and the session to which it applies.
        /// </param>
        protected override void OnSessionChange(SessionChangeDescription changeDescription)
        {
            switch (changeDescription.Reason)
            {
            // The user has logged off from a session, either locally or remotely.
            case SessionChangeReason.SessionLogoff:

                EncryptedSettings encryptedSettings = new EncryptedSettings(EncryptedSettings.SettingsFilePath);
                System.Collections.Generic.List <SecurityIdentifier> sidsToRemove = new System.Collections.Generic.List <SecurityIdentifier>(encryptedSettings.AddedUserSIDs);

                int[] sessionIds = LsaLogonSessions.LogonSessions.GetLoggedOnUserSessionIds();

                // For any user that is still logged on, remove their SID from the list of
                // SIDs to be removed from Administrators. That is, let the users who are still
                // logged on stay in the Administrators group.
                foreach (int id in sessionIds)
                {
                    SecurityIdentifier sid = LsaLogonSessions.LogonSessions.GetSidForSessionId(id);
                    if (sid != null)
                    {
                        if (sidsToRemove.Contains(sid))
                        {
                            sidsToRemove.Remove(sid);
                        }
                    }
                }

                // Process the list of SIDs to be removed from Administrators.
                for (int i = 0; i < sidsToRemove.Count; i++)
                {
                    if (
                        // If the user is not remote.
                        (!(encryptedSettings.ContainsSID(sidsToRemove[i]) && encryptedSettings.IsRemote(sidsToRemove[i])))
                        &&
                        // If admin rights are to be removed on logoff, or the user's rights do not expire.
                        (Settings.RemoveAdminRightsOnLogout || !encryptedSettings.GetExpirationTime(sidsToRemove[i]).HasValue)
                        )
                    {
                        LocalAdministratorGroup.RemoveUser(sidsToRemove[i], RemovalReason.UserLogoff);
                    }
                }

                /*
                 * In theory, this code should remove the user associated with the logoff, but it doesn't work.
                 * SecurityIdentifier sid = LsaLogonSessions.LogonSessions.GetSidForSessionId(changeDescription.SessionId);
                 * if (!(UserList.ContainsSID(sid) && UserList.IsRemote(sid)))
                 * {
                 *  LocalAdministratorGroup.RemoveUser(sid, RemovalReason.UserLogoff);
                 * }
                 */

                break;

            // The user has logged on to a session, either locally or remotely.
            case SessionChangeReason.SessionLogon:

                WindowsIdentity userIdentity = LsaLogonSessions.LogonSessions.GetWindowsIdentityForSessionId(changeDescription.SessionId);

                if (userIdentity != null)
                {
                    NetNamedPipeBinding          binding          = new NetNamedPipeBinding(NetNamedPipeSecurityMode.Transport);
                    ChannelFactory <IAdminGroup> namedPipeFactory = new ChannelFactory <IAdminGroup>(binding, Settings.NamedPipeServiceBaseAddress);
                    IAdminGroup channel = namedPipeFactory.CreateChannel();
                    bool        userIsAuthorizedForAutoAdd = channel.UserIsAuthorized(Settings.AutomaticAddAllowed, Settings.AutomaticAddDenied);
                    namedPipeFactory.Close();

                    // If the user is in the automatic add list, then add them to the Administrators group.
                    if (
                        (Settings.AutomaticAddAllowed != null) &&
                        (Settings.AutomaticAddAllowed.Length > 0) &&
                        (userIsAuthorizedForAutoAdd /*UserIsAuthorized(userIdentity, Settings.AutomaticAddAllowed, Settings.AutomaticAddDenied)*/)
                        )
                    {
                        LocalAdministratorGroup.AddUser(userIdentity, null, null);
                    }
                }
                else
                {
                    ApplicationLog.WriteEvent(Properties.Resources.UserIdentifyIsNull, EventID.DebugMessage, System.Diagnostics.EventLogEntryType.Warning);
                }

                break;

                /*
                 * // The user has reconnected or logged on to a remote session.
                 * case SessionChangeReason.RemoteConnect:
                 *  ApplicationLog.WriteInformationEvent(string.Format("Remote connect. Session ID: {0}", changeDescription.SessionId), EventID.SessionChangeEvent);
                 *  break;
                 */

                /*
                 * // The user has disconnected or logged off from a remote session.
                 * case SessionChangeReason.RemoteDisconnect:
                 *  ApplicationLog.WriteInformationEvent(string.Format("Remote disconnect. Session ID: {0}", changeDescription.SessionId), EventID.SessionChangeEvent);
                 *  break;
                 */

                /*
                 * // The user has locked their session.
                 * case SessionChangeReason.SessionLock:
                 *  ApplicationLog.WriteInformationEvent(string.Format("Session lock. Session ID: {0}", changeDescription.SessionId), EventID.SessionChangeEvent);
                 *  break;
                 */

                /*
                 * // The user has unlocked their session.
                 * case SessionChangeReason.SessionUnlock:
                 *  ApplicationLog.WriteInformationEvent(string.Format("Session unlock. Session ID: {0}", changeDescription.SessionId), EventID.SessionChangeEvent);
                 *  break;
                 */
            }

            base.OnSessionChange(changeDescription);
        }
Esempio n. 10
0
        private void Dynamic_All(Microsoft.Diagnostics.Tracing.TraceEvent obj)
        {
            if ((obj.Opcode == Microsoft.Diagnostics.Tracing.TraceEventOpcode.Start) && (string.Compare(obj.TaskName, "ProcessStart", true) == 0))
            {
                int      processIsElevated    = 0;
                int      processElevationType = 0;
                int      processId            = int.MinValue;
                int      sessionId            = int.MinValue;
                DateTime createTime           = DateTime.MinValue;
                int      index = int.MinValue;

                index = obj.PayloadIndex("ProcessTokenIsElevated");
                if (index >= 0)
                {
                    processIsElevated = (int)obj.PayloadValue(index);
                }

                if (processIsElevated == 1)
                {
                    index = obj.PayloadIndex("ProcessID");
                    if (index >= 0)
                    {
                        processId = (int)obj.PayloadValue(index);
                    }

                    ElevatedProcessInformation elevatedProcess = new ElevatedProcessInformation
                    {
                        ProcessID = processId
                    };

                    index = obj.PayloadIndex("ProcessTokenElevationType");
                    if (index >= 0)
                    {
                        processElevationType          = (int)obj.PayloadValue(index);
                        elevatedProcess.ElevationType = (TokenElevationType)processElevationType;
                    }

                    index = obj.PayloadIndex("SessionID");
                    if (index >= 0)
                    {
                        sessionId = (int)obj.PayloadValue(index);
                        elevatedProcess.SessionID = sessionId;
                    }

                    index = obj.PayloadIndex("CreateTime");
                    if (index >= 0)
                    {
                        createTime = (DateTime)obj.PayloadValue(index);
                        elevatedProcess.CreateTime = createTime;
                    }

                    // Determine whether the process should be logged. It should be logged if
                    // 1. The process logging setting is set to always, or
                    // 2. The process logging is set to "Only When Admin" and the user is in the admins group.
                    bool processShouldBeLogged = (Settings.LogElevatedProcesses == ElevatedProcessLogging.Always);
                    if (Settings.LogElevatedProcesses == ElevatedProcessLogging.OnlyWhenAdmin)
                    {
                        NetNamedPipeBinding          binding          = new NetNamedPipeBinding(NetNamedPipeSecurityMode.Transport);
                        ChannelFactory <IAdminGroup> namedPipeFactory = new ChannelFactory <IAdminGroup>(binding, Settings.NamedPipeServiceBaseAddress);
                        IAdminGroup channel = namedPipeFactory.CreateChannel();
                        processShouldBeLogged = channel.UserSessionIsInList(elevatedProcess.SessionID);
                        namedPipeFactory.Close();
                    }

                    if (processShouldBeLogged)
                    {
                        elevatedProcessList.Enqueue(elevatedProcess);
                    }
                }
            }
        }