Example #1
0
    // source: http://blogs.msdn.com/shawnfa/archive/2004/10/25/247379.aspx
    static AppDomain CreateRestrictedDomain(string filename)
    {
        PermissionSet   emptySet    = new PermissionSet(PermissionState.None);
        PolicyStatement emptyPolicy = new PolicyStatement(emptySet);
        UnionCodeGroup  root        = new UnionCodeGroup(new AllMembershipCondition(), emptyPolicy);

        PermissionSet userSet = null;

        if (filename [0] == '@')
        {
            userSet = GetNamedPermissionSet(filename.Substring(1));
        }
        else
        {
            userSet = LoadFromFile(filename);
        }

        PolicyStatement userPolicy = new PolicyStatement(userSet);

        root.AddChild(new UnionCodeGroup(new AllMembershipCondition(), userPolicy));

        PolicyLevel pl = PolicyLevel.CreateAppDomainLevel();

        pl.RootCodeGroup = root;

        AppDomain ad = AppDomain.CreateDomain("Restricted");

        ad.SetAppDomainPolicy(pl);
        return(ad);
    }
Example #2
0
                public static void SetAppDomainPolicy(AppDomain appDomain)
                {
                    // Create an AppDomain policy level.
                    PolicyLevel pLevel = PolicyLevel.CreateAppDomainLevel();
                    // The root code group of the policy level combines all
                    // permissions of its children.
                    UnionCodeGroup rootCodeGroup;
                    PermissionSet  ps = new PermissionSet(PermissionState.None);

                    ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
                    rootCodeGroup = new UnionCodeGroup(new AllMembershipCondition(),
                                                       new PolicyStatement(ps, PolicyStatementAttribute.Nothing));

                    NamedPermissionSet localIntranet = FindNamedPermissionSet("LocalIntranet");
                    // The following code limits all code on this machine to local intranet permissions
                    // when running in this application domain.
                    UnionCodeGroup virtualIntranet = new UnionCodeGroup(
                        new ZoneMembershipCondition(SecurityZone.MyComputer),
                        new PolicyStatement(localIntranet,
                                            PolicyStatementAttribute.Nothing));

                    virtualIntranet.Name = "Virtual Intranet";
                    // Add the code groups to the policy level.
                    rootCodeGroup.AddChild(virtualIntranet);
                    pLevel.RootCodeGroup = rootCodeGroup;
                    appDomain.SetAppDomainPolicy(pLevel);
                }
        private static AppDomain CreateRestrictedDomain(string domainName)
        {
            // Default to all code getting nothing
            PolicyStatement emptyPolicy = new PolicyStatement(new PermissionSet(PermissionState.None));
            UnionCodeGroup  policyRoot  = new UnionCodeGroup(new AllMembershipCondition(), emptyPolicy);

            // Grant all code the named permission set for the test
            PermissionSet partialTrustPermissionSet = new PermissionSet(PermissionState.None);

            partialTrustPermissionSet.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.AllFlags));
            partialTrustPermissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution | SecurityPermissionFlag.ControlEvidence));

            PolicyStatement permissions = new PolicyStatement(partialTrustPermissionSet);

            policyRoot.AddChild(new UnionCodeGroup(new AllMembershipCondition(), permissions));

            // Create an AppDomain policy level for the policy tree
            PolicyLevel appDomainLevel = PolicyLevel.CreateAppDomainLevel();

            appDomainLevel.RootCodeGroup = policyRoot;

            // Set the Application Base correctly in order to find the test assembly
            AppDomainSetup ads = new AppDomainSetup();

            ads.ApplicationBase = Environment.CurrentDirectory;

            AppDomain restrictedDomain = AppDomain.CreateDomain(domainName, null, ads);

            restrictedDomain.SetAppDomainPolicy(appDomainLevel);

            return(restrictedDomain);
        }
        private static PolicyLevel GetPolicyForUrl(String strUrl, int iZone, String strAppPath)
        {
            if (strUrl == null || strAppPath == null || strUrl.Length < 1 || strAppPath.Length < 1)
            {
                return(null);
            }

            Evidence       evidence = new Evidence();
            PolicyLevel    plReturn = PolicyLevel.CreateAppDomainLevel();
            PermissionSet  denyPS   = null;
            PermissionSet  ps;
            UnionCodeGroup allCG;
            UnionCodeGroup snCG;
            UnionCodeGroup cg;

            evidence.AddAssembly(new Url(strUrl));
            evidence.AddAssembly(new Zone((SecurityZone)iZone));

            ps = SecurityManager.ResolvePolicy(evidence,
                                               null, null, null, out denyPS);

            ps.RemovePermission(typeof(UrlIdentityPermission));
            ps.RemovePermission(typeof(ZoneIdentityPermission));


            allCG = new UnionCodeGroup(new AllMembershipCondition(),
                                       new PolicyStatement(new PermissionSet(PermissionState.None)));
            snCG = new UnionCodeGroup(
                new StrongNameMembershipCondition(new StrongNamePublicKeyBlob(s_microsoftPublicKey), null, null),
                new PolicyStatement(new PermissionSet(PermissionState.Unrestricted)));

            if (!strAppPath.EndsWith("/"))
            {
                strAppPath += "/";
            }
            strAppPath += "*";

            cg = new UnionCodeGroup(
                new UrlMembershipCondition(strAppPath),
                new PolicyStatement(ps));

            allCG.AddChild(snCG);
            allCG.AddChild(cg);
            plReturn.RootCodeGroup.AddChild(allCG);

            return(plReturn);
        }
