Esempio n. 1
0
        [Category("NotDotNet")]          // System.ExecutionEngineException on MS runtime (1.1)
#endif
        public void GetNamedPermissionSet()
        {
            PolicyLevel        pl  = Load(minimal, PolicyLevelType.Machine);
            NamedPermissionSet nps = pl.GetNamedPermissionSet("Mono");

            Assert.IsNull(nps, "GetNamedPermissionSet(notfound)");
            nps = new NamedPermissionSet("Mono", PermissionState.None);
            pl.AddNamedPermissionSet(nps);
            // ExecutionEngineException here!
            nps = pl.GetNamedPermissionSet("Mono");
            Assert.IsNotNull(nps, "GetNamedPermissionSet(found)");
        }
Esempio n. 2
0
        }// WizNext

        protected override int WizFinish()
        {
            // See if we're on the bail-out page...
            if (m_nPageToGetPermissionLevel == Page6Index)
            {
                return(0);
            }

            // Choose the permission set we want to use....
            PermissionSet permSet      = null;
            String        sPolicyLevel = Page1.isForHomeUser?"Machine":"User";
            PolicyLevel   pl           = Security.GetPolicyLevelFromLabel(sPolicyLevel);

            if (m_nPageToGetPermissionLevel == Page4Index)
            {
                // If the user decided to not give full trust, end the wizard without doing anything
                if (!Page4.GiveFullTrust)
                {
                    return(0);
                }
                else
                {
                    // Else, go ahead and give the FullTrust permission set
                    permSet = pl.GetNamedPermissionSet("FullTrust");
                }
            }
            else
            {
                if (Page5.MyTrustLevel == PermissionSetType.FULLTRUST)
                {
                    permSet = pl.GetNamedPermissionSet("FullTrust");
                }
                else if (Page5.MyTrustLevel == PermissionSetType.INTERNET)
                {
                    permSet = pl.GetNamedPermissionSet("Internet");
                }
                else if (Page5.MyTrustLevel == PermissionSetType.INTRANET)
                {
                    permSet = pl.GetNamedPermissionSet("LocalIntranet");
                }
                else if (Page5.MyTrustLevel == PermissionSetType.NONE)
                {
                    permSet = pl.GetNamedPermissionSet("Nothing");
                }
                else
                {
                    permSet = null;
                }
            }

            m_fChangesMade = (CreateCodegroup(permSet, true) != null);
            return(0);
        }// WizFinish
Esempio n. 3
0
        private static PermissionSet /*!*/ CreatePermissionSetByName()
        {
            string        name            = "Internet";
            bool          foundName       = false;
            PermissionSet setIntersection = new PermissionSet(PermissionState.Unrestricted);

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

            while (e.MoveNext())
            {
                PolicyLevel   level    = (PolicyLevel)e.Current;
                PermissionSet levelSet = level.GetNamedPermissionSet(name);
                if (levelSet != null)
                {
                    foundName       = true;
                    setIntersection = setIntersection.Intersect(levelSet);
                }
            }

            if (setIntersection == null || !foundName)
            {
                setIntersection = new PermissionSet(PermissionState.None);
            }
            else
            {
                setIntersection = new NamedPermissionSet(name, setIntersection);
            }

            return(setIntersection);
        }
        }// GetCodegroupName

        private PermissionSet GetPermissionSetNameFromSecurityLevel(PolicyLevel pl, int nLevel)
        {
            String sNameOfPermissionSet = null;

            switch (nLevel)
            {
            case PermissionSetType.NONE:
                sNameOfPermissionSet = "Nothing";
                break;

            case PermissionSetType.INTERNET:
                sNameOfPermissionSet = "Internet";
                break;

            case PermissionSetType.INTRANET:
                sNameOfPermissionSet = "LocalIntranet";
                break;

            case PermissionSetType.FULLTRUST:
                sNameOfPermissionSet = "FullTrust";
                break;

            default:
                throw new Exception("Help! I don't know about this security level");
            }

            return(pl.GetNamedPermissionSet(sNameOfPermissionSet));
        } // GetPermissionSetNameFromSecurityLevel
