Пример #1
0
        public void EncryptFile_DisableRightsAfterEncrypting()
        {
            ThreadRunner.Run((() =>
            {
                using (var cleaner = new TestFileCleaner())
                    using (var token = Security.OpenProcessToken(AccessTokenRights.Duplicate | AccessTokenRights.Query))
                    {
                        // Create and encrypt the file
                        string path = cleaner.CreateTestFile(nameof(EncryptFile_DisableRightsAfterEncrypting));
                        Storage.EncryptFile(path);
                        FileHelper.ReadAllText(path).Should().Be(nameof(EncryptFile_DisableRightsAfterEncrypting));

                        // Add Users group to the DACL
                        using (var handle = Storage.CreateFile(path, CreationDisposition.OpenExisting,
                                                               DesiredAccess.GenericReadWrite | DesiredAccess.WriteDac))
                        {
                            handle.IsInvalid.Should().BeFalse();
                            SID usersGroup = Security.CreateWellKnownSid(WellKnownSID.Users);
                            handle.ChangeAccess(usersGroup, FileAccessRights.GenericRead, AccessMode.Grant);
                        }

                        // Disable the primary user token (prevents using for granting access)
                        using (var restricted = Security.CreateRestrictedToken(token, Security.GetTokenUserSid(token)))
                        {
                            Security.ImpersonateLoggedOnUser(restricted);

                            // The primary user token being disabled doesn't impact the implicit decryption
                            // (We're getting rights to the file through the Users group)
                            FileHelper.ReadAllText(path).Should().Be(nameof(EncryptFile_DisableRightsAfterEncrypting));
                            Security.RevertToSelf();
                        }
                    }
            }));
        }
Пример #2
0
        public void SetAndGet_Current_Threading()
        {
            User user = User.FindByUserName("substituting.user");

            var principal = CreateSecurityManagerPrincipal(user.Tenant, user, null);

            SecurityManagerPrincipal.Current = principal;
            Assert.That(SecurityManagerPrincipal.Current, Is.SameAs(principal));

            ThreadRunner.Run(
                delegate
            {
                using (ClientTransaction.CreateRootTransaction().EnterDiscardingScope())
                {
                    User otherUser     = User.FindByUserName("group1/user1");
                    var otherPrincipal = CreateSecurityManagerPrincipal(otherUser.Tenant, otherUser, null);

                    Assert.That(SecurityManagerPrincipal.Current.IsNull, Is.True);
                    SecurityManagerPrincipal.Current = otherPrincipal;
                    Assert.That(SecurityManagerPrincipal.Current, Is.SameAs(otherPrincipal));
                }
            });

            Assert.That(SecurityManagerPrincipal.Current, Is.SameAs(principal));
        }
Пример #3
0
        public void Impersonate_DisableUserAddGroup_FileAccess()
        {
            ThreadRunner.Run((() =>
            {
                using (var cleaner = new TestFileCleaner())
                    using (var token = Security.OpenProcessToken(AccessTokenRights.Duplicate | AccessTokenRights.Query))
                    {
                        string path = cleaner.CreateTestFile(nameof(Impersonate_DisableUser_FileAccess));
                        FileHelper.ReadAllText(path).Should().Be(nameof(Impersonate_DisableUser_FileAccess));

                        // Add Users group
                        using (var handle = Storage.CreateFile(path, CreationDisposition.OpenExisting,
                                                               DesiredAccess.GenericReadWrite | DesiredAccess.WriteDac))
                        {
                            handle.IsInvalid.Should().BeFalse();
                            SID usersGroup = Security.CreateWellKnownSid(WellKnownSID.Users);
                            handle.ChangeAccess(usersGroup, FileAccessRights.GenericRead, AccessMode.Grant);
                        }

                        // Disable the primary user token (prevents using for granting access)
                        using (var restricted = Security.CreateRestrictedToken(token, Security.GetTokenUserSid(token)))
                        {
                            Security.ImpersonateLoggedOnUser(restricted);

                            // We'll get access through the Users group
                            FileHelper.ReadAllText(path).Should().Be(nameof(Impersonate_DisableUser_FileAccess));

                            Security.RevertToSelf();
                            FileHelper.ReadAllText(path).Should().Be(nameof(Impersonate_DisableUser_FileAccess));
                        }
                    }
            }));
        }