Example #5
0
        public void CopyWithChildren()
        {
            UnionCodeGroup cgChild = new UnionCodeGroup(new AllMembershipCondition(), new PolicyStatement(new PermissionSet(PermissionState.Unrestricted)));
            UnionCodeGroup cg      = new UnionCodeGroup(new AllMembershipCondition(), new PolicyStatement(new PermissionSet(PermissionState.None)));

            cg.AddChild(cgChild);
            UnionCodeGroup cg2 = (UnionCodeGroup)cg.Copy();

            Assert.AreEqual(cg.Children.Count, cg2.Children.Count, "Children");
            Assert.AreEqual(cg.ToXml().ToString(), cg2.ToXml().ToString(), "ToXml");
        }
Example #6
0
        public void ResolveMatchingCodeGroups_TwoLevel()
        {
            UnionCodeGroup level1 = new UnionCodeGroup(new AllMembershipCondition(), new PolicyStatement(new PermissionSet(PermissionState.None)));
            CodeGroup      level2 = level1.Copy();

            level1.AddChild(level2);

            CodeGroup match = level1.ResolveMatchingCodeGroups(new Evidence());

            Assert.IsNotNull(match, "Match");
            Assert.IsTrue(match.Equals(level1, false), "Equals(false)");
            Assert.IsTrue(match.Equals(level1, true), "Equals(true)");

            UnionCodeGroup level2b = new UnionCodeGroup(new ZoneMembershipCondition(SecurityZone.Untrusted), new PolicyStatement(new PermissionSet(PermissionState.Unrestricted)));

            level1.AddChild(level2b);
            CodeGroup match2 = level1.ResolveMatchingCodeGroups(new Evidence());

            Assert.IsNotNull(match2, "Match2");
            Assert.IsTrue(match2.Equals(level1, false), "Equals(false)");
            Assert.IsTrue(!match2.Equals(level1, true), "Equals(true)");
        }
        // Create new code groups using the custom named permission sets previously created.
        private static void CreateCodeGroups()
        {
            // Create instances of the named permission sets created earlier to establish the
            // permissions for the new code groups.
            NamedPermissionSet companyCodeSet    = new NamedPermissionSet("MyCompany", PermissionState.Unrestricted);
            NamedPermissionSet departmentCodeSet = new NamedPermissionSet("MyDepartment", PermissionState.Unrestricted);
            // Create new code groups using the named permission sets.
            PolicyStatement policyMyCompany    = new PolicyStatement(companyCodeSet, PolicyStatementAttribute.LevelFinal);
            PolicyStatement policyMyDepartment = new PolicyStatement(departmentCodeSet, PolicyStatementAttribute.Exclusive);
            // Create new code groups using UnionCodeGroup.
            CodeGroup myCompanyZone = new UnionCodeGroup(new ZoneMembershipCondition(SecurityZone.Intranet), policyMyCompany);

            myCompanyZone.Name = "MyCompanyCodeGroup";

            byte[] b1 = { 0, 36, 0, 0, 4, 128, 0, 0, 148, 0, 0, 0, 6, 2, 0, 0, 0, 36, 0, 0, 82, 83, 65, 49, 0, 4, 0, 0, 1, 0, 1, 0, 237, 146, 145, 51, 34, 97, 123, 196, 90, 174, 41, 170, 173, 221, 41, 193, 175, 39, 7, 151, 178, 0, 230, 152, 218, 8, 206, 206, 170, 84, 111, 145, 26, 208, 158, 240, 246, 219, 228, 34, 31, 163, 11, 130, 16, 199, 111, 224, 4, 112, 46, 84, 0, 104, 229, 38, 39, 63, 53, 189, 0, 157, 32, 38, 34, 109, 0, 171, 114, 244, 34, 59, 9, 232, 150, 192, 247, 175, 104, 143, 171, 42, 219, 66, 66, 194, 191, 218, 121, 59, 92, 42, 37, 158, 13, 108, 210, 189, 9, 203, 204, 32, 48, 91, 212, 101, 193, 19, 227, 107, 25, 133, 70, 2, 220, 83, 206, 71, 102, 245, 104, 252, 87, 109, 190, 56, 34, 180 };
            StrongNamePublicKeyBlob blob = new StrongNamePublicKeyBlob(b1);

            CodeGroup myDepartmentZone = new UnionCodeGroup(new StrongNameMembershipCondition(blob, null, null), policyMyDepartment);

            myDepartmentZone.Name = "MyDepartmentCodeGroup";

            // Move through the policy levels looking for the Machine policy level.
            // Create two new code groups at that level.
            IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy();

            while (policyEnumerator.MoveNext())
            {
                // At the Machine level delete already existing copies of the custom code groups,
                // then create the new code groups.
                PolicyLevel currentLevel = (PolicyLevel)policyEnumerator.Current;
                if (currentLevel.Label == "Machine")
                {
                    // Remove old instances of the custom groups.
                    DeleteCustomCodeGroups();
                    // Add the new code groups.
                    //*******************************************************
                    // To add a child code group, add the child to the parent prior to adding
                    // the parent to the root.
                    myCompanyZone.AddChild(myDepartmentZone);
                    // Add the parent to the root code group.
                    currentLevel.RootCodeGroup.AddChild(myCompanyZone);
                    SecurityManager.SavePolicy();
                }
            }
            // Save the security policy.
            SecurityManager.SavePolicy();
            Console.WriteLine("Security policy modified.");
            Console.WriteLine("New code groups added at the Machine policy level.");
        }
        static AppDomain NewDomain()
        {
            PolicyStatement statement = new PolicyStatement(new PermissionSet(PermissionState.None), PolicyStatementAttribute.Nothing);
            PermissionSet   ps        = new PermissionSet(PermissionState.None);

            ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
            ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.Assertion));
            ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlAppDomain));
            ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlDomainPolicy));
            ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlEvidence));
            ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlPolicy));
            ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlPrincipal));
            ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlThread));
            ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.Infrastructure));
            ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.RemotingConfiguration));
            ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter));
            ps.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
            ps.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
            ps.AddPermission(new ReflectionPermission(PermissionState.Unrestricted));
            ps.AddPermission(new RegistryPermission(PermissionState.Unrestricted));
            ps.AddPermission(new IsolatedStorageFilePermission(PermissionState.Unrestricted));
            ps.AddPermission(new EventLogPermission(PermissionState.Unrestricted));
            ps.AddPermission(new PerformanceCounterPermission(PermissionState.Unrestricted));
            ps.AddPermission(new DnsPermission(PermissionState.Unrestricted));
            ps.AddPermission(new UIPermission(PermissionState.Unrestricted));
            PolicyStatement statement1 = new PolicyStatement(ps, PolicyStatementAttribute.Exclusive);
            CodeGroup       group;

            group = new UnionCodeGroup(new AllMembershipCondition(), statement);
            group.AddChild(new UnionCodeGroup(new ZoneMembershipCondition(SecurityZone.MyComputer), statement1));
            PolicyLevel level = PolicyLevel.CreateAppDomainLevel();

            level.RootCodeGroup = group;

            AppDomain domain = AppDomain.CreateDomain("test");

            domain.SetAppDomainPolicy(level);
            return(domain);
        }
