Exemplo n.º 1
0
        /// <summary>
        ///     Generate the Internet permission set, optionally extending it with same site permissions
        /// </summary>
        private static PermissionSet GetInternetPermissionSet(Url sourceUrl)
        {
            PermissionSet internet = MachinePolicyLevel.GetNamedPermissionSet("Internet");

            // If we have a source URL, try to generate same-site web permissions to add to the internet set
            if (sourceUrl != null)
            {
                Evidence evidence = new Evidence();
                evidence.AddHostEvidence(new Zone(SecurityZone.Internet));
                evidence.AddHostEvidence(sourceUrl);

                PolicyStatement webPolicy =
                    new NetCodeGroup(new AllMembershipCondition()).Resolve(evidence);
                if (webPolicy != null)
                {
                    internet = internet.Union(webPolicy.PermissionSet);
                }
            }

            // If WPF is available on the machine, then extend the permission set with some additional WPF
            // permissions as well.
            internet = internet.Union(WpfPermissionSet);

            return(internet);
        }
Exemplo n.º 2
0
        /// <summary>
        ///     Generate the LocalIntranet permission set, optionally extending it with same site permissions
        /// </summary>
        private static PermissionSet GetLocalIntranetPermissionSet(Url sourceUrl)
        {
            PermissionSet localIntranet = MachinePolicyLevel.GetNamedPermissionSet("LocalIntranet");

            // If we have a source URL, try to generate same-site web and file permissions to add to the
            // local intranet set
            if (sourceUrl != null)
            {
                Evidence evidence = new Evidence();
                evidence.AddHostEvidence(new Zone(SecurityZone.Intranet));
                evidence.AddHostEvidence(sourceUrl);

                PolicyStatement webPolicy =
                    new NetCodeGroup(new AllMembershipCondition()).Resolve(evidence);
                if (webPolicy != null)
                {
                    localIntranet = localIntranet.Union(webPolicy.PermissionSet);
                }

                PolicyStatement filePolicy =
                    new FileCodeGroup(new AllMembershipCondition(), FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery).Resolve(evidence);
                if (filePolicy != null)
                {
                    localIntranet = localIntranet.Union(filePolicy.PermissionSet);
                }
            }

            // If WPF is available on the machine, then extend the permission set with some additional WPF
            // permissions as well.
            localIntranet = localIntranet.Union(WpfPermissionSet);

            return(localIntranet);
        }
        public void CopyWithChildren()
        {
            NetCodeGroup cgChild = new NetCodeGroup(new AllMembershipCondition());
            NetCodeGroup cg      = new NetCodeGroup(new AllMembershipCondition());

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

            Assert.AreEqual(cg.Children.Count, cg2.Children.Count, "Children");
            Assert.AreEqual(cg.ToXml().ToString(), cg2.ToXml().ToString(), "ToXml");
        }
Exemplo n.º 4
0
        public void Constructor()
        {
            NetCodeGroup cg = new NetCodeGroup(new AllMembershipCondition());

            Assert.IsNotNull(cg.MembershipCondition, "MembershipCondition");
            Assert.IsNull(cg.PolicyStatement, "PolicyStatement");
            // documented as always null
            Assert.IsNull(cg.AttributeString, "AttributeString");
            // seems it's easier to change code than to change code ;)
            Assert.AreEqual("Same site Web", cg.PermissionSetName, "PermissionSetName");
        }
        public void Copy()
        {
            NetCodeGroup cg  = new NetCodeGroup(new AllMembershipCondition());
            NetCodeGroup cg2 = (NetCodeGroup)cg.Copy();

            Assert.AreEqual(cg.AttributeString, cg2.AttributeString, "AttributeString");
            Assert.AreEqual(cg.Children.Count, cg2.Children.Count, "Children");
            Assert.AreEqual(cg.Description, cg2.Description, "Description");
            Assert.AreEqual(cg.MergeLogic, cg2.MergeLogic, "MergeLogic");
            Assert.AreEqual(cg.Name, cg2.Name, "Name");
            Assert.AreEqual(cg.PermissionSetName, cg2.PermissionSetName, "PermissionSetName");
            Assert.AreEqual(cg.ToXml().ToString(), cg2.ToXml().ToString(), "ToXml");
        }
