コード例 #1
0
        public void ReflectionFormatterReadSecurityExceptionPropertiesWithoutPermissionTest()
        {
            SecurityPermission denyPermission
                = new SecurityPermission(SecurityPermissionFlag.ControlPolicy | SecurityPermissionFlag.ControlEvidence);
            PermissionSet permissions = new PermissionSet(PermissionState.None);

            permissions.AddPermission(denyPermission);
            permissions.Deny();
            StringBuilder     sb        = new StringBuilder();
            StringWriter      writer    = new StringWriter(sb);
            SecurityException exception = null;

            try
            {
                DemandException(denyPermission);
            }
            catch (SecurityException e)
            {
                exception = e;
            }
            MockTextExceptionFormatter formatter = new MockTextExceptionFormatter(writer, exception, Guid.Empty);

            formatter.Format();
            CodeAccessPermission.RevertDeny();
            formatter = new MockTextExceptionFormatter(writer, exception, Guid.Empty);
            formatter.Format();
            Assert.AreEqual(exception.Demanded.ToString(), formatter.properties["Demanded"]);
        }
コード例 #2
0
        public void CanReflectOnSecurityExceptionWithoutPermission()
        {
            SecurityPermission denyPermission
                = new SecurityPermission(SecurityPermissionFlag.ControlPolicy | SecurityPermissionFlag.ControlEvidence);
            PermissionSet permissions = new PermissionSet(PermissionState.None);

            permissions.AddPermission(denyPermission);
            permissions.Deny();

            SecurityException exception = null;

            try
            {
                DemandException(denyPermission);
            }
            catch (SecurityException e)
            {
                exception = e;
            }

            ExceptionFormatter formatter = new ExceptionFormatter();

            String message       = formatter.GetMessage(exception);
            Match  demandedMatch = DemandedEntryRegex.Match(message);

            Assert.IsNotNull(demandedMatch);
            Assert.AreEqual(Resources.PropertyAccessFailed, demandedMatch.Groups[1].Value);

            CodeAccessPermission.RevertDeny();

            message       = formatter.GetMessage(exception);
            demandedMatch = DemandedEntryRegex.Match(message);
            Assert.IsNotNull(demandedMatch);
            Assert.AreNotEqual(Resources.PropertyAccessFailed, demandedMatch.Groups[1].Value);
        }
コード例 #3
0
        public override object Execute(Object o, IList args)
        {
            IStackWalk permission = null;

            try
            {
                permission = CreateStackWalk();
                if (this.PermitOnly)
                {
                    permission.PermitOnly();
                }
                else
                {
                    permission.Deny();
                }
                return(this.Invoker.Execute(o, args));
            }
            finally
            {
                if (permission != null)
                {
                    if (this.PermitOnly)
                    {
                        CodeAccessPermission.RevertPermitOnly();
                    }
                    else
                    {
                        CodeAccessPermission.RevertDeny();
                    }
                }
            }
        }
コード例 #4
0
        private static void DenyOpen()
        {
            try
            {
                //<Snippet20>
                // Create a KeyContainerPermission with the right
                // to open the key container.
                KeyContainerPermission keyContainerPerm = new
                                                          KeyContainerPermission(KeyContainerPermissionFlags.Open);
                //</Snippet20>

                // Demonstrate the results of a deny for an open action.
                keyContainerPerm.Deny();

                // The next line causes an exception to be thrown when the
                // infrastructure code attempts to open the key container.
                CspKeyContainerInfo info = new CspKeyContainerInfo(cspParams);
            }
            catch (Exception e)
            {
                Console.WriteLine("Expected exception thrown: " + e.Message);
            }

            // Revert the deny.
            CodeAccessPermission.RevertDeny();
        }
