Exemple #1
0
        /// <summary>
        /// Handle the privilege states.
        /// </summary>
        private void UpdatePrivilege()
        {
            switch (_state)
            {
            /// Privilege API has been started successfully, ready to make requests.
            case PrivilegeState.Started:
            {
                RequestPrivileges();
                break;
            }

            /// Privilege requests have been made, wait until all privileges are granted before enabling the feature that requires privileges.
            case PrivilegeState.Requested:
            {
                foreach (MLPrivilegeId priv in _privilegesToRequest)
                {
                    if (!_privilegesGranted.Contains(priv))
                    {
                        return;
                    }
                }
                _state = PrivilegeState.Succeeded;
                OnPrivilegesDone(MLResult.ResultOk);
                break;
            }

            /// Privileges have been denied, respond appropriately.
            case PrivilegeState.Failed:
            {
                OnPrivilegesDone(new MLResult(MLResultCode.PrivilegeDenied));
                enabled = false;
                break;
            }
            }
        }
Exemple #2
0
        private void ChangePrivileges_button_Click(object sender, EventArgs e)
        {
            int     PID  = Int32.Parse(Table.CurrentCell.Value.ToString());
            Process proc = Process.GetProcessById(PID);

            string p = Privilege_comboBox.Text.ToString();
            string s = State_comboBox.Text;

            Privilege privilege = (Privilege)Enum.Parse(typeof(Privilege), p);

            PrivilegeState state = (PrivilegeState)Enum.Parse(typeof(PrivilegeState), s);

            if (state == PrivilegeState.Disabled)
            {
                proc.DisablePrivilege(privilege);
            }
            else if (state == PrivilegeState.Enabled)
            {
                proc.EnablePrivilege(privilege);
            }
            else if (state == PrivilegeState.Removed)
            {
                proc.RemovePrivilege(privilege);
            }
        }
Exemple #3
0
        private static void AdjustPrivileges(bool enableTcb, bool enableImpersonate)
        {
            Process process = Process.GetCurrentProcess();

            if (enableTcb)
            {
                process.EnablePrivilege(Privilege.TrustedComputerBase);
            }
            else
            {
                process.DisablePrivilege(Privilege.TrustedComputerBase);
            }

            if (enableImpersonate)
            {
                process.EnablePrivilege(Privilege.Impersonate);
            }
            else
            {
                process.DisablePrivilege(Privilege.Impersonate);
            }

            Console.WriteLine("Current Privileges:");
            foreach (PrivilegeAndAttributes privilegeAndAttributes in process.GetPrivileges())
            {
                Privilege      privilege      = privilegeAndAttributes.Privilege;
                PrivilegeState privilegeState = privilegeAndAttributes.PrivilegeState;
                Console.WriteLine($"  {privilege, -20} => {privilegeState}");
            }
        }