Exemplo n.º 6
0
 // <snippet8>
 public static void DisplayConnectionAccessRules(NetCodeGroup group)
 {
     System.Collections.DictionaryEntry[] rules = group.GetConnectAccessRules();
     foreach (System.Collections.DictionaryEntry o in rules)
     {
         string key = o.Key as string;
         CodeConnectAccess[] values = (CodeConnectAccess[])o.Value;
         Console.WriteLine("Origin scheme: {0}", key);
         foreach (CodeConnectAccess c in values)
         {
             Console.WriteLine("Scheme {0} Port: {1}", c.Scheme, c.Port);
         }
         Console.WriteLine("__________________________");
     }
 }
Exemplo n.º 7
0
// </snippet5>
// <snippet3>
    public static void SetNetCodeGroupAccess()
    {
        const string userPolicyLevel = "User";
        // Locate the User policy level.
        PolicyLevel level = null;

        System.Collections.IEnumerator ph =
            System.Security.SecurityManager.PolicyHierarchy();
        while (ph.MoveNext())
        {
            level = (PolicyLevel)ph.Current;
            if (level.Label == userPolicyLevel)
            {
                break;
            }
        }
        if (level.Label != userPolicyLevel)
        {
            throw new ApplicationException("Could not find User policy level.");
        }
        // <snippet7>

        IMembershipCondition membership =
            new UrlMembershipCondition(@"http://www.contoso.com/*");
        NetCodeGroup codeGroup = new NetCodeGroup(membership);

        // Delete default settings.
        codeGroup.ResetConnectAccess();
        // Create an object that represents access to the FTP scheme and default port.
        CodeConnectAccess a1 = new CodeConnectAccess(Uri.UriSchemeFtp, CodeConnectAccess.DefaultPort);
        // Create an object that represents access to the HTTPS scheme and default port.
        CodeConnectAccess a2 = new CodeConnectAccess(Uri.UriSchemeHttps, CodeConnectAccess.DefaultPort);
        // Create an object that represents access to the origin scheme and port.
        CodeConnectAccess a3 = CodeConnectAccess.CreateOriginSchemeAccess(CodeConnectAccess.OriginPort);

        // Add connection access objects to the NetCodeGroup object.
        codeGroup.AddConnectAccess(Uri.UriSchemeHttp, a1);
        codeGroup.AddConnectAccess(Uri.UriSchemeHttp, a2);
        codeGroup.AddConnectAccess(Uri.UriSchemeHttp, a3);
        // </snippet7>
        // Provide name and description information for caspol.exe tool.
        codeGroup.Name        = "ContosoHttpCodeGroup";
        codeGroup.Description = "Code originating from contoso.com can connect back using the FTP or HTTPS.";
        // Add the code group to the User policy's root node.
        level.RootCodeGroup.AddChild(codeGroup);
        // Save the changes to the policy level.
        System.Security.SecurityManager.SavePolicy();
    }
        public void ToFromXmlRoundtrip()
        {
            NetCodeGroup cg = new NetCodeGroup(new AllMembershipCondition());

            cg.Name        = "SomeName";
            cg.Description = "Some Description";
            Assert.IsTrue(cg.Equals(cg), "Equals (itself)");
            SecurityElement se = cg.ToXml();

            NetCodeGroup cg2 = new NetCodeGroup(new AllMembershipCondition());

            cg2.Name        = "SomeOtherName";
            cg2.Description = "Some Other Description";
            Assert.IsTrue(!cg.Equals(cg2), "Equals (another)");

            cg2.FromXml(se);
            Assert.IsTrue(cg.Equals(cg2), "Equals (FromXml)");
        }
Exemplo n.º 9
0
        public static void NetCodeGroupCallMethods()
        {
            NetCodeGroup ncg        = new NetCodeGroup(new GacMembershipCondition());
            string       teststring = NetCodeGroup.AbsentOriginScheme;

            teststring = NetCodeGroup.AnyOtherOriginScheme;
            ncg.AddConnectAccess("test", new CodeConnectAccess("test", 0));
            CodeGroup cg     = ncg.Copy();
            bool      equals = ncg.Equals(new object());

            System.Collections.DictionaryEntry[] de = ncg.GetConnectAccessRules();
            int hash = ncg.GetHashCode();

            ncg.ResetConnectAccess();
            PolicyStatement ps = ncg.Resolve(new Evidence());

            cg = ncg.ResolveMatchingCodeGroups(new Evidence());
        }