Esempio n. 5
0
        private void SetSandBoxPolicy()
        {
            if (!this.SandBox)
            {
                throw new InvalidOperationException("SandBox property is not set to true");
            }
            // http://www.dotnetthis.com/Articles/DynamicSandboxing.htm

            // Now we need to set the appdomain policy,
            // and to do that we will need to create a Policy Level.
            // A Policy Level is a tree-like structure that has Code Groups as its nodes.
            // Each code group consists of a Membership Condition (something that
            // defines if an assembly in question belongs to the code group) and
            // a Permission Set that is granted to the assembly if it does.
            PolicyLevel domainPolicy = PolicyLevel.CreateAppDomainLevel();

            // Let's create a code group that gives Internet permission set
            // to all code.
            // First, let's create a membership condition that accepts all code.
            AllMembershipCondition allCodeMC = new AllMembershipCondition();

            // If you were to build a more complex policy (giving different permissions
            // to different assemblies) you could use other membership conditions,
            // such as ZoneMembershipCondition, StrongNameMembershipCondition, etc.

            // Now let's create a policy statement that represents Internet permissions.
            // Here we just grab named permission set called "Internet" from the default policy,
            // but you could also create your own permission set with whatever permissions
            // you want in there.
            PermissionSet   internetPermissionSet   = domainPolicy.GetNamedPermissionSet("Internet");
            PolicyStatement internetPolicyStatement = new PolicyStatement(internetPermissionSet);

            // We are ready to create a code group that maps all code to Internet permissions
            CodeGroup allCodeInternetCG = new UnionCodeGroup(allCodeMC, internetPolicyStatement);

            // We have used a UnionCodeGroup here. It does not make much difference for
            // a simple policy like ours here, but if you were to set up a more complex one
            // you would probably add some child code groups and then the type of the parent
            // code group would matter. UnionCodeGroup unions all permissions granted by its
            // child code groups (as opposed to FirstMatchCodeGroup that only takes one child
            // code group into effect).
            // Once we have the CodeGroup set up we can add it to our Policy Level.
            domainPolicy.RootCodeGroup = allCodeInternetCG;

            // If our root code group had any children the whole tree would be added
            // to the appdomain security policy now.
            // Imagine you wanted to modify our policy so that your strongname signed
            // assemblies would get FullTrust and all other assemblies would get Internet
            // permissions. Do accomplish that you would create a new UnionCodeGroup,
            // whose membership condition would be a StrongNameMembershipCondition
            // specifying your public key, and its permission set would be a "FullTrust"
            // or just a "new PermissionSet(PermissionState.Unrestricted)".
            // Then you would add that code group as a child to our allCodeInternetCG by
            // calling its AddChild method. Whenever you then loaded a correct strong
            // name signed assembly into your appdomain it would get Internet from the
            // root code group and FullTrust from the child code group, and the effective
            // permissions would be a union of the two, which is FullTrust.
            // and our final policy related step is setting the AppDomain policy
            this.Domain.SetAppDomainPolicy(domainPolicy);
        }
Esempio n. 6
0
    // source: http://blogs.msdn.com/shawnfa/archive/2004/10/22/246549.aspx
    static PermissionSet GetNamedPermissionSet(string name)
    {
        bool          foundName = false;
        PermissionSet pset      = new PermissionSet(PermissionState.Unrestricted);

        IEnumerator e = SecurityManager.PolicyHierarchy();

        while (e.MoveNext())
        {
            PolicyLevel pl = e.Current as PolicyLevel;

            PermissionSet levelpset = pl.GetNamedPermissionSet(name);
            if ((levelpset != null) && (pset != null))
            {
                foundName = true;
                pset      = pset.Intersect(levelpset);
            }
        }

        if (pset == null || !foundName)
        {
            return(new PermissionSet(PermissionState.None));
        }

        return(new NamedPermissionSet(name, pset));
    }
 private PermissionSet GetNamedPermissionSet(string name)
 {
     if (_domainPolicy != null)
     {
         return(_domainPolicy.GetNamedPermissionSet(name));
     }
     return(null);
 }
Esempio n. 8
0
        public static PermissionSet GetNamedPermissionSet(string name)
        {
            IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy();

            // Move through the policy levels to the machine policy level.
            while (policyEnumerator.MoveNext())
            {
                PolicyLevel currentLevel = (PolicyLevel)policyEnumerator.Current;

                if (currentLevel.Label == "Machine")
                {
                    return(currentLevel.GetNamedPermissionSet(name));
                }
            }
            return(null);
        }
Esempio n. 9
0
        public SecurityElement ToXml(PolicyLevel level)
        {
            SecurityElement element;

            element = new SecurityElement("PolicyStatement");
            element.AddAttribute
                ("class",
                SecurityElement.Escape(typeof(PolicyStatement).
                                       AssemblyQualifiedName));
            element.AddAttribute("version", "1");
            if (attributes != PolicyStatementAttribute.Nothing)
            {
                element.AddAttribute("Attributes", attributes.ToString());
            }
            if (permSet != null)
            {
                NamedPermissionSet namedSet;
                namedSet = (permSet as NamedPermissionSet);
                if (namedSet != null)
                {
                    if (level != null &&
                        level.GetNamedPermissionSet(namedSet.Name) != null)
                    {
                        element.AddAttribute
                            ("PermissionSetName",
                            SecurityElement.Escape(namedSet.Name));
                    }
                    else
                    {
                        element.AddChild(permSet.ToXml());
                    }
                }
                else
                {
                    element.AddChild(permSet.ToXml());
                }
            }
            return(element);
        }
Esempio n. 10
0
        public static void PolicyLevelCallMethods()
        {
            PolicyLevel        pl  = (PolicyLevel)Activator.CreateInstance(typeof(PolicyLevel), true);
            NamedPermissionSet nps = new NamedPermissionSet("test");

            pl.AddNamedPermissionSet(nps);
            nps = pl.ChangeNamedPermissionSet("test", new PermissionSet(new Permissions.PermissionState()));
            PolicyLevel.CreateAppDomainLevel();
            nps = pl.GetNamedPermissionSet("test");
            pl.Recover();
            NamedPermissionSet nps2 = pl.RemoveNamedPermissionSet(nps);

            nps2 = pl.RemoveNamedPermissionSet("test");
            pl.Reset();
            Evidence        evidence = new Evidence();
            PolicyStatement ps       = pl.Resolve(evidence);
            CodeGroup       cg       = pl.ResolveMatchingCodeGroups(evidence);
            SecurityElement se       = new SecurityElement("");

            pl.FromXml(se);
            se = pl.ToXml();
        }