Example #9
0
        /// <summary>
        /// 设置程序域的权限
        /// </summary>
        /// <param name="pAppDomain">指定的程序域</param>
        private void SetAppDomainPolicy(AppDomain pAppDomain)
        {
            PolicyLevel pLevel = PolicyLevel.CreateAppDomainLevel();

            PermissionSet pPermission = new PermissionSet(PermissionState.None);

            pPermission.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

            UnionCodeGroup pRootGroup = new UnionCodeGroup(new AllMembershipCondition(),
                                                           new PolicyStatement(pPermission, PolicyStatementAttribute.Nothing));

            NamedPermissionSet pPermissionSet = FindNamedPermissionSet("Machine", "Everything");

            UnionCodeGroup pChileGroup = new UnionCodeGroup(
                new ZoneMembershipCondition(SecurityZone.MyComputer),
                new PolicyStatement(pPermissionSet, PolicyStatementAttribute.Nothing));

            pChileGroup.Name = "Virtual Intranet";
            pRootGroup.AddChild(pChileGroup);
            pLevel.RootCodeGroup = pRootGroup;
            pAppDomain.SetAppDomainPolicy(pLevel);
        }
Example #10
0
	// source: http://blogs.msdn.com/shawnfa/archive/2004/10/25/247379.aspx
	static AppDomain CreateRestrictedDomain (string filename)
	{
		PermissionSet emptySet = new PermissionSet (PermissionState.None);
		PolicyStatement emptyPolicy = new PolicyStatement (emptySet);
		UnionCodeGroup root = new UnionCodeGroup (new AllMembershipCondition (), emptyPolicy);

		PermissionSet userSet = null;
		if (filename [0] == '@')
			userSet = GetNamedPermissionSet (filename.Substring (1));
		else
			userSet = LoadFromFile (filename);

		PolicyStatement userPolicy = new PolicyStatement (userSet);
		root.AddChild (new UnionCodeGroup (new AllMembershipCondition (), userPolicy));

		PolicyLevel pl = PolicyLevel.CreateAppDomainLevel ();
		pl.RootCodeGroup = root;

		AppDomain ad = AppDomain.CreateDomain ("Restricted");
		ad.SetAppDomainPolicy (pl);
		return ad;
	}