Exemple #4
0
        protected override void OnStart(string[] args)
        {
            // okay, the 'args' here are ONLY for when the service is started via the Properties dialog in services.msc
            try
            {
                using (TokenHandle my_token = TokenUtil.OpenProcessToken(Process.GetCurrentProcess(), TokenAccess.TOKEN_ADJUST_PRIVILEGES | TokenAccess.TOKEN_DUPLICATE))
                {
                    PrivilegeState[] privs = new PrivilegeState[] {
                        new PrivilegeState(TokenPrivileges.SE_TCB_NAME, true)
                    };
                    if (!my_token.AdjustPrivileges(privs))
                    {
                        throw new Win32Exception();
                    }

                    // open the token of the process that lives in the session we want
                    Process     proc       = Process.GetProcessById(this.Pid);
                    TokenHandle proc_token = TokenUtil.OpenProcessToken(proc.Handle, TokenAccess.TOKEN_READ);

                    // create a primary token
                    TokenHandle new_token = TokenUtil.DuplicateTokenEx(my_token, TokenAccess.TOKEN_ALL_ACCESS, SECURITY_IMPERSONATION_LEVEL.SecurityDelegation, TOKEN_TYPE.TokenPrimary);
                    // override the session under which it's going to be created
                    new_token.SessionId = proc_token.SessionId;

                    string cmd_exe = Environment.GetEnvironmentVariable("COMSPEC");

                    STARTUPINFO sui = new STARTUPINFO();
                    sui.cb = Marshal.SizeOf(typeof(STARTUPINFO));

                    PROCESS_INFORMATION procinfo;

                    bool result = Advapi32.CreateProcessAsUser(
                        new_token,
                        cmd_exe,
                        cmd_exe,
                        IntPtr.Zero,     // default process attributes
                        IntPtr.Zero,     // default thread attributes
                        false,
                        CreateProcessFlags.CREATE_NEW_CONSOLE | CreateProcessFlags.CREATE_NEW_PROCESS_GROUP | CreateProcessFlags.CREATE_DEFAULT_ERROR_MODE | CreateProcessFlags.CREATE_BREAKAWAY_FROM_JOB | CreateProcessFlags.CREATE_PRESERVE_CODE_AUTHZ_LEVEL | CreateProcessFlags.CREATE_UNICODE_ENVIRONMENT,
                        IntPtr.Zero, // inherit environment
                        null,        // inherit current directory
                        ref sui,
                        out procinfo);
                    if (!result)
                    {
                        throw new Win32Exception();
                    }
                }
            }
            catch
            {
                this.ExitCode = 1;
            }
            finally
            {
                EventWaitHandle ewh = EventWaitHandle.OpenExisting(EventName);
                ewh.Set();
            }
            ThreadPool.QueueUserWorkItem(DoStop);
        }
        public Integrity(int pid)
        {
            InitializeComponent();
            procid         = pid;
            textBox2.Text  = procid.ToString();
            label3.Visible = false;
            comboBox1.Items.Add("LOW");
            comboBox1.Items.Add("MEDIUM");
            comboBox1.Items.Add("HIGH");
            comboBox1.Items.Add("SYSTEM");

            comboBox3.Items.Add("ENABLE");
            comboBox3.Items.Add("DISABLE");

            System.Diagnostics.Process       process    = System.Diagnostics.Process.GetProcessById(pid);
            PrivilegeAndAttributesCollection privileges = process.GetPrivileges();

            if (privileges.Count == 0)
            {
                comboBox2.Items.Add("NO PRIVS");
            }
            else
            {
                int maxPrivilegeLebgth = privileges.Max(privilege => privilege.Privilege.ToString().Length);
                foreach (PrivilegeAndAttributes PrivNAtrr in privileges)
                {
                    Privilege      privilege      = PrivNAtrr.Privilege;
                    PrivilegeState privilegeState = PrivNAtrr.PrivilegeState;
                    string         StrComboBox2   = privilege.ToString();
                    comboBox2.Items.Add(StrComboBox2);
                }
            }
        }
        private void button3_Click_2(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(textBox2.Text);

            //System.Diagnostics.Process proc = System.Diagnostics.Process.GetProcessById(id);

            //string argument = Convert.ToString(id);
            //var info = new System.Diagnostics.ProcessStartInfo(@"C:\Users\abuly_000\Documents\Visual Studio 2015\Projects\mbks2lab\x64\Debug\GetProcessPrivileges.exe", argument);
            //System.Diagnostics.Process.Start(info);

            //string text = System.IO.File.ReadAllText("C:\\Users\\abuly_000\\Documents\\Visual Studio 2015\\Projects\\mbks2lab\\Privileges.txt");
            //MessageBox.Show(text);
            System.Diagnostics.Process       process    = Process.GetProcessById(id);
            PrivilegeAndAttributesCollection privileges = process.GetPrivileges();

            if (privileges.Count == 0)
            {
                MessageBox.Show("NO PRIVILEGES");
            }
            else
            {
                int    maxPrivilegeLength = privileges.Max(privilege => privilege.Privilege.ToString().Length);
                string Out = null;
                foreach (PrivilegeAndAttributes privilegeAndAttributes in privileges)
                {
                    Privilege      privilege      = privilegeAndAttributes.Privilege;
                    PrivilegeState privilegeState = privilegeAndAttributes.PrivilegeState;
                    string         PaddingString  = GetPadding(privilege.ToString().Length, maxPrivilegeLength);
                    Out += privilege + " " + PaddingString + " => " + privilegeState + "\n";
                }
                MessageBox.Show(Out);
            }
        }
Exemple #7
0
 /// <summary>
 /// Start the Privileges API and set the Privilege State
 /// </summary>
 void Start()
 {
     #if PLATFORM_LUMIN
     _privilegesToRequest.AddRange(Array.ConvertAll(_privileges, tempPrivilege => (MLPrivileges.Id)tempPrivilege));
     _state = PrivilegeState.Started;
     #endif
 }
        /// <summary>
        /// Handle the privilege states.
        /// </summary>
        private void UpdatePrivilege()
        {
            switch (_currentPrivilegeState)
            {
            /// Privilege API has been started successfully, ready to make requests.
            case PrivilegeState.Started:
            {
                RequestPrivileges();
                break;
            }

            /// Privilege requests have been made, wait until all privileges are granted before enabling the feature that requires privileges.
            case PrivilegeState.Requested:
            {
                foreach (MLPrivilegeId priv in _privilegesNeeded)
                {
                    if (!_privilegesGranted.Contains(priv))
                    {
                        return;
                    }
                }
                _currentPrivilegeState = PrivilegeState.Granted;
                break;
            }

            /// Privileges have been denied, respond appropriately.
            case PrivilegeState.Denied:
            {
                enabled = false;
                break;
            }
            }
        }