Пример #4
0
        public void Impersonate_Anonymous_GetThreadToken(bool openAsSelf)
        {
            using (var token = Security.OpenProcessToken(AccessTokenRights.Read))
            {
                var privileges = token.GetTokenPrivileges();
            }

            ThreadRunner.Run((() =>
            {
                Security.ImpersonateAnonymousToken();
                SID sid;
                using (var threadToken = Security.OpenThreadToken(AccessTokenRights.Query, openAsSelf))
                {
                    threadToken.Should().NotBeNull();
                    threadToken.IsInvalid.Should().BeFalse();
                    sid = threadToken.GetTokenOwnerSid();
                    Action action = () => sid.LookupAccountSid();
                    action.Should().Throw <UnauthorizedAccessException>();

                    var privileges = threadToken.GetTokenPrivileges();
                }
                Security.RevertToSelf();

                var info = sid.LookupAccountSid();
                info.Name.Should().Be("ANONYMOUS LOGON");
                info.Usage.Should().Be(SidNameUse.WellKnownGroup);
                sid.Equals(Security.CreateWellKnownSid(WellKnownSID.Anonymous)).Should().BeTrue();
            }));
        }
Пример #5
0
        public void ChangeThreadToImpersonate()
        {
            ThreadRunner.Run((() =>
            {
                using (var token = Security.OpenThreadToken(AccessTokenRights.Query, openAsSelf: true))
                {
                    token.Should().BeNull();
                }

                using (var token = Security.OpenProcessToken(AccessTokenRights.Duplicate | AccessTokenRights.Query))
                {
                    using (var duplicate = Security.DuplicateToken(token, AccessTokenRights.Query | AccessTokenRights.Impersonate, ImpersonationLevel.Impersonation))
                    {
                        using (ThreadHandle thread = Threads.GetCurrentThread())
                        {
                            Security.SetThreadToken(thread, duplicate);

                            // We didn't actually change from what the process token is
                            using (var threadToken = Security.OpenThreadToken(AccessTokenRights.Query, openAsSelf: false))
                            {
                                threadToken.Should().BeNull();
                            }
                        }
                    }
                }
            }));
        }
Пример #6
0
        public void EncryptFile_DisableRightsBeforeEncrypting()
        {
            ThreadRunner.Run((() =>
            {
                using (var cleaner = new TestFileCleaner())
                    using (var token = Security.OpenProcessToken(AccessTokenRights.Duplicate | AccessTokenRights.Query | AccessTokenRights.Impersonate))
                    {
                        // Create and encrypt the file
                        string path = cleaner.CreateTestFile(nameof(EncryptFile_DisableRightsBeforeEncrypting));

                        Action action;

                        // Disable the primary user token (prevents using for granting access)
                        using (var restricted = Security.CreateRestrictedToken(token, Security.GetTokenUserSid(token)))
                        {
                            Security.ImpersonateLoggedOnUser(restricted);
                            action = () => Storage.EncryptFile(path);
                            action.Should().Throw <UnauthorizedAccessException>();
                            Security.RevertToSelf();
                        }

                        action = () => Storage.QueryUsersOnEncryptedFile(path);
                        action.Should().Throw <WInteropIOException>()
                        .And.HResult.Should().Be((int)WindowsError.ERROR_FILE_NOT_ENCRYPTED.ToHResult());
                    }
            }));
        }
Пример #7
0
        private static void RunControlRunner(MainForm form, string[] args)
        {
            Console.WriteLine("Thread {0}", Thread.CurrentThread.Name);
            Console.WriteLine("InvokeRequired {0}", form.InvokeRequired);
            var uir = new ControlRunner(form, (ex) =>
            {
                Console.WriteLine(ex.Message);
                throw new Exception("Should be ignored");
            });
            var ior = new ThreadRunner("Runner");

            ior.Run(() =>
            {
                Console.WriteLine("InvokeRequired {0}", form.InvokeRequired);
                Console.WriteLine("Thread {0}", Thread.CurrentThread.Name);
                uir.Run(() => { throw new Exception("Should be catched"); });
                uir.Run(() =>
                {
                    Console.WriteLine("InvokeRequired {0}", form.InvokeRequired);
                    Console.WriteLine("Thread {0}", Thread.CurrentThread.Name);
                    Console.WriteLine("form.Text {0}", form.Text);
                    form.Close();
                });
            });
        }