Example #11
0
        private static void SetupPolicy(string path, string name)
        {
            //Get a reference to the User level "All Code" group.
            PolicyLevel polLevel = GetPolicy(_user);

            if (polLevel != null)
            {
                UnionCodeGroup allCodeCG =
                    (UnionCodeGroup)polLevel.RootCodeGroup;

                //Create a new code group with the FullTrust permission
                //set and a URL as evidence of membership.
                PermissionSet          permSet    = polLevel.GetNamedPermissionSet(_fullTrust);
                UrlMembershipCondition urlMemCond = new UrlMembershipCondition(path);
                UnionCodeGroup         cg         =
                    new UnionCodeGroup(urlMemCond, new PolicyStatement(permSet));
                cg.Name = name;
                allCodeCG.AddChild(cg);

                //Save the policy
                SecurityManager.SavePolicy();
            }
        }
Example #12
0
    public static void CreateAPolicyLevel()
    {
        try
        {
            //<Snippet2>
            // Create an AppDomain policy level.
            PolicyLevel pLevel = PolicyLevel.CreateAppDomainLevel();
            //</Snippet2>
            // The root code group of the policy level combines all
            // permissions of its children.
            UnionCodeGroup rootCodeGroup;
            PermissionSet  ps = new PermissionSet(PermissionState.None);
            ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

            rootCodeGroup = new UnionCodeGroup(
                new AllMembershipCondition(),
                new PolicyStatement(ps, PolicyStatementAttribute.Nothing));

            // This code group grants FullTrust to assemblies with the strong
            // name key from this assembly.
            UnionCodeGroup myCodeGroup = new UnionCodeGroup(
                new StrongNameMembershipCondition(
                    new StrongNamePublicKeyBlob(GetKey()),
                    null,
                    null),
                new PolicyStatement(new PermissionSet(PermissionState.Unrestricted),
                                    PolicyStatementAttribute.Nothing)
                );
            myCodeGroup.Name = "My CodeGroup";


            //<Snippet4>
            // Add the code groups to the policy level.
            rootCodeGroup.AddChild(myCodeGroup);
            pLevel.RootCodeGroup = rootCodeGroup;
            Console.WriteLine("Permissions granted to all code running in this AppDomain level: ");
            Console.WriteLine(rootCodeGroup.ToXml());
            Console.WriteLine("Child code groups in RootCodeGroup:");
            IList       codeGroups = pLevel.RootCodeGroup.Children;
            IEnumerator codeGroup  = codeGroups.GetEnumerator();
            while (codeGroup.MoveNext())
            {
                Console.WriteLine("\t" + ((CodeGroup)codeGroup.Current).Name);
            }
            //</Snippet4>
            //<Snippet5>
            Console.WriteLine("Demonstrate adding and removing named permission sets.");
            Console.WriteLine("Original named permission sets:");
            ListPermissionSets(pLevel);
            NamedPermissionSet myInternet = pLevel.GetNamedPermissionSet("Internet");
            //</Snippet5>
            myInternet.Name = "MyInternet";
            //<Snippet6>
            pLevel.AddNamedPermissionSet(myInternet);
            //</Snippet6>
            Console.WriteLine("\nNew named permission sets:");
            ListPermissionSets(pLevel);
            myInternet.RemovePermission(typeof(System.Security.Permissions.FileDialogPermission));
            //<Snippet7>
            pLevel.ChangeNamedPermissionSet("MyInternet", myInternet);
            //</Snippet7>
            //<Snippet8>
            pLevel.RemoveNamedPermissionSet("MyInternet");
            //</Snippet8>
            Console.WriteLine("\nCurrent permission sets:");
            ListPermissionSets(pLevel);
            pLevel.AddNamedPermissionSet(myInternet);
            Console.WriteLine("\nUpdated named permission sets:");
            ListPermissionSets(pLevel);
            //<Snippet9>
            pLevel.Reset();
            //</Snippet9>
            Console.WriteLine("\nReset named permission sets:");
            ListPermissionSets(pLevel);
            //<Snippet10>
            Console.WriteLine("\nType property = " + pLevel.Type.ToString());
            //</Snippet10>
            //<Snippet11>
            Console.WriteLine("The result of GetHashCode is " + pLevel.GetHashCode().ToString());
            //</Snippet11>
            Console.WriteLine("StoreLocation property for the AppDomain level is empty, since AppDomain policy " +
                              "cannot be saved to a file.");
            Console.WriteLine("StoreLocation property = " + pLevel.StoreLocation);
            //<Snippet12>
            PolicyLevel pLevelCopy = PolicyLevel.CreateAppDomainLevel();
            // Create a copy of the PolicyLevel using ToXml/FromXml.
            pLevelCopy.FromXml(pLevel.ToXml());

            if (ComparePolicyLevels(pLevel, pLevelCopy))
            {
                Console.WriteLine("The ToXml/FromXml roundtrip was successful.");
            }
            else
            {
                Console.WriteLine("ToXml/FromXml roundtrip failed.");
            }
            //</Snippet12>
            Console.WriteLine("Show the result of resolving policy for evidence unique to the AppDomain policy level.");
            Evidence myEvidence = new Evidence(new object[] { myCodeGroup }, null);
            CheckEvidence(pLevel, myEvidence);
            return;
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return;
        }
    }