Exemple #9
0
 /// <summary>
 /// Cannot make the assumption that a reality privilege is still granted after
 /// returning from pause. Return the application to the state where it
 /// requests privileges needed and clear out the list of already granted
 /// privileges. Also, disable the camera and unregister callbacks.
 /// </summary>
 /// <remarks>
 /// Not necessary, but harmless, for sensitive privileges.
 /// </remarks>
 void OnApplicationPause(bool pause)
 {
     if (pause && _state != PrivilegeState.Off)
     {
         _privilegesGranted.Clear();
         _state = PrivilegeState.Started;
     }
 }
Exemple #10
0
 internal PrivilegeSetting(string privilege, PrivilegeState state)
 {
     Privileges p;
     if (!Enum.TryParse(privilege, out p))
     {
         p = Privileges.UnknownPrivilege;
     }
     Privilege = p;
     State = state;
 }
Exemple #11
0
        internal PrivilegeSetting(string privilege, PrivilegeState state)
        {
            Privileges p;

            if (!Enum.TryParse(privilege, out p))
            {
                p = Privileges.UnknownPrivilege;
            }
            this.Privilege = p;
            this.State     = state;
        }
        void OnDestroy()
        {
            if (_state != PrivilegeState.Off && _state != PrivilegeState.StartFailed)
            {
                MLPrivileges.Stop();

                _state = PrivilegeState.Off;
                _privilegesGranted.Clear();
                _privilegesToRequest.Clear();
            }
        }
Exemple #13
0
 /// <summary>
 /// Handles the result that is received from the query to the Privilege API.
 /// If one of the required privileges are denied, set the Privilege state to Denied.
 /// <param name="result">The resulting status of the query</param>
 /// <param name="privilegeId">The privilege being queried</param>
 /// </summary>
 private void HandlePrivilegeAsyncRequest(MLResult result, MLPrivilegeId privilegeId)
 {
     if (result.Code == MLResultCode.PrivilegeGranted)
     {
         _privilegesGranted.Add(privilegeId);
         Debug.LogFormat("{0} Privilege Granted", privilegeId);
     }
     else
     {
         Debug.LogErrorFormat("{0} Privilege Error: {1}, disabling example.", privilegeId, result);
         _state = PrivilegeState.Failed;
     }
 }
Exemple #14
0
            private void Handle(IAcSession acSession, IPrivilegeUpdateIo input, bool isCommand)
            {
                var       acDomain            = _set._acDomain;
                var       privilegeList       = _set._privilegeList;
                var       privilegeRepository = acDomain.RetrieveRequiredService <IRepository <Privilege, Guid> >();
                Privilege entity       = null;
                var       stateChanged = false;

                lock (Locker)
                {
                    entity = privilegeRepository.GetByKey(input.Id);
                    if (entity == null)
                    {
                        throw new NotExistException("不存在的权限记录标识" + input.Id);
                    }
                    var  bkState = acDomain.PrivilegeSet.FirstOrDefault(a => a.Id == input.Id);
                    bool isAccountSubjectType = string.Equals(UserAcSubjectType.Account.ToName(), entity.SubjectType);

                    entity.Update(input);

                    var newState = PrivilegeState.Create(entity);
                    stateChanged = newState != bkState;
                    if (!isAccountSubjectType && stateChanged)
                    {
                        privilegeList.Remove(bkState);
                        privilegeList.Add(newState);
                    }
                    if (isCommand)
                    {
                        try
                        {
                            privilegeRepository.Update(entity);
                            privilegeRepository.Context.Commit();
                        }
                        catch
                        {
                            if (!isAccountSubjectType && stateChanged)
                            {
                                privilegeList.Remove(newState);
                                privilegeList.Add(bkState);
                            }
                            privilegeRepository.Context.Rollback();
                            throw;
                        }
                    }
                }
                if (isCommand && stateChanged)
                {
                    acDomain.MessageDispatcher.DispatchMessage(new PrivilegeUpdatedEvent(acSession, entity, input, isPrivate: true));
                }
            }