Пример #8
0
        public void EncryptFile_AccessAsAnonymousAfterEncrypting()
        {
            ThreadRunner.Run((() =>
            {
                using (var cleaner = new TestFileCleaner())
                    using (var token = Security.OpenProcessToken(AccessTokenRights.Duplicate | AccessTokenRights.Query))
                    {
                        // Create and encrypt the file
                        string path = cleaner.CreateTestFile(nameof(EncryptFile_AccessAsAnonymousAfterEncrypting));
                        Storage.EncryptFile(path);
                        FileHelper.ReadAllText(path).Should().Be(nameof(EncryptFile_AccessAsAnonymousAfterEncrypting));

                        // Give anonymous rights
                        using (var handle = Storage.CreateFile(path, CreationDisposition.OpenExisting,
                                                               DesiredAccess.GenericReadWrite | DesiredAccess.WriteDac))
                        {
                            handle.IsInvalid.Should().BeFalse();
                            SID anonymous = Security.CreateWellKnownSid(WellKnownSID.Anonymous);
                            handle.ChangeAccess(anonymous, FileAccessRights.GenericRead, AccessMode.Grant);
                        }

                        // Should still have only one encrypted user
                        var sids = Storage.QueryUsersOnEncryptedFile(path);
                        sids.Count().Should().Be(1);

                        // Try accessing as anonymous
                        Security.ImpersonateAnonymousToken();
                        Action action = () => FileHelper.ReadAllText(path);
                        action.Should().Throw <UnauthorizedAccessException>();
                        Security.RevertToSelf();
                    }
            }));
        }
Пример #9
0
        public void AddUser_AnonymousRead_CanRead()
        {
            using (var cleaner = new TestFileCleaner())
            {
                string path = cleaner.CreateTestFile(nameof(AddUser_AnonymousRead_CanRead));

                using (var handle = Storage.CreateFile(path, CreationDisposition.OpenExisting,
                                                       DesiredAccess.GenericReadWrite | DesiredAccess.WriteDac))
                {
                    handle.IsInvalid.Should().BeFalse();
                    SID anonymous = Security.CreateWellKnownSid(WellKnownSID.Anonymous);
                    handle.ChangeAccess(anonymous, FileAccessRights.GenericRead, AccessMode.Grant);
                }

                ThreadRunner.Run(() =>
                {
                    Security.ImpersonateAnonymousToken();
                    Action action = () => FileHelper.ReadAllText(path);
                    // The problem here is that Anonymous does not have bypass traverse checking.
                    // All folders, including the root, would need to have DirectoryAccessRights.Traverse.
                    action.Should().Throw <UnauthorizedAccessException>();
                    Security.RevertToSelf();
                });
            }
        }
Пример #10
0
 public void Impersonate_Anonymous()
 {
     ThreadRunner.Run((() =>
     {
         Security.ImpersonateAnonymousToken();
         Security.RevertToSelf();
     }));
 }
Пример #11
0
 public void CurrentObjectInitializationContext_ThreadStatic()
 {
     using (new ObjectInititalizationContextScope(_initializationContext))
     {
         ThreadRunner.Run(() => Assert.That(ObjectInititalizationContextScope.CurrentObjectInitializationContext, Is.Null));
     }
     Assert.That(ObjectInititalizationContextScope.CurrentObjectInitializationContext, Is.Null);
 }
Пример #12
0
        public void Run()
        {
            bool threadRun = false;

            ThreadRunner.Run(delegate { threadRun = true; });

            Assert.That(threadRun, Is.True);
        }
Пример #13
0
        public void ActiveConfigurationIsThreadSpecific()
        {
            var newConfiguration = new MixinConfiguration();

            MixinConfiguration.SetActiveConfiguration(newConfiguration);

            ThreadRunner.Run(() => Assert.That(MixinConfiguration.ActiveConfiguration, Is.Not.SameAs(newConfiguration)));
        }
Пример #14
0
        public void Start()
        {
            if (!statisticsRecorder.Enabled || thread != null)
            {
                return;
            }

            thread = ThreadRunner.Run(ThreadRoutine, log);
        }
Пример #15
0
        private void RunGesture(IGesture gesture)
        {
            ThreadRunner runner = new ThreadRunner(new ThreadStart(gesture.Start));

            runner.Run();
            if (runner.CatchedException != null)
            {
                Assert.Fail(runner.CatchedException.ToString());
            }
        }
Пример #16
0
    public static void Main(string[] args)
    {
        int   n     = 20;
        Token token = new Token();

        token.data      = "data";
        token.recipient = n;
        ThreadRunner runner = new ThreadRunner();

        runner.Run(token, n);
    }
        public void ScriptingHost_Current_ThreadStatic()
        {
            ScriptingHost scriptingHostDifferentThread = null;
            var           threadRunner = new ThreadRunner(delegate { scriptingHostDifferentThread = ScriptingHost.Current; });

            threadRunner.Run();
            ScriptingHost scriptingHost = ScriptingHost.Current;

            Assert.That(scriptingHost, Is.Not.Null);
            Assert.That(scriptingHostDifferentThread, Is.Not.Null);
            Assert.That(scriptingHost, Is.Not.SameAs(scriptingHostDifferentThread));
        }