Example #13
0
        /// <summary>
        /// Create an AppDomain that contains policy restricting code to execute
        /// with only the permissions granted by a named permission set
        /// </summary>
        /// <param name="permissionSetName">name of the permission set to restrict to</param>
        /// <param name="appDomainName">'friendly' name of the appdomain to be created</param>
        /// <exception cref="ArgumentNullException">
        /// if <paramref name="permissionSetName"/> is null
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// if <paramref name="permissionSetName"/> is empty
        /// </exception>
        /// <returns>AppDomain with a restricted security policy</returns>
        /// <remarks>Substantial portions of this function from: http://blogs.msdn.com/shawnfa/archive/2004/10/25/247379.aspx
        /// Valid permissionSetName values are:
        /// * FullTrust
        /// * SkipVerification
        /// * Execution
        /// * Nothing
        /// * LocalIntranet
        /// * Internet
        /// * Everything
        /// </remarks>
#pragma warning disable 0618
        public static AppDomain CreateRestrictedDomain(string permissionSetName, string appDomainName)
        {
            if (permissionSetName == null)
            {
                throw new ArgumentNullException("permissionSetName");
            }
            if (permissionSetName.Length == 0)
            {
                throw new ArgumentOutOfRangeException("permissionSetName", permissionSetName,
                                                      "Cannot have an empty permission set name");
            }

            // Default to all code getting nothing
            PolicyStatement emptyPolicy = new PolicyStatement(new PermissionSet(PermissionState.None));
            UnionCodeGroup  policyRoot  = new UnionCodeGroup(new AllMembershipCondition(), emptyPolicy);

            bool          foundName       = false;
            PermissionSet setIntersection = new PermissionSet(PermissionState.Unrestricted);

            // iterate over each policy level
            IEnumerator levelEnumerator = SecurityManager.PolicyHierarchy();

            while (levelEnumerator.MoveNext())
            {
                PolicyLevel level = levelEnumerator.Current as PolicyLevel;

                // if this level has defined a named permission set with the
                // given name, then intersect it with what we've retrieved
                // from all the previous levels
                if (level != null)
                {
                    PermissionSet levelSet = level.GetNamedPermissionSet(permissionSetName);
                    if (levelSet != null)
                    {
                        foundName = true;
                        if (setIntersection != null)
                        {
                            setIntersection = setIntersection.Intersect(levelSet);
                        }
                    }
                }
            }

            // Intersect() can return null for an empty set, so convert that
            // to an empty set object. Also return an empty set if we didn't find
            // the named permission set we were looking for
            if (setIntersection == null || !foundName)
            {
                setIntersection = new PermissionSet(PermissionState.None);
            }
            else
            {
                setIntersection = new NamedPermissionSet(permissionSetName, setIntersection);
            }

            // if no named permission sets were found, return an empty set,
            // otherwise return the set that was found
            PolicyStatement permissions = new PolicyStatement(setIntersection);

            policyRoot.AddChild(new UnionCodeGroup(new AllMembershipCondition(), permissions));

            // create an AppDomain policy level for the policy tree
            PolicyLevel appDomainLevel = PolicyLevel.CreateAppDomainLevel();

            appDomainLevel.RootCodeGroup = policyRoot;

            // create an AppDomain where this policy will be in effect
            string    domainName       = appDomainName;
            AppDomain restrictedDomain = AppDomain.CreateDomain(domainName);

            restrictedDomain.SetAppDomainPolicy(appDomainLevel);

            return(restrictedDomain);
        }
        /// From MRMModule.cs by Adam Frisby
        /// <summary>
        ///     Create an AppDomain that contains policy restricting code to execute
        ///     with only the permissions granted by a named permission set
        /// </summary>
        /// <param name="permissionSetName">name of the permission set to restrict to</param>
        /// <param name="appDomainName">'friendly' name of the appdomain to be created</param>
        /// <param name="ads"></param>
        /// <exception cref="ArgumentNullException">
        ///     if <paramref name="permissionSetName" /> is null
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        ///     if <paramref name="permissionSetName" /> is empty
        /// </exception>
        /// <returns>AppDomain with a restricted security policy</returns>
        /// <remarks>
        ///     Substantial portions of this function from: http://blogs.msdn.com/shawnfa/archive/2004/10/25/247379.aspx
        ///     Valid permissionSetName values are:
        ///     * FullTrust
        ///     * SkipVerification
        ///     * Execution
        ///     * Nothing
        ///     * LocalIntranet
        ///     * Internet
        ///     * Everything
        /// </remarks>
        public AppDomain CreateRestrictedDomain(string permissionSetName, string appDomainName, AppDomainSetup ads)
        {
            if (permissionSetName == null)
            {
                throw new ArgumentNullException("permissionSetName");
            }
            if (permissionSetName.Length == 0)
            {
                throw new ArgumentOutOfRangeException("permissionSetName", permissionSetName,
                                                      "Cannot have an empty permission set name");
            }

            // Default to all code getting everything
            PermissionSet setIntersection  = new PermissionSet(PermissionState.Unrestricted);
            AppDomain     restrictedDomain = null;

#if LINUX
        #pragma warning disable 612, 618
            PolicyStatement emptyPolicy = new PolicyStatement(new PermissionSet(PermissionState.None));
            UnionCodeGroup  policyRoot  = new UnionCodeGroup(new AllMembershipCondition(), emptyPolicy);

            bool foundName = false;
            // iterate over each policy level
            IEnumerator levelEnumerator = SecurityManager.PolicyHierarchy();
            while (levelEnumerator.MoveNext())
            {
                PolicyLevel level = levelEnumerator.Current as PolicyLevel;

                // if this level has defined a named permission set with the
                // given name, then intersect it with what we've retrieved
                // from all the previous levels
                if (level != null)
                {
                    PermissionSet levelSet = level.GetNamedPermissionSet(permissionSetName);
                    if (levelSet != null)
                    {
                        foundName = true;
                        if (setIntersection != null)
                        {
                            setIntersection = setIntersection.Intersect(levelSet);
                        }
                    }
                }
            }

            // Intersect() can return null for an empty set, so convert that
            // to an empty set object. Also return an empty set if we didn't find
            // the named permission set we were looking for
            if (setIntersection == null || !foundName)
            {
                setIntersection = new PermissionSet(PermissionState.None);
            }
            else
            {
                setIntersection = new NamedPermissionSet(permissionSetName, setIntersection);
            }

            // if no named permission sets were found, return an empty set,
            // otherwise return the set that was found
            setIntersection.AddPermission(new SocketPermission(PermissionState.Unrestricted));
            setIntersection.AddPermission(new WebPermission(PermissionState.Unrestricted));
            setIntersection.AddPermission(new SecurityPermission(PermissionState.Unrestricted));

            PolicyStatement permissions = new PolicyStatement(setIntersection);
            policyRoot.AddChild(new UnionCodeGroup(new AllMembershipCondition(), permissions));

            // create an AppDomain policy level for the policy tree
            PolicyLevel appDomainLevel = PolicyLevel.CreateAppDomainLevel();
            appDomainLevel.RootCodeGroup = policyRoot;

            // create an AppDomain where this policy will be in effect
            restrictedDomain = AppDomain.CreateDomain(appDomainName, null, ads);
            restrictedDomain.SetAppDomainPolicy(appDomainLevel);
        #pragma warning restore 612, 618
#else
            SecurityZone zone = SecurityZone.MyComputer;
            try
            {
                zone = (SecurityZone)Enum.Parse(typeof(SecurityZone), permissionSetName);
            }
            catch
            {
                zone = SecurityZone.MyComputer;
            }

            Evidence ev = new Evidence();
            ev.AddHostEvidence(new Zone(zone));
            setIntersection = SecurityManager.GetStandardSandbox(ev);
            setIntersection.AddPermission(new System.Net.SocketPermission(PermissionState.Unrestricted));
            setIntersection.AddPermission(new System.Net.WebPermission(PermissionState.Unrestricted));
            setIntersection.AddPermission(
                new System.Security.Permissions.SecurityPermission(PermissionState.Unrestricted));

            // create an AppDomain where this policy will be in effect
            restrictedDomain = AppDomain.CreateDomain(appDomainName, ev, ads, setIntersection, null);
#endif

            return(restrictedDomain);
        }