Esempio n. 11
0
        public static void PolicyLevelCallMethods()
        {
            PolicyLevel        pl  = (PolicyLevel)FormatterServices.GetUninitializedObject(typeof(PolicyLevel));
            NamedPermissionSet nps = new NamedPermissionSet("test");

            pl.AddNamedPermissionSet(nps);
            nps = pl.ChangeNamedPermissionSet("test", new PermissionSet(new Permissions.PermissionState()));
#pragma warning disable 618
            PolicyLevel.CreateAppDomainLevel();
#pragma warning restore 618
            nps = pl.GetNamedPermissionSet("test");
            pl.Recover();
            NamedPermissionSet nps2 = pl.RemoveNamedPermissionSet(nps);
            nps2 = pl.RemoveNamedPermissionSet("test");
            pl.Reset();
            Evidence        evidence = new Evidence();
            PolicyStatement ps       = pl.Resolve(evidence);
            CodeGroup       cg       = pl.ResolveMatchingCodeGroups(evidence);
            SecurityElement se       = new SecurityElement("");
            pl.FromXml(se);
            se = pl.ToXml();
        }
Esempio n. 12
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();
            }
        }
Esempio n. 13
0
        private static PermissionSet /*!*/ CreatePermissionSet()
        {
#if CLR2
            string        name            = "Internet";
            bool          foundName       = false;
            PermissionSet setIntersection = new PermissionSet(PermissionState.Unrestricted);

            // iterate over each policy level
            IEnumerator e = SecurityManager.PolicyHierarchy();
            while (e.MoveNext())
            {
                PolicyLevel   level    = (PolicyLevel)e.Current;
                PermissionSet levelSet = level.GetNamedPermissionSet(name);
                if (levelSet != null)
                {
                    foundName       = true;
                    setIntersection = setIntersection.Intersect(levelSet);
                }
            }

            if (setIntersection == null || !foundName)
            {
                setIntersection = new PermissionSet(PermissionState.None);
            }
            else
            {
                setIntersection = new NamedPermissionSet(name, setIntersection);
            }

            return(setIntersection);
#else
            // this functionality is not available on Mono (AddHostEvidence is undefined), use dynamic to resolve it at runtime
            dynamic e = new Evidence();
            e.AddHostEvidence(new Zone(SecurityZone.Internet));
            return(SecurityManager.GetStandardSandbox((Evidence)e));
#endif
        }