コード例 #5
0
    public static void Main(string[] args)
    {
        //<Snippet2>
        Console.WriteLine("Creating a permission with Flags = OpenStore.");
        StorePermission sp = new StorePermission(StorePermissionFlags.OpenStore);
        //</Snippet2>
        //Create a new X509 store named teststore from the local certificate store.
        //You must put in a valid path to a certificate in the following constructor.
        X509Certificate2 certificate = new X509Certificate2("c:\\certificates\\*****.cer");

        //      Deny the permission to open a store.
        sp.Deny();
        // The following code results in an exception due to an attempt to open a store.
        AddToStore(certificate);
        // Remove the deny for opening a store.
        CodeAccessPermission.RevertDeny();
        // The following code results in an exception due to an attempt to add a certificate.
        // The exception is thrown due to a StorePermissionAttribute on the method denying AddToStore permission.
        AddToStore(certificate);
        // The current code is not affected by the attribute in the previously called method, so the following
        // intructions execute without an exception.
        X509Store store = new X509Store("teststore", StoreLocation.CurrentUser);

        store.Open(OpenFlags.ReadWrite);
        store.Add(certificate);

        // Demonstrate the behavior of the class members.
        ShowMembers();

        Console.WriteLine("Press the Enter key to exit.");
        Console.ReadKey();
        return;
    }
コード例 #6
0
        public object Invoke(object[] parameters)
        {
            if (FAssembly == null || FAssembly.Instance == null)
            {
                return(null);
            }
            if (FMethodInfo == null)
            {
                FMethodInfo = FAssembly.Instance.GetType().GetMethod(MethodName, BindingFlags.Instance | BindingFlags.NonPublic);
            }
            if (FMethodInfo == null)
            {
                return(null);
            }

            PermissionSet restrictions = FAssembly.Report.ScriptRestrictions;

            if (restrictions != null)
            {
                restrictions.Deny();
            }
            try
            {
                return(FMethodInfo.Invoke(FAssembly.Instance, parameters));
            }
            finally
            {
                if (restrictions != null)
                {
                    CodeAccessPermission.RevertDeny();
                }
            }
        }
コード例 #7
0
        static void Main(string[] args)
        {
            CodeAccessPermission permission = new FileIOPermission(FileIOPermissionAccess.Append, @"c:\audit.txt");

            permission.Deny();
            AuditClass.Save("some data to audit");
            CodeAccessPermission.RevertDeny();
        }
コード例 #8
0
        static void Main(string[] args)
        {
            CodeAccessPermission permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, @"c:\");

            permission.Deny();
            UntrustworthyClass.Method();
            CodeAccessPermission.RevertDeny();
        }
コード例 #9
0
        private void _9()
        {
            CodeAccessPermission perm = new FileIOPermission(FileIOPermissionAccess.Append, @"e:\Progr\C#\ProgramujemeProfesionalne\20-Security\audit.txt");

            //Deny permissions
            perm.Deny();
            AuditMethod("Testovaci zapis\n");

            //Revert ALL deny permissions
            CodeAccessPermission.RevertDeny();
        }