Example #15
0
    // Create new code groups using the custom named permission sets previously created. 
    private static void CreateCodeGroups()
    {
        // Create instances of the named permission sets created earlier to establish the 
        // permissions for the new code groups.
        NamedPermissionSet companyCodeSet = new NamedPermissionSet("MyCompany",PermissionState.Unrestricted);
        NamedPermissionSet departmentCodeSet = new NamedPermissionSet("MyDepartment",PermissionState.Unrestricted);
        // Create new code groups using the named permission sets.
        PolicyStatement policyMyCompany = new PolicyStatement(companyCodeSet,PolicyStatementAttribute.LevelFinal);
        PolicyStatement policyMyDepartment = new PolicyStatement(departmentCodeSet,PolicyStatementAttribute.Exclusive);
        // Create new code groups using UnionCodeGroup.
        CodeGroup myCompanyZone = new UnionCodeGroup(new ZoneMembershipCondition(SecurityZone.Intranet), policyMyCompany);
        myCompanyZone.Name = "MyCompanyCodeGroup";

        byte[] b1 = { 0, 36, 0, 0, 4, 128, 0, 0, 148, 0, 0, 0, 6, 2, 0, 0, 0, 36, 0, 0, 82, 83, 65, 49, 0, 4, 0, 0, 1, 0, 1, 0, 237, 146, 145, 51, 34, 97, 123, 196, 90, 174, 41, 170, 173, 221, 41, 193, 175, 39, 7, 151, 178, 0, 230, 152, 218, 8, 206, 206, 170,84, 111, 145, 26, 208, 158, 240, 246, 219, 228, 34, 31, 163, 11, 130, 16, 199, 111, 224, 4, 112, 46, 84, 0, 104, 229, 38, 39, 63, 53, 189, 0, 157, 32, 38, 34, 109, 0, 171, 114, 244, 34, 59, 9, 232, 150, 192, 247, 175, 104, 143, 171, 42, 219, 66, 66, 194, 191, 218, 121, 59, 92, 42, 37, 158, 13, 108, 210, 189, 9, 203, 204, 32, 48, 91, 212, 101, 193, 19, 227, 107, 25, 133, 70, 2, 220, 83, 206, 71, 102, 245, 104, 252, 87, 109, 190, 56, 34, 180};
        StrongNamePublicKeyBlob blob = new StrongNamePublicKeyBlob(b1);

        CodeGroup myDepartmentZone = new UnionCodeGroup(new StrongNameMembershipCondition(blob, null, null), policyMyDepartment);
        myDepartmentZone.Name = "MyDepartmentCodeGroup";

        // Move through the policy levels looking for the Machine policy level. 
        // Create two new code groups at that level.
        IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy();
        while(policyEnumerator.MoveNext())
        {
            // At the Machine level delete already existing copies of the custom code groups, 
            // then create the new code groups.
            PolicyLevel currentLevel = (PolicyLevel)policyEnumerator.Current;
            if (currentLevel.Label == "Machine")
            {

                // Remove old instances of the custom groups.
                DeleteCustomCodeGroups();
                // Add the new code groups. 
                //******************************************************* 
                // To add a child code group, add the child to the parent prior to adding 
                // the parent to the root.
                myCompanyZone.AddChild(myDepartmentZone);
                // Add the parent to the root code group.
                currentLevel.RootCodeGroup.AddChild(myCompanyZone);
                SecurityManager.SavePolicy();
            }
        }
        // Save the security policy.
        SecurityManager.SavePolicy();
        Console.WriteLine("Security policy modified.");
        Console.WriteLine("New code groups added at the Machine policy level.");
    }