Esempio n. 14
0
        //-----------------------------------------------------------------------------------------------
        // private methods
        //-----------------------------------------------------------------------------------------------

        /// <summary>
        /// Written by Abhishek Kumar on March 05, 2007
        /// purpose: to initiate the central Application Domain that
        /// all Grid Threads will be run on.
        ///
        /// Police and permissions will also be set.
        /// ADV: a crash in this App Domain(because of poor code in GThread)
        /// does not affect eduGRID's Framework i.e. the Alchemi executor is maintained steady even in error
        ///
        /// initially Alchemi created separate app domains for each Gthread it received.
        /// now, instead, we create 1 appdomain and run all gthreads on it
        /// the Bot Logic resides in this app domain.
        /// (this saves the overhead of initializing bot logic for every Gthread (or every query))
        /// </summary>
        private void initialize_GridThreadExecutor()
        {
            if (GridThreadExecutor == null)
            {
                string         appDir = GetApplicationDirectory(_CurTi.ApplicationId);
                AppDomainSetup info   = new AppDomainSetup();
                info.PrivateBinPath         = appDir;
                GridThreadApplicationDomain = AppDomain.CreateDomain("Central_AppDomain", null, info);

                // ***
                // http://www.dotnetthis.com/Articles/DynamicSandboxing.htm
                PolicyLevel            domainPolicy = PolicyLevel.CreateAppDomainLevel();
                AllMembershipCondition allCodeMC    = new AllMembershipCondition();
                // TODO: 'FullTrust' in the following line needs to be replaced with something like 'AlchemiGridThread'
                //        This permission set needs to be defined and set automatically as part of the installation.
                PermissionSet   internetPermissionSet   = domainPolicy.GetNamedPermissionSet("FullTrust");
                PolicyStatement internetPolicyStatement = new PolicyStatement(internetPermissionSet);
                CodeGroup       allCodeInternetCG       = new UnionCodeGroup(allCodeMC, internetPolicyStatement);
                domainPolicy.RootCodeGroup = allCodeInternetCG;
                GridThreadApplicationDomain.SetAppDomainPolicy(domainPolicy);

                GridThreadExecutor = (AppDomainExecutor)GridThreadApplicationDomain.CreateInstanceFromAndUnwrap(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Alchemi.Executor.dll"), "Alchemi.Executor.AppDomainExecutor");
            }

            if (!GridThreadExecutor.Initialized)
            {
                try
                {
                    GridThreadExecutor.initialize();
                }
                catch (Exception ex)
                {
                    throw new Exception("Error during initialization of GridThreadExecutor");
                }
            }
        }
        }// FindCurrentPermissionSet

        internal static int FindCurrentPermissionSet(Evidence ev, PermissionSet pSet)
        {
            // Ok, now let's see if the permission set that is currently granted matches
            // either Full Trust, Internet, Intranet, or none.

            if (pSet.IsEmpty())
            {
                return(PermissionSetType.NONE);
            }

            if (pSet.IsUnrestricted())
            {
                return(PermissionSetType.FULLTRUST);
            }

            // Let's grab the internet and intranet permission sets....
            PolicyLevel   pl         = GetPolicyLevelFromType(PolicyLevelType.Enterprise);
            PermissionSet psInternet = pl.GetNamedPermissionSet("Internet");
            PermissionSet psIntranet = pl.GetNamedPermissionSet("LocalIntranet");

            // In addition, the internet and intranet permission sets get additional
            // permissions that are normally provided by custom codegroups. We'll
            // create those codegroups and get the permissions of of those

            // Mess with the custom codegroups
            FileCodeGroup fcg = new FileCodeGroup(new AllMembershipCondition(), FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery);
            NetCodeGroup  ncg = new NetCodeGroup(new AllMembershipCondition());

            // The intranet permission set gets unioned with each of these...
            PermissionSet psss = fcg.Resolve(ev).PermissionSet;

            psIntranet = psIntranet.Union(psss);
            psIntranet = psIntranet.Union(ncg.Resolve(ev).PermissionSet);
            // The internet permission set just gets the net codegroup
            psInternet = psInternet.Union(ncg.Resolve(ev).PermissionSet);

            int nPermissionSet = PermissionSetType.UNKNOWN;

            // These 'IsSubsetOf' will throw exceptions if there are non-identical
            // regular expressions.

            try
            {
                if (psIntranet != null && pSet.IsSubsetOf(psIntranet) && psIntranet.IsSubsetOf(pSet))
                {
                    nPermissionSet = PermissionSetType.INTRANET;
                }
            }
            catch (Exception)
            {
            }

            // See if we should keep looking
            if (nPermissionSet == PermissionSetType.UNKNOWN)
            {
                try
                {
                    // See if this is a Internet policy level
                    if (psInternet != null && pSet.IsSubsetOf(psInternet) && psInternet.IsSubsetOf(pSet))
                    {
                        nPermissionSet = PermissionSetType.INTERNET;
                    }
                }
                catch (Exception)
                {
                }
            }
            return(nPermissionSet);
        }// FindCurrentPermissionSet
Esempio n. 16
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;
        }
    }
Esempio n. 17
0
 public void GetNamedPermissionSet_Null()
 {
     PolicyLevel        pl  = Load(minimal, PolicyLevelType.Machine);
     NamedPermissionSet nps = pl.GetNamedPermissionSet(null);
 }
Esempio n. 18
0
        // Implement the ISecurityPolicyEncodable interface.
        public void FromXml(SecurityElement et, PolicyLevel level)
        {
            if (et == null)
            {
                throw new ArgumentNullException("et");
            }
            if (et.Tag != "PolicyStatement")
            {
                throw new ArgumentException
                          (_("Security_PolicyName"));
            }
            if (et.Attribute("version") != "1")
            {
                throw new ArgumentException
                          (_("Security_PolicyVersion"));
            }
            String value = et.Attribute("Attributes");

            if (value != null)
            {
                attributes = (PolicyStatementAttribute)
                             Enum.Parse(typeof(PolicyStatementAttribute), value);
            }
            else
            {
                attributes = PolicyStatementAttribute.Nothing;
            }
            permSet = null;
            if (level != null)
            {
                String name = et.Attribute("PermissionSetName");
                if (name != null)
                {
                    permSet = level.GetNamedPermissionSet(value);
                    if (permSet == null)
                    {
                        permSet = new PermissionSet(PermissionState.None);
                    }
                }
            }
            if (permSet == null)
            {
                SecurityElement child;
                child = et.SearchForChildByTag("PermissionSet");
                if (child != null)
                {
                    String permClass;
                    permClass = child.Attribute("class");
                    if (permClass != null &&
                        permClass.IndexOf("NamedPermissionSet") != -1)
                    {
                        permSet = new NamedPermissionSet
                                      ("DefaultName", PermissionState.None);
                    }
                    else
                    {
                        permSet = new PermissionSet(PermissionState.None);
                    }
                    try
                    {
                        permSet.FromXml(child);
                    }
                    catch (Exception)
                    {
                        // Ignore errors during set loading.
                    }
                }
            }
            if (permSet == null)
            {
                permSet = new PermissionSet(PermissionState.None);
            }
        }