Exemple #15
0
        /// <summary>
        /// Cannot make the assumption that a reality privilege is still granted after
        /// returning from pause. Return the application to the state where it
        /// requests privileges needed and clear out the list of already granted
        /// privileges. Also, disable the camera and unregister callbacks.
        /// </summary>
        /// <remarks>
        /// Not necessary, but harmless, for sensitive privileges.
        /// </remarks>
        void OnApplicationPause(bool pause)
        {
#if !UNITY_EDITOR
            if (FindObjectOfType <VisSpatialMappingTracking>() != null)
            {
                Destroy(FindObjectOfType <VisSpatialMappingTracking>().transform.root.gameObject);
            }
#endif
            if (pause && _state != PrivilegeState.Off)
            {
                _privilegesGranted.Clear();
                _state = PrivilegeState.Started;
            }
        }
        /// <summary>
        /// Start Privilege API.
        /// </summary>
        void OnEnable()
        {
            MLResult result = MLPrivileges.Start();

            if (result.IsOk)
            {
                _currentPrivilegeState = PrivilegeState.Started;
            }
            else
            {
                Debug.LogError("Privilege Error: failed to startup");
                enabled = false;
                return;
            }
        }
 /// <summary>
 /// Handles the result that is received from the query to the Privilege API.
 /// If one of the required privileges are denied, set the Privilege state to Denied.
 /// <param name="result">The resulting status of the query</param>
 /// <param name="privilegeId">The privilege being queried</param>
 /// </summary>
 private void HandlePrivilegeAsyncRequest(MLResult result, MLPrivileges.Id privilegeId)
 {
     #if PLATFORM_LUMIN
     if (result.Result == MLResult.Code.PrivilegeGranted)
     {
         _privilegesGranted.Add(privilegeId);
         Debug.LogFormat("{0} Privilege Granted", privilegeId);
     }
     else
     {
         Debug.LogErrorFormat("{0} Privilege Error: {1}.", privilegeId, result);
         _state = PrivilegeState.Failed;
     }
     #endif
 }
        /// <summary>
        /// Request each needed privilege.
        /// </summary>
        private void RequestPrivileges()
        {
            foreach (MLPrivilegeId priv in _privilegesNeeded)
            {
                MLResult result = MLPrivileges.RequestPrivilegeAsync(priv, HandlePrivilegeAsyncRequest);
                if (!result.IsOk)
                {
                    Debug.LogErrorFormat("{0} Privilege Request Error: {1}", priv, result);
                    _currentPrivilegeState = PrivilegeState.Denied;
                    return;
                }
            }

            _currentPrivilegeState = PrivilegeState.Requested;
        }
Exemple #19
0
        /// <summary>
        /// Request each needed privilege.
        /// </summary>
        private void RequestPrivileges()
        {
            foreach (MLPrivilegeId priv in _privilegesToRequest)
            {
                MLResult result = MLPrivileges.RequestPrivilegeAsync(priv, HandlePrivilegeAsyncRequest);
                if (!result.IsOk)
                {
                    Debug.LogErrorFormat("Error: PrivilegeRequester failed requesting {0} privilege. Reason: {1}", priv, result);
                    _state = PrivilegeState.Failed;
                    return;
                }
            }

            _state = PrivilegeState.Requested;
        }
        void Start()
        {
            MLResult result = MLPrivileges.Start();

            if (result.IsOk)
            {
                _privilegesToRequest.AddRange(Array.ConvertAll(_privileges, tempPrivilege => (MLPrivilegeId)tempPrivilege));
                _state = PrivilegeState.Started;
            }
            else
            {
                Debug.LogError("Privilege Error: failed to startup");
                _state = PrivilegeState.StartFailed;
                OnPrivilegesDone(result);
                enabled = false;
            }
        }
Exemple #21
0
        /// <summary>
        /// Start the Privileges API and set the Privilege State
        /// </summary>
        void Start()
        {
            MLResult result = MLPrivileges.Start();

            if (result.IsOk)
            {
                _privilegesToRequest.AddRange(Array.ConvertAll(_privileges, tempPrivilege => (MLPrivilegeId)tempPrivilege));
                _state = PrivilegeState.Started;
            }
            else
            {
                Debug.LogErrorFormat("Error: PrivilegeRequester failed starting MLPrivileges, disabling script. Reason: {0}", result);
                _state = PrivilegeState.StartFailed;
                OnPrivilegesDone(result);
                enabled = false;
            }
        }