Пример #18
0
        private void AddControl(string name, SerializableMap settings = null)
        {
            if (settings == null)
            {
                settings = new SerializableMap();
            }
            var control = CreateControl(name, settings);
            var wrapper = new WrapperControl(control, () => {
                ior.Run(() => {
                    controls.Remove((IoControl)control);
                });
            });

            wrapper.ItemName = settings.GetString("$Name", "NO NAME");
            panelContainer.Controls.Add(wrapper);
            ior.Run(() => {
                var ioc = (IoControl)control;
                ioc.SetMaster(master);
                controls.Add(ioc);
            });
        }
 public void HasSessionAndGetCurrentInSeparateThreads()
 {
     HttpContextHelper.SetCurrent(HttpContextHelper.CreateHttpContext("get", "default.aspx", string.Empty));
     Assert.That(WxeFunctionStateManager.HasSession, Is.False);
     Assert.That(WxeFunctionStateManager.Current, Is.Not.Null);
     ThreadRunner.Run(
         delegate
     {
         HttpContextHelper.SetCurrent(HttpContextHelper.CreateHttpContext("get", "default.aspx", string.Empty));
         Assert.That(WxeFunctionStateManager.HasSession, Is.False);
         Assert.That(WxeFunctionStateManager.Current, Is.Not.Null);
         Assert.That(WxeFunctionStateManager.HasSession, Is.True);
     });
 }
Пример #20
0
 public void Impersonate_DisableUser()
 {
     ThreadRunner.Run((() =>
     {
         using (var token = Security.OpenProcessToken(AccessTokenRights.Duplicate | AccessTokenRights.Query))
         {
             using (var restricted = Security.CreateRestrictedToken(token, Security.GetTokenUserSid(token)))
             {
                 Security.ImpersonateLoggedOnUser(restricted);
                 Security.RevertToSelf();
             }
         }
     }));
 }
Пример #21
0
        public void Execute_ScriptContext_ThreadStatic()
        {
            var scriptContext = CreateScriptContext();

            Assert.That(ScriptContext.Current, Is.Null);
            var scriptContextInExecute = scriptContext.Execute(
                delegate
            {
                Assert.That(ScriptContext.Current, Is.SameAs(scriptContext));
                ThreadRunner.Run(() => Assert.That(ScriptContext.Current, Is.Null));
                Assert.That(ScriptContext.Current, Is.SameAs(scriptContext));
                return(ScriptContext.Current);
            });

            Assert.That(scriptContextInExecute, Is.SameAs(scriptContext));
        }
Пример #22
0
        public void MasterConfigurationIsCopiedByNewThreads()
        {
            var oldMasterConfiguration = MixinConfiguration.GetMasterConfiguration();

            try
            {
                var newMasterConfiguration = new MixinConfiguration();
                MixinConfiguration.SetMasterConfiguration(newMasterConfiguration);

                ThreadRunner.Run(() => Assert.That(MixinConfiguration.ActiveConfiguration, Is.SameAs(newMasterConfiguration)));
            }
            finally
            {
                MixinConfiguration.SetMasterConfiguration(oldMasterConfiguration);
            }
        }
Пример #23
0
        private void SendText(string text)
        {
            var list = new List <byte>();

            list.AddRange(ascii.GetBytes(text));
            AppendLineEnding(list);
            var bytes = list.ToArray();

            buffer.Output(bytes, true);
            ior.Run(() => iom.Write(bytes));
        }
Пример #24
0
        public void EncryptFile_AsAnonymous()
        {
            ThreadRunner.Run(() =>
            {
                using (var cleaner = new TestFileCleaner())
                {
                    string path = cleaner.CreateTestFile(nameof(EncryptFile_AsAnonymous));
                    FileHelper.ReadAllText(path).Should().Be(nameof(EncryptFile_AsAnonymous));
                    Storage.EncryptFile(path);

                    FileHelper.ReadAllText(path).Should().Be(nameof(EncryptFile_AsAnonymous));
                    Security.ImpersonateAnonymousToken();
                    Action action = () => FileHelper.ReadAllText(path);
                    action.Should().Throw <UnauthorizedAccessException>();
                    Security.RevertToSelf();
                }
            });
        }