Esempio n. 19
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);
        }
	// Implement the ISecurityPolicyEncodable interface.
	public void FromXml(SecurityElement et, PolicyLevel level)
			{
				if(et == null)
				{
					throw new ArgumentNullException("et");
				}
				if(et.Tag != "PolicyStatement")
				{
					throw new ArgumentException
						(_("Security_PolicyName"));
				}
				if(et.Attribute("version") != "1")
				{
					throw new ArgumentException
						(_("Security_PolicyVersion"));
				}
				String value = et.Attribute("Attributes");
				if(value != null)
				{
					attributes = (PolicyStatementAttribute)
						Enum.Parse(typeof(PolicyStatementAttribute), value);
				}
				else
				{
					attributes = PolicyStatementAttribute.Nothing;
				}
				permSet = null;
				if(level != null)
				{
					String name = et.Attribute("PermissionSetName");
					if(name != null)
					{
						permSet = level.GetNamedPermissionSet(value);
						if(permSet == null)
						{
							permSet = new PermissionSet(PermissionState.None);
						}
					}
				}
				if(permSet == null)
				{
					SecurityElement child;
					child = et.SearchForChildByTag("PermissionSet");
					if(child != null)
					{
						String permClass;
						permClass = child.Attribute("class");
						if(permClass != null &&
						   permClass.IndexOf("NamedPermissionSet") != -1)
						{
							permSet = new NamedPermissionSet
								("DefaultName", PermissionState.None);
						}
						else
						{
							permSet = new PermissionSet(PermissionState.None);
						}
						try
						{
							permSet.FromXml(child);
						}
						catch(Exception)
						{
							// Ignore errors during set loading.
						}
					}
				}
				if(permSet == null)
				{
					permSet = new PermissionSet(PermissionState.None);
				}
			}
	public SecurityElement ToXml(PolicyLevel level)
			{
				SecurityElement element;
				element = new SecurityElement("PolicyStatement");
				element.AddAttribute
					("class",
					 SecurityElement.Escape(typeof(PolicyStatement).
					 						AssemblyQualifiedName));
				element.AddAttribute("version", "1");
				if(attributes != PolicyStatementAttribute.Nothing)
				{
					element.AddAttribute("Attributes", attributes.ToString());
				}
				if(permSet != null)
				{
					NamedPermissionSet namedSet;
					namedSet = (permSet as NamedPermissionSet);
					if(namedSet != null)
					{
						if(level != null &&
						   level.GetNamedPermissionSet(namedSet.Name) != null)
						{
							element.AddAttribute
								("PermissionSetName",
								 SecurityElement.Escape(namedSet.Name));
						}
						else
						{
							element.AddChild(permSet.ToXml());
						}
					}
					else
					{
						element.AddChild(permSet.ToXml());
					}
				}
				return element;
			}
Esempio n. 23
0
        /// <summary>
        /// Creates a new instance providing default "FullTrust", "Nothing", "MediumTrust" and "LowTrust" permissionsets
        /// </summary>
        /// <param name="allowUnmanagedCode">NCover requires unmangaged code permissions, set this flag <c>true</c> in this case.</param>
        public SecurityTemplate(bool allowUnmanagedCode)
        {
            PolicyLevel pLevel = PolicyLevel.CreateAppDomainLevel();

            // NOTHING permissionset
            if (null == pLevel.GetNamedPermissionSet(PERMISSIONSET_NOTHING))
            {
                NamedPermissionSet noPermissionSet = new NamedPermissionSet(PERMISSIONSET_NOTHING, PermissionState.None);
                noPermissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.NoFlags));
                pLevel.AddNamedPermissionSet(noPermissionSet);
            }

            // FULLTRUST permissionset
            if (null == pLevel.GetNamedPermissionSet(PERMISSIONSET_FULLTRUST))
            {
                NamedPermissionSet fulltrustPermissionSet = new NamedPermissionSet(PERMISSIONSET_FULLTRUST, PermissionState.Unrestricted);
                pLevel.AddNamedPermissionSet(fulltrustPermissionSet);
            }
            // MEDIUMTRUST permissionset (corresponds to ASP.Net permission set in web_mediumtrust.config)
            NamedPermissionSet mediumTrustPermissionSet = new NamedPermissionSet(PERMISSIONSET_MEDIUMTRUST, PermissionState.None);

            mediumTrustPermissionSet.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Medium));
            mediumTrustPermissionSet.AddPermission(new DnsPermission(PermissionState.Unrestricted));
            mediumTrustPermissionSet.AddPermission(new EnvironmentPermission(EnvironmentPermissionAccess.Read,
                                                                             "TEMP;TMP;USERNAME;OS;COMPUTERNAME"));
            mediumTrustPermissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.AllAccess,
                                                                        AppDomain.CurrentDomain.BaseDirectory));
            IsolatedStorageFilePermission isolatedStorageFilePermission = new IsolatedStorageFilePermission(PermissionState.None);

            isolatedStorageFilePermission.UsageAllowed = IsolatedStorageContainment.AssemblyIsolationByUser;
            isolatedStorageFilePermission.UserQuota    = 9223372036854775807;
            mediumTrustPermissionSet.AddPermission(isolatedStorageFilePermission);
            mediumTrustPermissionSet.AddPermission(new PrintingPermission(PrintingPermissionLevel.DefaultPrinting));
            SecurityPermissionFlag securityPermissionFlag = SecurityPermissionFlag.Assertion | SecurityPermissionFlag.Execution |
                                                            SecurityPermissionFlag.ControlThread | SecurityPermissionFlag.ControlPrincipal |
                                                            SecurityPermissionFlag.RemotingConfiguration;

            if (allowUnmanagedCode)
            {
                securityPermissionFlag |= SecurityPermissionFlag.UnmanagedCode;
            }
            mediumTrustPermissionSet.AddPermission(new SecurityPermission(securityPermissionFlag));
            mediumTrustPermissionSet.AddPermission(new System.Net.Mail.SmtpPermission(System.Net.Mail.SmtpAccess.Connect));
            mediumTrustPermissionSet.AddPermission(new SqlClientPermission(PermissionState.Unrestricted));
            mediumTrustPermissionSet.AddPermission(new WebPermission());
            pLevel.AddNamedPermissionSet(mediumTrustPermissionSet);

            // LOWTRUST permissionset (corresponds to ASP.Net permission set in web_mediumtrust.config)
            NamedPermissionSet lowTrustPermissionSet = new NamedPermissionSet(PERMISSIONSET_LOWTRUST, PermissionState.None);

            lowTrustPermissionSet.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Low));
            lowTrustPermissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery,
                                                                     AppDomain.CurrentDomain.BaseDirectory));
            IsolatedStorageFilePermission isolatedStorageFilePermissionLow = new IsolatedStorageFilePermission(PermissionState.None);

            isolatedStorageFilePermissionLow.UsageAllowed = IsolatedStorageContainment.AssemblyIsolationByUser;
            isolatedStorageFilePermissionLow.UserQuota    = 1048576;
            lowTrustPermissionSet.AddPermission(isolatedStorageFilePermissionLow);
            SecurityPermissionFlag securityPermissionFlagLow = SecurityPermissionFlag.Execution;

            if (allowUnmanagedCode)
            {
                securityPermissionFlagLow |= SecurityPermissionFlag.UnmanagedCode;
            }
            lowTrustPermissionSet.AddPermission(new SecurityPermission(securityPermissionFlagLow));
            pLevel.AddNamedPermissionSet(lowTrustPermissionSet);