Exemple #22
0
        /// <summary>
        /// Cannot make the assumption that a privilege is still granted after
        /// returning from pause. Return the application to the state where it
        /// requests privileges needed and clear out the list of already granted
        /// privileges. Also, unregister callbacks.
        /// </summary>
        private void OnApplicationPause(bool pause)
        {
            if (pause)
            {
                if (_currentPrivilegeState != PrivilegeState.Off)
                {
                    _privilegesGranted.Clear();
                    _currentPrivilegeState = PrivilegeState.Started;
                }

                MLInput.OnControllerButtonDown -= HandleOnButtonDown;

                updateImageTrackerBehaviours(false);

                _hasStarted = false;
            }
        }
        /// <summary>
        /// Cannot make the assumption that a privilege is still granted after
        /// returning from pause. Return the application to the state where it
        /// requests privileges needed and clear out the list of already granted
        /// privileges. Also, disable the camera and unregister callbacks.
        /// </summary>
        private void OnApplicationPause(bool pause)
        {
            if (pause)
            {
                if (_currentPrivilegeState != PrivilegeState.Off)
                {
                    _privilegesGranted.Clear();
                    _currentPrivilegeState = PrivilegeState.Started;
                }

                if (_isCameraConnected)
                {
                    DisableMLCamera();
                }

                MLInput.OnControllerButtonDown -= OnButtonDown;

                _hasStarted = false;
            }
        }
Exemple #24
0
        private static string GetPrivil(Process process)
        {
            string allPriv = "";
            //Process p;
            //p = Process.GetProcessById(Int32.Parse(process.Id));
            PrivilegeAndAttributesCollection privileges = process.GetPrivileges();

            int maxPrivilegeLength = privileges.Max(privilege => privilege.Privilege.ToString().Length);

            foreach (PrivilegeAndAttributes privilegeAndAttributes in privileges)
            {
                Privilege      privilege      = privilegeAndAttributes.Privilege;
                PrivilegeState privilegeState = privilegeAndAttributes.PrivilegeState;

                if (privilegeState.ToString() == "Enabled")
                {
                    allPriv += privilege + "; ";
                }
            }
            return(allPriv);
        }
        /// <summary>
        /// Stop the camera, unregister callbacks, and stop input and privileges APIs.
        /// </summary>
        void OnDisable()
        {
            if (MLInput.IsStarted)
            {
                MLInput.OnControllerButtonDown -= OnButtonDown;
                MLInput.Stop();
            }

            if (_isCameraConnected)
            {
                DisableMLCamera();
            }

            if (_currentPrivilegeState != PrivilegeState.Off)
            {
                MLPrivileges.Stop();

                _currentPrivilegeState = PrivilegeState.Off;
                _privilegesGranted.Clear();
            }
        }
Exemple #26
0
        private void Table_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int PID = 0;

            try
            {
                #region Получение DLL и вывод в TextBox
                PID = Int32.Parse(Table.CurrentCell.Value.ToString());
                DLLBox.Clear();
                Process proc = Process.GetProcessById(PID);

                DLLBox.Text += "Процесс: " + proc.ProcessName + Environment.NewLine;
                foreach (ProcessModule module in proc.Modules)
                {
                    DLLBox.Text += module.FileName + Environment.NewLine;
                }
                #endregion

                #region Получение привелегий процесса
                Priveleges_dataGridView.Rows.Clear();

                PrivilegeAndAttributesCollection privileges = proc.GetPrivileges();

                //int maxPrivilegeLength = privileges.Max(privilege => privilege.Privilege.ToString().Length);

                foreach (PrivilegeAndAttributes privilegeAndAttributes in privileges)
                {
                    Privilege privilege = privilegeAndAttributes.Privilege;

                    PrivilegeState privilegeState = privilegeAndAttributes.PrivilegeState;

                    Priveleges_dataGridView.Rows.Add(privilege /*+ GetPadding(privilege.ToString().Length, maxPrivilegeLength)*/, privilegeState);
                }
                #endregion
            }
            catch (Win32Exception) { }
            catch (ArgumentException) { }
            catch (FormatException) { }
            catch (InvalidOperationException) { }
        }
Exemple #27
0
        /// <summary>
        /// Cannot make the assumption that a reality privilege is still granted after
        /// returning from pause. Return the application to the state where it
        /// requests privileges needed and clear out the list of already granted
        /// privileges. Also, disable the camera and unregister callbacks.
        /// </summary>
        private void OnApplicationPause(bool pause)
        {
            if (pause)
            {
                if (_currentPrivilegeState != PrivilegeState.Off)
                {
                    _privilegesGranted.Clear();
                    _currentPrivilegeState = PrivilegeState.Started;
                }

                if (_isCameraConnected)
                {
                    MLCamera.OnRawImageAvailable -= OnCaptureRawImageComplete;
                    _isCapturing = false;
                    DisableMLCamera();
                }

                MLInput.OnControllerButtonDown -= OnButtonDown;

                _hasStarted = false;
            }
        }