Пример #25
0
        public static bool CouldAcquireLockFromOtherThread(object lockObject)
        {
            ArgumentUtility.CheckNotNull("lockObject", lockObject);

            var lockAcquired = false;

            ThreadRunner.Run(
                () =>
            {
                lockAcquired = Monitor.TryEnter(lockObject);
                if (lockAcquired)
                {
                    Monitor.Exit(lockObject);
                }
            });

            return(lockAcquired);
        }
Пример #26
0
        public void Threading()
        {
            Assert.That(SecurityFreeSection.IsActive, Is.False);
            var scope = SecurityFreeSection.Activate();

            Assert.That(SecurityFreeSection.IsActive, Is.True);

            ThreadRunner.Run(
                delegate
            {
                Assert.That(SecurityFreeSection.IsActive, Is.False);
                using (SecurityFreeSection.Activate())
                {
                    Assert.That(SecurityFreeSection.IsActive, Is.True);
                }
                Assert.That(SecurityFreeSection.IsActive, Is.False);
            });

            scope.Dispose();
            Assert.That(SecurityFreeSection.IsActive, Is.False);
        }
Пример #27
0
        protected override State RequestAction(ActionRequest request)
        {
            if (!IsActionAllowed(request))
            {
                return(_currentState);
            }

            _latestRequest = request;
            if (_latestRequest == ActionRequest.Start)
            {
                _currentState = State.Running;
                if (_indexJob == null)
                {
                    if (_runThreadPool)
                    {
                        ThreadRunner.Run(DoRun);
                    }
                    else
                    {
                        DoRun();
                    }
                }
                else
                {
                    _fileSource.Start();
                }
            }
            else if (_latestRequest == ActionRequest.Stop)
            {
                _currentState = State.Stopped;
                _fileSource.Stop();
            }
            else
            {
                _currentState = State.Paused;
                _fileSource.Pause();
            }
            return(_currentState);
        }
Пример #28
0
        public void Impersonate_DisableUser_FileAccess()
        {
            ThreadRunner.Run(() =>
            {
                using (var cleaner = new TestFileCleaner())
                    using (var token = Security.OpenProcessToken(AccessTokenRights.Duplicate | AccessTokenRights.Query))
                    {
                        string path = cleaner.CreateTestFile(nameof(Impersonate_DisableUser_FileAccess));
                        FileHelper.ReadAllText(path).Should().Be(nameof(Impersonate_DisableUser_FileAccess));

                        // Disable the primary user token (prevents using for granting access)
                        using (var restricted = Security.CreateRestrictedToken(token, Security.GetTokenUserSid(token)))
                        {
                            Security.ImpersonateLoggedOnUser(restricted);
                            Action action = () => FileHelper.ReadAllText(path);
                            action.Should().Throw <UnauthorizedAccessException>();
                            Security.RevertToSelf();
                            FileHelper.ReadAllText(path).Should().Be(nameof(Impersonate_DisableUser_FileAccess));
                        }
                    }
            });
        }
        public void ThreadAbortExceptionInNestedFunctionWithThreadMigration()
        {
            var nestedFunction = new ThreadAbortTestTransactedFunction();
            var originalScope  = ClientTransaction.CreateRootTransaction().EnterDiscardingScope();
            var parentFunction =
                new CreateRootWithChildTestTransactedFunction(ClientTransactionScope.CurrentTransaction, nestedFunction);

            try
            {
                parentFunction.Execute(Context);
                Assert.Fail("Expected ThreadAbortException");
            }
            catch (ThreadAbortException)
            {
                Thread.ResetAbort();
            }

            Assert.That(ClientTransactionScope.ActiveScope, Is.SameAs(originalScope));

            ThreadRunner.Run(
                delegate
            {
                Assert.That(ClientTransactionScope.ActiveScope, Is.Null, "ActiveScope is not null before execute.");
                Assert.That(nestedFunction.FirstStepExecuted, Is.True);
                Assert.That(nestedFunction.SecondStepExecuted, Is.False);
                Assert.That(nestedFunction.ThreadAborted, Is.True);

                parentFunction.Execute(Context);

                Assert.That(nestedFunction.FirstStepExecuted, Is.True);
                Assert.That(nestedFunction.SecondStepExecuted, Is.True);
                Assert.That(ClientTransactionScope.ActiveScope, Is.Null, "ActiveScope is not null after execute.");
                //TODO: Before there was a transaction, now there isn't
                //Assert.That ( ClientTransactionScope.CurrentTransaction, Is.SameAs (originalScope.ScopedTransaction)); // but same transaction as on old thread
            });

            originalScope.Leave();
        }
Пример #30
0
        public void Run_WithException()
        {
            var exception = new InvalidOperationException("xy");

            ThreadRunner.Run(() => { throw exception; });
        }