Example #16
0
        public void ResolveWithChildren()
        {
            PermissionSet pset1 = new PermissionSet(PermissionState.None);
            PermissionSet pset2 = new PermissionSet(PermissionState.None);
            PermissionSet pset3 = new PermissionSet(PermissionState.None);
            PermissionSet pset4 = new PermissionSet(PermissionState.None);
            PermissionSet pset5 = new PermissionSet(PermissionState.None);
            PermissionSet pset6 = new PermissionSet(PermissionState.None);

            IPermission perm1 = new UIPermission(PermissionState.Unrestricted);
            IPermission perm2 = new EnvironmentPermission(PermissionState.Unrestricted);
            IPermission perm3 = new FileDialogPermission(PermissionState.Unrestricted);
            IPermission perm4 = new ReflectionPermission(PermissionState.Unrestricted);
            IPermission perm5 = new RegistryPermission(PermissionState.Unrestricted);
            IPermission perm6 = new FileIOPermission(PermissionState.Unrestricted);

            pset1.AddPermission(perm1);
            PolicyStatement policy1 = new PolicyStatement(pset1);

            pset2.AddPermission(perm2);
            PolicyStatement policy2 = new PolicyStatement(pset2);

            pset3.AddPermission(perm3);
            PolicyStatement policy3 = new PolicyStatement(pset3);

            pset4.AddPermission(perm4);
            PolicyStatement policy4 = new PolicyStatement(pset4);

            pset5.AddPermission(perm5);
            PolicyStatement policy5 = new PolicyStatement(pset5);

            pset6.AddPermission(perm6);
            PolicyStatement policy6 = new PolicyStatement(pset6);

            UnionCodeGroup root = new UnionCodeGroup(new AllMembershipCondition(), policy1);

            UnionCodeGroup child1        = new UnionCodeGroup(new ZoneMembershipCondition(SecurityZone.Internet), policy2);
            UnionCodeGroup child2        = new UnionCodeGroup(new AllMembershipCondition(), policy3);
            UnionCodeGroup child3        = new UnionCodeGroup(new AllMembershipCondition(), policy4);
            UnionCodeGroup childofchild1 = new UnionCodeGroup(new AllMembershipCondition(), policy5);
            UnionCodeGroup childofchild3 = new UnionCodeGroup(new AllMembershipCondition(), policy6);

            child1.AddChild(childofchild1);
            child3.AddChild(childofchild3);

            root.AddChild(child1);
            root.AddChild(child2);
            root.AddChild(child3);

            PolicyStatement result = root.Resolve(new Evidence());

            PermissionSet correctset = new PermissionSet(PermissionState.None);

            correctset.AddPermission(perm1);
            correctset.AddPermission(perm3);
            correctset.AddPermission(perm4);
            correctset.AddPermission(perm6);

            Assert.AreEqual(correctset.Count, result.PermissionSet.Count, "PermissionSet.Count");
            foreach (IPermission p in correctset)
            {
                IPermission r = result.PermissionSet.GetPermission(p.GetType());
                Assert.IsNotNull(r, "PermissionSet.GetPermission");
            }
        }