Exemple #28
0
        /// <summary>
        /// Stop the camera, unregister callbacks, and stop input and privileges APIs.
        /// </summary>
        void OnDisable()
        {
            if (MLInput.IsStarted)
            {
                MLInput.OnControllerButtonDown -= OnButtonDown;
                MLInput.Stop();
            }

            if (_isCameraConnected)
            {
                MLCamera.OnRawImageAvailable -= OnCaptureRawImageComplete;
                _isCapturing = false;
                DisableMLCamera();
            }

            if (_currentPrivilegeState != PrivilegeState.Off)
            {
                MLPrivileges.Stop();

                _currentPrivilegeState = PrivilegeState.Off;
                _privilegesGranted.Clear();
            }
        }
Exemple #29
0
 private void Init()
 {
     if (_initialized)
     {
         return;
     }
     lock (Locker)
     {
         if (_initialized)
         {
             return;
         }
         _acDomain.MessageDispatcher.DispatchMessage(new MemorySetInitingEvent(this));
         _privilegeList.Clear();
         var rolePrivileges = _acDomain.RetrieveRequiredService <IOriginalHostStateReader>().GetPrivileges();
         foreach (var rolePrivilege in rolePrivileges)
         {
             var rolePrivilegeState = PrivilegeState.Create(rolePrivilege);
             _privilegeList.Add(rolePrivilegeState);
         }
         _initialized = true;
         _acDomain.MessageDispatcher.DispatchMessage(new MemorySetInitializedEvent(this));
     }
 }