//            UnionCodeGroup rootCodeGroup = new UnionCodeGroup(new AllMembershipCondition(), new PolicyStatement(noPermissionSet, PolicyStatementAttribute.Nothing));
//            pLevel.RootCodeGroup = rootCodeGroup;
            _domainPolicy = pLevel;
        }
        }// DoesCGHaveNetCodegroup

        internal static void PrepCodeGroupTree(CodeGroup root, PolicyLevel plSrc, PolicyLevel plDest)
        {
            SuperCodeGroupArrayList scal;

            ListifyCodeGroup(root, null, out scal);
            for (int i = 0; i < scal.Count; i++)
            {
                // make sure this codegroup name is not already used
                int    nCounter = 1;
                String sBase    = scal[i].cg.Name;
                while (Security.isCodeGroupNameUsed(plDest.RootCodeGroup, scal[i].cg.Name) ||
                       Security.isCodeGroupNameUsed(root, scal[i].cg))
                {
                    if (nCounter == 1)
                    {
                        scal[i].cg.Name = String.Format(CResourceStore.GetString("CSingleCodeGroup:NewDupCodegroup"), sBase);
                    }
                    else
                    {
                        scal[i].cg.Name = String.Format(CResourceStore.GetString("CSingleCodeGroup:NumNewDupCodegroup"), nCounter.ToString(), sBase);
                    }

                    nCounter++;
                }

                // Now check to see if we have its permission set in the policy
                if (plDest != plSrc)
                {
                    bool fAddPermissionSet = false;

                    if (!Security.isPermissionSetNameUsed(plDest, scal[i].cg.PermissionSetName))
                    {
                        // We're copying a codegroup from a different policy level to a new
                        // policy level. This new policy level does not contain the permission
                        // set that our codegroup uses... thus, we must also copy over a new
                        // permission set as well
                        fAddPermissionSet = true;
                    }
                    else
                    {
                        // The permission set name is used. Let's see if it's what we want
                        PermissionSet psSrc  = plSrc.GetNamedPermissionSet(scal[i].cg.PermissionSetName);
                        PermissionSet psDest = plDest.GetNamedPermissionSet(scal[i].cg.PermissionSetName);
                        // See if these permission sets are equal
                        try
                        {
                            if (!(psSrc.IsSubsetOf(psDest) && psDest.IsSubsetOf(psSrc)))
                            {
                                // We're copying a codegroup from a different policy level to a new
                                // policy level. This new policy level contains a permission
                                // set with the same name as the permission set the our codegroup uses...
                                // However, the permission set that the codegroup uses has different permissions
                                // than what the permission set that the new policy level has... therefore, we
                                // must copy over a new permission set.
                                // The copied permission set will have a different name (since we can't have two
                                // permission sets with the exact same name). We'll have to remember
                                // to change the name of the permission set that the codegroup uses.
                                fAddPermissionSet = true;
                            }
                        }
                        catch (Exception)
                        {
                            // When we're doing these IsSubSetOf things, RegEx classes will throw
                            // exceptions if things aren't quite right. If that's the case, then
                            // we want to add the permission set.
                            fAddPermissionSet = true;
                        }
                    }

                    if (fAddPermissionSet)
                    {
                        // See if this codegroup has a policy (i.e. a permission set)
                        if (scal[i].cg.PolicyStatement != null)
                        {
                            // We need to add this permission set from that policy level
                            String sPermissionSetName = AddPermissionSet(plDest, plSrc.GetNamedPermissionSet(scal[i].cg.PermissionSetName)).DisplayName;
                            // It's possible that we added a permission set and the name of our permission
                            // set was already used in the security policy. In that case, the permission set
                            // we tried to add was renamed. We should updated the codegroup to look at the
                            // permission set's new name
                            PermissionSet   ps   = plDest.GetNamedPermissionSet(sPermissionSetName);
                            PolicyStatement pols = scal[i].cg.PolicyStatement;
                            pols.PermissionSet         = ps;
                            scal[i].cg.PolicyStatement = pols;
                        }
                    }
                }

                if (i != 0)
                {
                    // Add the modified codegroup back into the tree
                    Security.RefreshCodeGroup(scal[scal[i].nParent].cg, scal[i].cg, scal[i].ChildNum);
                }
            }
        }// PrepCodeGroupTree
        }// didMachinePolicyChange

        protected override int WizFinish()
        {
            // This is the main things that the wizard needs to do.
            // If mucking with the machine level
            //
            // 1. Apply appropriate settings to the security zone codegroups.
            //
            // If mucking with the user level
            //
            // 1. Change the user policylevel's root codegroup's permission set to Nothing
            // 2. Apply appropriate settings to the security zone codegroups
            // 3. Copy the entire machine policy into a child codegroup in the user policy
            // 4. Skip the top level of the copied policy looking for zone codegroups. Set
            //    their permission set to nothing, and remove child file and net codegroups.
            // 5. Walk through the entire copied policy and remove any exclusive codegroups


            // We have some different behavior depending on what type of policy we're after
            String sPolicyLevel = IsHomeUser?"Machine":"User";

            PolicyLevel pl = Security.GetPolicyLevelFromLabel(sPolicyLevel);

            SecurityZone[] sz = new SecurityZone[] {
                SecurityZone.MyComputer,
                SecurityZone.Intranet,
                SecurityZone.Internet,
                SecurityZone.Trusted,
                SecurityZone.Untrusted
            };
            m_alNewCodeGroups.Clear();

            for (int i = 0; i < 5; i++)
            {
                // Only do this if we know how to assign a permission set
                if (Page2.SecurityLevels[i] != PermissionSetType.UNKNOWN)
                {
                    // Find the Codegroup with the appropriate Membership Condition
                    CodeGroup cgParent = null;
                    CodeGroup cg       = GetCGWithMembershipCondition(pl.RootCodeGroup, sz[i], out cgParent);

                    // Remove this codegroup from the heirarchy
                    if (cg != null)
                    {
                        if (cgParent == null)
                        {
                            throw new Exception("I should have a parent");
                        }
                        cgParent.RemoveChild(cg);
                    }

                    // We have to create this Codegroup
                    if (cg == null)
                    {
                        ZoneMembershipCondition zmc = new ZoneMembershipCondition(sz[i]);
                        cg = new UnionCodeGroup(zmc, new PolicyStatement(new PermissionSet(PermissionState.None)));
                        // Add a name and description
                        cg.Name = GetCodegroupName(sz[i]);

                        m_alNewCodeGroups.Add(cg);
                        m_pl     = pl;
                        cgParent = pl.RootCodeGroup;
                    }
                    // If was an internet or intranet codegroup, we'll need to remove child codegroups of type
                    // NetCodeGroup or FileCodeGroup
                    if (cg.PermissionSetName != null && (cg.PermissionSetName.Equals("Internet") || cg.PermissionSetName.Equals("LocalIntranet")))
                    {
                        IEnumerator enumCodeGroups = cg.Children.GetEnumerator();
                        while (enumCodeGroups.MoveNext())
                        {
                            CodeGroup group = (CodeGroup)enumCodeGroups.Current;
                            if (group is NetCodeGroup || group is FileCodeGroup)
                            {
                                cg.RemoveChild(group);
                            }
                        }
                    }

                    // Now give this codegroup the appropriate permission set
                    PolicyStatement ps = cg.PolicyStatement;
                    ps.PermissionSet = GetPermissionSetNameFromSecurityLevel(pl, Page2.SecurityLevels[i]);

                    // Put in the helper codegroups if necessary
                    if (Page2.SecurityLevels[i] == PermissionSetType.INTRANET)
                    {
                        if (!DoesCGHaveCodegroup(cg, typeof(NetCodeGroup)))
                        {
                            CodeGroup cgChild = new NetCodeGroup(new AllMembershipCondition());
                            cgChild.Name        = Security.FindAGoodCodeGroupName(pl, "NetCodeGroup_");
                            cgChild.Description = CResourceStore.GetString("GeneratedCodegroup");

                            cg.AddChild(cgChild);
                        }
                        if (!DoesCGHaveCodegroup(cg, typeof(FileCodeGroup)))
                        {
                            CodeGroup cgChild = new FileCodeGroup(new AllMembershipCondition(), FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery);
                            cgChild.Name        = Security.FindAGoodCodeGroupName(pl, "FileCodeGroup_");
                            cgChild.Description = CResourceStore.GetString("GeneratedCodegroup");

                            cg.AddChild(cgChild);
                        }
                    }
                    else if (Page2.SecurityLevels[i] == PermissionSetType.INTERNET)
                    {
                        if (!DoesCGHaveCodegroup(cg, typeof(NetCodeGroup)))
                        {
                            CodeGroup cgChild = new NetCodeGroup(new AllMembershipCondition());
                            cgChild.Name        = Security.FindAGoodCodeGroupName(pl, "NetCodeGroup_");
                            cgChild.Description = CResourceStore.GetString("GeneratedCodegroup");

                            cg.AddChild(cgChild);
                        }
                    }

                    cg.PolicyStatement = ps;
                    // Now let's build the code group description
                    String sPermissionSetDes = "";
                    if (ps.PermissionSet is NamedPermissionSet)
                    {
                        sPermissionSetDes += ((NamedPermissionSet)ps.PermissionSet).Description;
                    }


                    cg.Description = String.Format(CResourceStore.GetString("CSecurityAdjustmentWizard:CodeGroupDescription"),
                                                   cg.PermissionSetName,
                                                   GetCodegroupName(sz[i]),
                                                   sPermissionSetDes);
                    // Now add this child back in
                    cgParent.AddChild(cg);
                }
            }

            // Check to see if this is for the user.
            if (!IsHomeUser)
            {
                // Let's start on our list....
                PolicyLevel plUser = Security.GetPolicyLevelFromLabel("User");
                // Change the root codegroup's permission set to nothing
                CodeGroup       cgRoot = plUser.RootCodeGroup;
                PolicyStatement ps     = cgRoot.PolicyStatement;
                ps.PermissionSet       = plUser.GetNamedPermissionSet("Nothing");
                cgRoot.PolicyStatement = ps;

                // Now copy the entire machine level's policy into a child codegroup
                // of the user policy
                PolicyLevel plMachine = Security.GetPolicyLevelFromLabel("Machine");
                CodeGroup   cgMachine = plMachine.RootCodeGroup.Copy();
                // Change the codegroup's name to something more interesting...
                cgMachine.Name        = "Wizard_Machine_Policy";
                cgMachine.Description = CResourceStore.GetString("CSecurityAdjustmentWizard:CopiedMachinePolicyDes");
                // Now skim through the top level looking for Zone codegroups, set
                // their permission sets to nothing, and delete any child net and file
                // codegroups
                IEnumerator enumCodeGroups = cgMachine.Children.GetEnumerator();
                while (enumCodeGroups.MoveNext())
                {
                    CodeGroup zoneGroup = (CodeGroup)enumCodeGroups.Current;

                    if (zoneGroup.MembershipCondition is ZoneMembershipCondition)
                    {
                        // Ok, we need to change this codegroup
                        cgMachine.RemoveChild(zoneGroup);
                        PolicyStatement zoneps = zoneGroup.PolicyStatement;
                        zoneps.PermissionSet      = plUser.GetNamedPermissionSet("Nothing");
                        zoneGroup.PolicyStatement = zoneps;
                        // Now run through its children looking for a file or net codegroup
                        IEnumerator enumChildCodeGroups = zoneGroup.Children.GetEnumerator();
                        while (enumChildCodeGroups.MoveNext())
                        {
                            CodeGroup zoneChildGroup = (CodeGroup)enumChildCodeGroups.Current;
                            if (zoneChildGroup is NetCodeGroup || zoneChildGroup is FileCodeGroup)
                            {
                                zoneGroup.RemoveChild(zoneChildGroup);
                            }
                        }
                        cgMachine.AddChild(zoneGroup);
                    }
                }

                // Now run through the tree and remove any exclusive code groups
                // We're best to do this recursively....
                if ((cgMachine.PolicyStatement.Attributes & PolicyStatementAttribute.Exclusive) == PolicyStatementAttribute.Exclusive)
                {
                    // Remove the exclusive bit
                    PolicyStatement psMachine = cgMachine.PolicyStatement;
                    psMachine.Attributes      = psMachine.Attributes & ~PolicyStatementAttribute.Exclusive;
                    cgMachine.PolicyStatement = psMachine;
                }
                Security.RemoveExclusiveCodeGroups(cgMachine);


                // Now run through the user policy looking for codegroups named
                // "Wizard_Machine_Policy" and delete those as well.
                enumCodeGroups = cgRoot.Children.GetEnumerator();
                while (enumCodeGroups.MoveNext())
                {
                    CodeGroup group = (CodeGroup)enumCodeGroups.Current;
                    if (group.Name.Equals("Wizard_Machine_Policy"))
                    {
                        cgRoot.RemoveChild(group);
                    }
                }

                // Add finally this to the root codegroup of the user policy

                Security.PrepCodeGroupTree(cgMachine, plMachine, plUser);
                cgRoot.AddChild(cgMachine);
                plUser.RootCodeGroup = cgRoot;
            }

            m_fWizardFinished = true;

            return(0);
        }// WizFinish