Exemplo n.º 10
0
        public static PermissionSet GetStandardSandbox(Evidence evidence)
        {
            if (evidence == null)
            {
                throw new ArgumentNullException("evidence");
            }
            Zone hostEvidence = evidence.GetHostEvidence <Zone>();

            if (hostEvidence == null)
            {
                return(new PermissionSet(PermissionState.None));
            }
            if (hostEvidence.SecurityZone == SecurityZone.MyComputer)
            {
                return(new PermissionSet(PermissionState.Unrestricted));
            }
            if (hostEvidence.SecurityZone == SecurityZone.Intranet)
            {
                PermissionSet   localIntranet = BuiltInPermissionSets.LocalIntranet;
                PolicyStatement statement     = new NetCodeGroup(new AllMembershipCondition()).Resolve(evidence);
                PolicyStatement statement2    = new FileCodeGroup(new AllMembershipCondition(), FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read).Resolve(evidence);
                if (statement != null)
                {
                    localIntranet.InplaceUnion(statement.PermissionSet);
                }
                if (statement2 != null)
                {
                    localIntranet.InplaceUnion(statement2.PermissionSet);
                }
                return(localIntranet);
            }
            if ((hostEvidence.SecurityZone != SecurityZone.Internet) && (hostEvidence.SecurityZone != SecurityZone.Trusted))
            {
                return(new PermissionSet(PermissionState.None));
            }
            PermissionSet   internet   = BuiltInPermissionSets.Internet;
            PolicyStatement statement3 = new NetCodeGroup(new AllMembershipCondition()).Resolve(evidence);

            if (statement3 != null)
            {
                internet.InplaceUnion(statement3.PermissionSet);
            }
            return(internet);
        }
Exemplo n.º 11
0
// </snippet6>

    public static void CreateNetCodeGroup()
    {
        IMembershipCondition membership =
            new UrlMembershipCondition(@"http://www.contoso.com/*");
        NetCodeGroup codeGroup = new NetCodeGroup(membership);

        // Display default settings.
        DisplayConnectionAccessRules(codeGroup);
        // Delete default settings.
        codeGroup.ResetConnectAccess();
        // Create an object that represents access to the ftp scheme and default port.
        CodeConnectAccess a1 = new CodeConnectAccess(Uri.UriSchemeFtp, CodeConnectAccess.DefaultPort);
        // Create an object that represents access to the HTTPS scheme and default port.
        CodeConnectAccess a2 = new CodeConnectAccess(Uri.UriSchemeHttps, CodeConnectAccess.DefaultPort);
        // Create an object that represents access to the origin scheme and port.
        CodeConnectAccess a3 = CodeConnectAccess.CreateOriginSchemeAccess(CodeConnectAccess.OriginPort);

        codeGroup.AddConnectAccess(Uri.UriSchemeHttp, a1);
        codeGroup.AddConnectAccess(Uri.UriSchemeHttp, a2);
        codeGroup.AddConnectAccess(Uri.UriSchemeHttp, a3);
        Console.WriteLine("New NetCodeGroup settings:");
        DisplayConnectionAccessRules(codeGroup);
    }
        }// 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
Exemplo n.º 13
0
        // Get a sandbox permission set that the CLR considers safe to grant an application with the given
        // evidence.  Note that this API is not a policy API, but rather a host helper API so that a host can
        // determine if an application's requested permission set is reasonable.  This is esentially just a
        // hard coded mapping of Zone -> Sandbox and is not configurable in any way.
        public static PermissionSet GetStandardSandbox(Evidence evidence)
        {
            if (evidence == null)
            {
                throw new ArgumentNullException("evidence");
            }
            Contract.EndContractBlock();

            //
            // The top-level switch for grant set is based upon Zone
            //   MyComputer -> FullTrust
            //   Intranet   -> LocalIntranet
            //   Trusted    -> Internet
            //   Internet   -> Internet
            //   All else   -> Nothing
            //
            //   Both the Internet and LocalIntranet zones can have permission set extensions applied to them
            //   if there is Activation.
            //

            Zone zone = evidence.GetHostEvidence <Zone>();

            if (zone == null)
            {
                return(new PermissionSet(PermissionState.None));
            }
#if FEATURE_CAS_POLICY
            else if (zone.SecurityZone == SecurityZone.MyComputer)
            {
                return(new PermissionSet(PermissionState.Unrestricted));
            }
            else if (zone.SecurityZone == SecurityZone.Intranet)
            {
                PermissionSet intranetGrantSet = BuiltInPermissionSets.LocalIntranet;

                // We also need to add in same site web and file IO permission
                PolicyStatement webPolicy =
                    new NetCodeGroup(new AllMembershipCondition()).Resolve(evidence);
                PolicyStatement filePolicy =
                    new FileCodeGroup(new AllMembershipCondition(), FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery).Resolve(evidence);

                if (webPolicy != null)
                {
                    intranetGrantSet.InplaceUnion(webPolicy.PermissionSet);
                }
                if (filePolicy != null)
                {
                    intranetGrantSet.InplaceUnion(filePolicy.PermissionSet);
                }

                return(intranetGrantSet);
            }
            else if (zone.SecurityZone == SecurityZone.Internet ||
                     zone.SecurityZone == SecurityZone.Trusted)
            {
                PermissionSet internetGrantSet = BuiltInPermissionSets.Internet;

                // We also need to add in same site web permission
                PolicyStatement webPolicy =
                    new NetCodeGroup(new AllMembershipCondition()).Resolve(evidence);

                if (webPolicy != null)
                {
                    internetGrantSet.InplaceUnion(webPolicy.PermissionSet);
                }

                return(internetGrantSet);
            }
#endif // FEATURE_CAS_POLICY
            else
            {
                return(new PermissionSet(PermissionState.None));
            }
        }