Exemple #30
0
            private void Handle(IAcSession acSession, IPrivilegeCreateIo input, bool isCommand)
            {
                var acDomain                  = _set._acDomain;
                var privilegeList             = _set._privilegeList;
                var privilegeBigramRepository = acDomain.RetrieveRequiredService <IRepository <Privilege, Guid> >();
                var accountRepository         = acDomain.RetrieveRequiredService <IRepository <Account, Guid> >();

                if (!input.Id.HasValue || input.Id.Value == Guid.Empty)
                {
                    throw new GeneralException("意外的标识");
                }
                AcElementType subjectType;

                if (!input.SubjectType.TryParse(out subjectType))
                {
                    throw new ValidationException("非法的主体类型" + input.SubjectType);
                }
                AcElementType acObjectType;

                if (!input.ObjectType.TryParse(out acObjectType))
                {
                    throw new ValidationException("非法的客体类型" + input.ObjectType);
                }
                Privilege entity;

                lock (Locker)
                {
                    switch (subjectType)
                    {
                    case AcElementType.Undefined:
                        throw new GeneralException("意外的主体类型" + subjectType.ToString());

                    case AcElementType.Account:
                        if (!accountRepository.AsQueryable().Any(a => a.Id == input.SubjectInstanceId))
                        {
                            throw new ValidationException("给定标识的账户不存在" + input.SubjectInstanceId);;
                        }
                        break;

                    case AcElementType.Role:
                        RoleState role;
                        if (!acDomain.RoleSet.TryGetRole(input.SubjectInstanceId, out role))
                        {
                            throw new ValidationException("意外的角色标识" + input.SubjectInstanceId);
                        }
                        break;

                    case AcElementType.Catalog:
                        CatalogState org;
                        if (!acDomain.CatalogSet.TryGetCatalog(input.SubjectInstanceId, out org))
                        {
                            throw new ValidationException("意外的目录标识" + input.SubjectInstanceId);
                        }
                        break;

                    case AcElementType.Privilege:
                        throw new NotSupportedException();

                    default:
                        throw new GeneralException("意外的主体类型" + subjectType.ToString());
                    }
                    switch (acObjectType)
                    {
                    case AcElementType.Undefined:
                        throw new ValidationException("意外的账户权限类型" + input.SubjectType);

                    case AcElementType.Catalog:
                        CatalogState catalog;
                        if (!acDomain.CatalogSet.TryGetCatalog(input.ObjectInstanceId, out catalog))
                        {
                            throw new ValidationException("意外的目录标识" + input.ObjectInstanceId);
                        }
                        break;

                    case AcElementType.Role:
                        RoleState role;
                        if (!acDomain.RoleSet.TryGetRole(input.ObjectInstanceId, out role))
                        {
                            throw new ValidationException("意外的角色标识" + input.ObjectInstanceId);
                        }
                        break;

                    case AcElementType.Group:
                        GroupState group;
                        if (!acDomain.GroupSet.TryGetGroup(input.ObjectInstanceId, out group))
                        {
                            throw new ValidationException("意外的工作组标识" + input.ObjectInstanceId);
                        }
                        break;

                    case AcElementType.Function:
                        FunctionState function;
                        if (!acDomain.FunctionSet.TryGetFunction(input.ObjectInstanceId, out function))
                        {
                            throw new ValidationException("意外的功能标识" + input.ObjectInstanceId);
                        }
                        break;

                    case AcElementType.Menu:
                        MenuState menu;
                        if (!acDomain.MenuSet.TryGetMenu(input.ObjectInstanceId, out menu))
                        {
                            throw new ValidationException("意外的菜单标识" + input.ObjectInstanceId);
                        }
                        break;

                    case AcElementType.AppSystem:
                        if (!acDomain.AppSystemSet.ContainsAppSystem(input.ObjectInstanceId))
                        {
                            throw new ValidationException("意外的应用系统标识" + input.ObjectInstanceId);
                        }
                        break;

                    case AcElementType.Privilege:
                        throw new ValidationException("暂不支持" + input.SubjectType + "类型的授权");

                    default:
                        throw new ValidationException("意外的账户权限类型" + input.SubjectType);
                    }
                    if (subjectType == AcElementType.Role && acObjectType == AcElementType.Role)
                    {
                        if (input.SubjectInstanceId == input.ObjectInstanceId)
                        {
                            throw new ValidationException("角色不能继承自己");
                        }
                        var descendantIds = new HashSet <Guid>();
                        RecDescendantRoles(input.SubjectInstanceId, descendantIds);
                        if (descendantIds.Contains(input.SubjectInstanceId))
                        {
                            throw new ValidationException("角色不能继承自己的子孙");
                        }
                    }
                    if (subjectType == AcElementType.Account && acObjectType == AcElementType.Account)
                    {
                        if (input.SubjectInstanceId == input.ObjectInstanceId)
                        {
                            throw new ValidationException("账户不能继承自己");
                        }
                        var descendantIds = new HashSet <Guid>();
                        RecDescendantAccounts(input.SubjectInstanceId, descendantIds);
                        if (descendantIds.Contains(input.SubjectInstanceId))
                        {
                            throw new ValidationException("账户不能继承自己的子孙");
                        }
                    }
                    if (subjectType == AcElementType.Account && acObjectType == AcElementType.Role)
                    {
                        var       sType          = UserAcSubjectType.Account.ToName();
                        var       oType          = AcElementType.Role.ToName();
                        var       rolePrivileges = privilegeBigramRepository.AsQueryable().Where(a => a.SubjectType == sType && a.SubjectInstanceId == input.SubjectInstanceId && a.ObjectType == oType);
                        var       roles          = new HashSet <RoleState>();
                        RoleState role;
                        if (acDomain.RoleSet.TryGetRole(input.ObjectInstanceId, out role))
                        {
                            roles.Add(role);
                        }
                        foreach (var item in rolePrivileges)
                        {
                            if (acDomain.RoleSet.TryGetRole(item.ObjectInstanceId, out role))
                            {
                                roles.Add(role);
                            }
                        }
                        // TODO:考虑上角色继承

                        /*
                         * 其实就是在当前账户的角色集中元素的数目有增加时执行责任分离验证。
                         * 这个地方没考虑清楚。可能只考虑(Account, Role)是对的,没有办法去考虑上Catalog上的角色、Group上的角色,甚至别的Account委托过来的角色。
                         * 那些角色是在进入这些场景、边界之后才会并入到当前账户的角色集的,离开那个边界时就会收回。也就是说可能需要在当前活动的账户进入某个Catalog、Group、和变身为某人时执行一下职责分离约束规则。
                         */
                        string msg;
                        if (!acDomain.SsdSetSet.CheckRoles(roles, out msg))
                        {
                            throw new ValidationException(msg);
                        }
                    }
                    if (subjectType == AcElementType.Catalog && acObjectType == AcElementType.Catalog)
                    {
                        if (input.SubjectInstanceId == input.ObjectInstanceId)
                        {
                            throw new ValidationException("组织机构不能继承自己");
                        }
                        var descendantIds = new HashSet <Guid>();
                        RecDescendantCatalogs(input.SubjectInstanceId, descendantIds);
                        if (descendantIds.Contains(input.SubjectInstanceId))
                        {
                            throw new ValidationException("组织机构不能继承自己的子孙");
                        }
                    }
                    if (acDomain.PrivilegeSet.Any(a => a.ObjectType == acObjectType && a.ObjectInstanceId == input.ObjectInstanceId && a.SubjectType == subjectType && a.SubjectInstanceId == input.SubjectInstanceId))
                    {
                        return;
                    }

                    entity = Privilege.Create(input);

                    if (subjectType != AcElementType.Account && privilegeList.All(a => a.Id != entity.Id))
                    {
                        privilegeList.Add(PrivilegeState.Create(entity));
                    }
                    if (isCommand)
                    {
                        try
                        {
                            privilegeBigramRepository.Add(entity);
                            privilegeBigramRepository.Context.Commit();
                        }
                        catch
                        {
                            if (subjectType != AcElementType.Account && privilegeList.Any(a => a.Id == entity.Id))
                            {
                                var item = privilegeList.First(a => a.Id == entity.Id);
                                privilegeList.Remove(item);
                            }
                            privilegeBigramRepository.Context.Rollback();
                            throw;
                        }
                    }
                }
                if (isCommand)
                {
                    acDomain.MessageDispatcher.DispatchMessage(new PrivilegeAddedEvent(acSession, entity, input, isPrivate: true));
                }
                if (subjectType == AcElementType.Role && acObjectType == AcElementType.Role)
                {
                    acDomain.MessageDispatcher.DispatchMessage(new RoleRolePrivilegeAddedEvent(acSession, entity));
                }
            }