コード例 #10
0
        private void _8()
        {
            CodeAccessPermission cap = new FileIOPermission(FileIOPermissionAccess.AllAccess, @"C:\");

            //Deny permission
            cap.Deny();
            //Call untrusted method
            UntrustedMethod();
            //Revert ALL permition
            CodeAccessPermission.RevertDeny();
        }
コード例 #11
0
        static void Main()
        {
            CodeAccessPermission permission =
                new FileIOPermission(FileIOPermissionAccess.Append,
                                     @"C:\audit.txt");

            permission.Deny();
            AuditClass.Save("some data to audit");
            CodeAccessPermission.RevertDeny();

            Console.ReadLine();
        }
        public void CanGetExistingSectionInAppConfigEvenIfTheAppDomainDoesNotHaveFileIOPermission()
        {
            try
            {
                new FileIOPermission(PermissionState.Unrestricted).Deny();

                CanGetExistingSectionInAppConfig();
            }
            finally
            {
                CodeAccessPermission.RevertDeny();
            }
        }
コード例 #13
0
        public void FileIOPermission()
        {
            FileIOPermission f = new FileIOPermission(PermissionState.Unrestricted);

            f.Deny();
            try
            {
                IStateName2 proxy = (IStateName2)XmlRpcProxyGen.Create(typeof(IStateName2));
            }
            finally
            {
                CodeAccessPermission.RevertDeny();
            }
        }
コード例 #14
0
ファイル: form1.cs プロジェクト: zhamppx97/dotnet-api-docs
        void RunCode()
        {
            try
            {
                // Deny a permission.
                KeyContainerPermission kCP1 = new KeyContainerPermission(
                    KeyContainerPermissionFlags.Decrypt);
                kCP1.Deny();

                // Demand the denied permission and display the
                // exception properties.
                Display("Demanding a denied permission. \n\n");
                DemandDeniedPermission();
                Display("************************************************\n");
                CodeAccessPermission.RevertDeny();

                // Demand the permission refused in the
                // assembly-level attribute.
                Display("Demanding a refused permission. \n\n");
                DemandRefusedPermission();
                Display("************************************************\n");

                // Demand the permission implicitly refused through a
                // PermitOnly attribute. Permit only the permission that
                // will cause the failure and the security permissions
                // necessary to display the results of the failure.
                PermissionSet permitOnly = new PermissionSet(
                    PermissionState.None);
                permitOnly.AddPermission(new KeyContainerPermission(
                                             KeyContainerPermissionFlags.Import));
                permitOnly.AddPermission(new SecurityPermission(
                                             SecurityPermissionFlag.ControlEvidence |
                                             SecurityPermissionFlag.ControlPolicy |
                                             SecurityPermissionFlag.SerializationFormatter));
                permitOnly.PermitOnly();
                Display("Demanding an implicitly refused permission. \n\n");
                DemandPermitOnly();
            }
            catch (Exception sE)
            {
                Display("************************************************\n");
                //<Snippet17>
                Display("Displaying an exception using the ToString method: ");
                Display(sE.ToString());
                //</Snippet17>
            }
        }
コード例 #15
0
        public void foo()
        {
            string[] drives = Environment.GetLogicalDrives();

            IStackWalk stackWalker;

            stackWalker = new FileIOPermission(FileIOPermissionAccess.Write, drives);

            stackWalker.Deny();

            // QuestableComponent is a class in an not trusted assembly
            //QuestableComponent obj = new QuestableComponent();
            //obj.DoSomething();

            CodeAccessPermission.RevertDeny();

            // Do more work
        }
コード例 #16
0
        /// <summary>
        /// Try/finally is completely unnecessary. Permissions are associated with stack frames
        /// and go out of scope once stack frame returns.
        /// </summary>
        private string GetMachineNameWithoutPermissions()
        {
            EnvironmentPermission denyPermission = new EnvironmentPermission(PermissionState.None);

            PermissionSet permissions = new PermissionSet(PermissionState.None);

            permissions.AddPermission(denyPermission);
            permissions.Deny();

            try
            {
                return(Environment.MachineName);
            }
            finally
            {
                CodeAccessPermission.RevertDeny();
            }
        }
コード例 #17
0
        public void NoPermissionToReadFileWhenCreated()
        {
            FileIOPermission denyPermission =
                new FileIOPermission(FileIOPermissionAccess.Read, Path.GetFullPath("TestFile"));

            PermissionSet permissions = new PermissionSet(PermissionState.None);

            permissions.AddPermission(denyPermission);
            permissions.Deny();

            try
            {
                new FileDependency("TestFile");
            }
            finally
            {
                CodeAccessPermission.RevertDeny();
            }
        }
コード例 #18
0
        public void NoPermissionToReadWhenCheckingExpiration()
        {
            FileDependency dependency = new FileDependency("TestFile");

            FileIOPermission denyPermission =
                new FileIOPermission(FileIOPermissionAccess.Read, Path.GetFullPath("TestFile"));

            PermissionSet permissions = new PermissionSet(PermissionState.None);

            permissions.AddPermission(denyPermission);
            permissions.Deny();

            try
            {
                dependency.HasExpired();
            }
            finally
            {
                CodeAccessPermission.RevertDeny();
            }
        }
コード例 #19
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                FileIOPermission ff = new FileIOPermission(FileIOPermissionAccess.Write, "c:/temp/xyz.txt");
                //ff.Assert();

                ff.Deny();
                StreamWriter objW = new StreamWriter(File.Open("c:/temp/xyz.txt", FileMode.Open));
                CodeAccessPermission.RevertDeny();
                objW = null;

                objW.WriteLine("testing");
                objW.Flush();
                objW.Close();
                objW = null;
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }
コード例 #20
0
ファイル: CASPermissionsTests.cs プロジェクト: yuzukwok/NetMX
        private bool DoDenied(ThreadStart delSetup, ThreadStart del, string denyClassName, string denyMemberName, ObjectName denyObjectName, MBeanPermissionAction denyAction)
        {
            if (delSetup != null)
            {
                delSetup();
            }
            MBeanCASPermission perm = new MBeanCASPermission(denyClassName, denyMemberName, denyObjectName, denyAction);

            try
            {
                perm.Deny();
                del();
                return(false);
            }
            catch (SecurityException ex)
            {
                return(true);
            }
            finally
            {
                CodeAccessPermission.RevertDeny();
            }
        }