Exemplo n.º 14
0
        }// TryToCreateFullTrust

        private CodeGroup CreateCodegroup(PermissionSet pSet, bool fHighjackExisting)
        {
            // Now create our codegroup
            // Figure out what membership condition to use
            IMembershipCondition mc = null;
            // If the assembly didn't have a publisher certificate or a strong name,
            // then we must trust it by hash
            int nTrustBy = m_fHasCertOrSName?Page3.HowToTrust:TrustBy.HASH;

            if ((nTrustBy & TrustBy.SNAME) > 0)
            {
                // Let's get the strong name stuff together
                StrongName sn = GetStrongName();
                StrongNamePublicKeyBlob snpkb = sn.PublicKey;
                Version v     = null;
                String  sName = null;
                if ((nTrustBy & TrustBy.SNAMEVER) > 0)
                {
                    v = sn.Version;
                }

                if ((nTrustBy & TrustBy.SNAMENAME) > 0)
                {
                    sName = sn.Name;
                }

                mc = new StrongNameMembershipCondition(snpkb, sName, v);
            }
            else if ((nTrustBy & TrustBy.PUBCERT) > 0)
            {
                // We're using the publisher certificate stuff
                mc = new PublisherMembershipCondition(GetCertificate());
            }
            else // We'll trust by hash
            {
                Hash h = GetHash();
                mc = new HashMembershipCondition(SHA1.Create(), h.SHA1);
            }

            // Figure out the policy level that we should put this in....
            String      sPolicyLevel = Page1.isForHomeUser?"Machine":"User";
            PolicyLevel pl           = Security.GetPolicyLevelFromLabel(sPolicyLevel);

            // See if a codegroup for this already exists... and if it does, we'll just
            // modify that.
            CSingleCodeGroup scg = null;
            CodeGroup        cg  = null;

            if (fHighjackExisting)
            {
                scg = FindExistingCodegroup(pl, mc);

                if (scg != null)
                {
                    cg = scg.MyCodeGroup;

                    // Cool. We were able to find a codegroup to use. We'll
                    // need to strip off all the File and Net child codegroups
                    IEnumerator enumChildCodeGroups = cg.Children.GetEnumerator();
                    while (enumChildCodeGroups.MoveNext())
                    {
                        CodeGroup cgChild = (CodeGroup)enumChildCodeGroups.Current;
                        if (cgChild is NetCodeGroup || cgChild is FileCodeGroup)
                        {
                            // Ok to use CodeGroup.RemoveChild here we want to toast all
                            // File and Net codegroups... we don't care if the security system
                            // gets confused about which are which (if they don't have names)
                            cg.RemoveChild(cgChild);
                        }
                    }
                }
            }

            // Create the codegroup... we're going to make this a level final
            // codegroup, so if policy gets changes such that a lower-level policy
            // level tries to deny permissions to this codegroup it will be unsuccessful.
            PolicyStatement policystatement = new PolicyStatement(pSet, PolicyStatementAttribute.LevelFinal);

            if (cg == null)
            {
                cg = new UnionCodeGroup(mc, policystatement);
                String sCGName = Security.FindAGoodCodeGroupName(pl, "Wizard_");
                cg.Name        = sCGName;
                cg.Description = CResourceStore.GetString("GeneratedCodegroup");
            }
            else
            {
                cg.PolicyStatement = policystatement;
            }


            // If this is a internet or intranet permission set, we also need to add some codegroups
            if (pSet is NamedPermissionSet)
            {
                NamedPermissionSet nps = (NamedPermissionSet)pSet;

                if (nps.Name.Equals("LocalIntranet"))
                {
                    CodeGroup cgChild = new NetCodeGroup(new AllMembershipCondition());
                    cgChild.Name        = Security.FindAGoodCodeGroupName(pl, "NetCodeGroup_");
                    cgChild.Description = CResourceStore.GetString("GeneratedCodegroup");

                    cg.AddChild(cgChild);
                    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 (nps.Name.Equals("Internet"))
                {
                    CodeGroup cgChild = new NetCodeGroup(new AllMembershipCondition());
                    cgChild.Name        = Security.FindAGoodCodeGroupName(pl, "NetCodeGroup_");
                    cgChild.Description = CResourceStore.GetString("GeneratedCodegroup");

                    cg.AddChild(cgChild);
                }
            }


            // Add this codegroup to the root codegroup of the policy
            // If there was already an existing one, just replace that...
            if (scg != null)
            {
                Security.UpdateCodegroup(pl, scg);
            }
            else
            {
                pl.RootCodeGroup.AddChild(cg);
            }

            return(cg);
        }// CreateCodegroup
        public void MergeLogic()
        {
            NetCodeGroup cg = new NetCodeGroup(new AllMembershipCondition());

            Assert.AreEqual("Union", cg.MergeLogic, "MergeLogic");
        }
 public void Constructor_Null()
 {
     NetCodeGroup cg = new NetCodeGroup((IMembershipCondition)null);
 }
Exemplo n.º 17
0
        // Here is the managed portion of the QuickCache code.  It
        // is mainly concerned with detecting whether it is valid
        // for us to use the quick cache, and then calculating the
        // proper mapping of partial evidence to partial mapping.
        //
        // The choice of the partial evidence sets is fairly arbitrary
        // and in this case is tailored to give us meaningful
        // results from default policy.
        //
        // The choice of whether or not we can use the quick cache
        // is far from arbitrary.  There are a couple conditions that must
        // be true for the QuickCache to produce valid result.  These
        // are:
        //
        // * equivalent evidence objects must produce the same
        //   grant set (i.e. it must be independent of time of day,
        //   space on the harddisk, other "external" factors, and
        //   cannot be random).
        //
        // * evidence must be used positively (i.e. if evidence A grants
        //   permission X, then evidence A+B must grant at least permission
        //   X).
        //
        // In particular for our implementation, this means that we
        // limit the classes that can be used by policy to just
        // the ones defined within mscorlib and that there are
        // no Exclusive bits set on any code groups.

        internal static bool CanUseQuickCache(CodeGroup group)
        {
            ArrayList list = new ArrayList();

            list.Add(group);

            for (int i = 0; i < list.Count; ++i)
            {
                group = (CodeGroup)list[i];

                NetCodeGroup        netGroup   = group as NetCodeGroup;
                UnionCodeGroup      unionGroup = group as UnionCodeGroup;
                FirstMatchCodeGroup firstGroup = group as FirstMatchCodeGroup;
                FileCodeGroup       fileGroup  = group as FileCodeGroup;

                if (netGroup != null)
                {
                    if (!TestPolicyStatement(netGroup.PolicyStatement))
                    {
                        return(false);
                    }
                }
                else if (unionGroup != null)
                {
                    if (!TestPolicyStatement(unionGroup.PolicyStatement))
                    {
                        return(false);
                    }
                }
                else if (firstGroup != null)
                {
                    if (!TestPolicyStatement(firstGroup.PolicyStatement))
                    {
                        return(false);
                    }
                }
                else if (fileGroup != null)
                {
                    if (!TestPolicyStatement(fileGroup.PolicyStatement))
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }

                IMembershipCondition cond = group.MembershipCondition;

                if (cond != null && !(cond is IConstantMembershipCondition))
                {
                    return(false);
                }

                IList children = group.Children;

                if (children != null && children.Count > 0)
                {
                    IEnumerator enumerator = children.GetEnumerator();

                    while (enumerator.MoveNext())
                    {
                        list.Add(enumerator.Current);
                    }
                }
            }

            return(true);
        }
        public void ResolveMatchingCodeGroups_Null()
        {
            NetCodeGroup cg = new NetCodeGroup(new AllMembershipCondition());

            cg.ResolveMatchingCodeGroups(null);
        }
Exemplo n.º 19
0
        }// 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