Exemple #31
0
        public void RoleSubjectTypePrivilege()
        {
            var acDomain = TestHelper.GetAcDomain();
            var roleId   = Guid.NewGuid();

            AcSessionState.AcMethod.SignIn(acDomain, new Dictionary <string, object>
            {
                { "loginName", "test" },
                { "password", "111111" },
                { "rememberMe", "rememberMe" }
            });
            RoleState roleById;

            acDomain.Handle(new RoleCreateInput
            {
                Id           = roleId,
                Name         = "测试1",
                CategoryCode = "test",
                Description  = "test",
                IsEnabled    = 1,
                SortCode     = 10,
                Icon         = null
            }.ToCommand(acDomain.GetAcSession()));
            Assert.AreEqual(1, acDomain.RoleSet.Count());
            Assert.IsTrue(acDomain.RoleSet.TryGetRole(roleId, out roleById));

            var functionId = Guid.NewGuid();

            FunctionState functionById;

            acDomain.Handle(new FunctionCreateInput
            {
                Id             = functionId,
                Code           = "fun1",
                Description    = string.Empty,
                DeveloperId    = acDomain.SysUserSet.GetDevAccounts().First().Id,
                IsEnabled      = 1,
                IsManaged      = true,
                ResourceTypeId = TestHelper.TestCatalogNodeId,
                SortCode       = 10
            }.ToCommand(acDomain.GetAcSession()));
            CatalogState resource;

            Assert.IsTrue(acDomain.CatalogSet.TryGetCatalog(TestHelper.TestCatalogNodeId, out resource));
            Assert.AreEqual(1, acDomain.FunctionSet.Count());
            Assert.IsTrue(acDomain.FunctionSet.TryGetFunction(functionId, out functionById));
            var entityId = Guid.NewGuid();

            acDomain.Handle(new AddPrivilegeCommand(acDomain.GetAcSession(), new PrivilegeCreateIo
            {
                Id = entityId,
                SubjectInstanceId = roleId,
                SubjectType       = UserAcSubjectType.Role.ToString(),// 主体是角色
                AcContent         = null,
                AcContentType     = null,
                ObjectInstanceId  = functionId,
                ObjectType        = AcElementType.Function.ToString()
            }));
            PrivilegeState privilegeBigram = acDomain.PrivilegeSet.First(a => a.Id == entityId);

            Assert.IsNotNull(privilegeBigram);
            Assert.IsNotNull(acDomain.RetrieveRequiredService <IRepository <Privilege> >().AsQueryable().FirstOrDefault(a => a.Id == entityId));
            Assert.AreEqual(roleId, privilegeBigram.SubjectInstanceId);
            Assert.AreEqual(functionId, privilegeBigram.ObjectInstanceId);

            acDomain.Handle(new UpdatePrivilegeCommand(acDomain.GetAcSession(), new PrivilegeUpdateIo
            {
                Id        = entityId,
                AcContent = "this is a test"
            }));
            Assert.AreEqual("this is a test", acDomain.PrivilegeSet.Single(a => a.Id == entityId).AcContent);

            acDomain.Handle(new RemovePrivilegeCommand(acDomain.GetAcSession(), entityId));
            Assert.IsNull(acDomain.PrivilegeSet.FirstOrDefault(a => a.Id == entityId));
        }