コード例 #21
0
        public static void Main()
        {
            // Try to access resources using the permissions currently available.
            AttemptAccess("Default permissions");

            // Create a permission set that allows read access to the TEMP
            // environment variable and read, write, and append access to SomeFile
            PermissionSet ps = new PermissionSet(PermissionState.None);

            ps.AddPermission(
                new EnvironmentPermission(EnvironmentPermissionAccess.Read, "TEMP"));
            ps.AddPermission(
                new FileIOPermission(FileIOPermissionAccess.Read |
                                     FileIOPermissionAccess.Write | FileIOPermissionAccess.Append,
                                     Path.GetFullPath("SomeFile")));

            // Use caution in asserting permissions in publicly callable code without
            // any kind of check on the caller.  There is a danger of the assert being
            // used to exploit a downstream caller by stopping its security check,
            // allowing the malicious code access to unauthorized resources.
            // Stop security checks at this point in the stack walk
            // for the specified permissions
            ps.Assert();

            // Try to access resources using the permissions we've just asserted.
            AttemptAccess("Assert permissions");

            // Remove this stack frame's Assert
            CodeAccessPermission.RevertAssert();

            // Deny access to the resources we specify
            ps.Deny();

            // Try to access resources using the permissions we've just denied.
            AttemptAccess("Deny permissions");

            // Remove this stack frame's Deny so we're back to default permissions.
            CodeAccessPermission.RevertDeny();

            // Make the permissions indicate the only things that we're allowed to do.
            ps.PermitOnly();

            // Try to access resources using only the permissions we've just permitted.
            AttemptAccess("PermitOnly permissions");

            // Remove this stack frame's PermitOnly so we're back to default permissions.
            CodeAccessPermission.RevertPermitOnly();

            // Remove the FileIOPermissions from the permission set
            ps.RemovePermission(typeof(FileIOPermission));

            // Try to access resources using only the Environment permissions.
            ps.PermitOnly();
            AttemptAccess("PermitOnly without FileIOPermission permissions");
            CodeAccessPermission.RevertPermitOnly();

            // Remove the EnvironmentPermission from the permission set
            ps.RemovePermission(typeof(EnvironmentPermission));

            // Try to access resources using no permissions.
            ps.PermitOnly();
            AttemptAccess("PermitOnly without any permissions");
            CodeAccessPermission.RevertPermitOnly();

            // Show how to use Demand/Assert to improve performance
            CopyFile(".\\Permissions.exe", ".\\Permissions.copy.exe");

            // Delete .exe copy
            File.Delete(".\\Permissions.copy.exe");
        }