Intersect() public méthode

public Intersect ( PermissionSet other ) : PermissionSet
other PermissionSet
Résultat PermissionSet
Exemple #1
0
        public static PermissionSet ResolvePolicy(Evidence[] evidences)
        {
            if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
            {
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
            }
            if ((evidences == null) || (evidences.Length == 0))
            {
                evidences = new Evidence[1];
            }
            PermissionSet set = ResolvePolicy(evidences[0]);

            if (set == null)
            {
                return(null);
            }
            for (int i = 1; i < evidences.Length; i++)
            {
                set = set.Intersect(ResolvePolicy(evidences[i]));
                if ((set == null) || set.IsEmpty())
                {
                    return(set);
                }
            }
            return(set);
        }
        static public PermissionSet ResolvePolicy(Evidence[] evidences)
        {
            if (evidences == null || evidences.Length == 0)
            {
                evidences = new Evidence[] { null }
            }
            ;

            PermissionSet retval = ResolvePolicy(evidences[0]);

            if (retval == null)
            {
                return(null);
            }

            for (int i = 1; i < evidences.Length; ++i)
            {
                retval = retval.Intersect(ResolvePolicy(evidences[i]));
                if (retval == null || retval.IsEmpty())
                {
                    return(retval);
                }
            }

            return(retval);
        }
Exemple #3
0
        internal static bool ResolvePolicyLevel(ref PermissionSet ps, PolicyLevel pl, Evidence evidence)
        {
            PolicyStatement policyStatement = pl.Resolve(evidence);

            if (policyStatement != null)
            {
                if (ps == null)
                {
                    ps = policyStatement.PermissionSet;
                }
                else
                {
                    ps = ps.Intersect(policyStatement.PermissionSet);
                    if (ps == null)
                    {
                        ps = new PermissionSet(PermissionState.None);
                    }
                }
                if ((policyStatement.Attributes & PolicyStatementAttribute.LevelFinal) == PolicyStatementAttribute.LevelFinal)
                {
                    return(true);
                }
            }
            return(false);
        }
Exemple #4
0
        internal static bool ResolvePolicyLevel(ref PermissionSet ps, PolicyLevel pl, Evidence evidence)
        {
            PolicyStatement pst = pl.Resolve(evidence);

            if (pst != null)
            {
                if (ps == null)
                {
                    // only for initial (first) policy level processed
                    ps = pst.PermissionSet;
                }
                else
                {
                    ps = ps.Intersect(pst.PermissionSet);
                    if (ps == null)
                    {
                        // null is equals to None - exist that null can throw NullReferenceException ;-)
                        ps = new PermissionSet(PermissionState.None);
                    }
                }

                if ((pst.Attributes & PolicyStatementAttribute.LevelFinal) == PolicyStatementAttribute.LevelFinal)
                {
                    return(true);
                }
            }
            return(false);
        }
        static public PermissionSet ResolvePolicy(Evidence[] evidences)
        {
            if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
            {
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
            }

            if (evidences == null || evidences.Length == 0)
            {
                evidences = new Evidence[] { null }
            }
            ;

            PermissionSet retval = ResolvePolicy(evidences[0]);

            if (retval == null)
            {
                return(null);
            }

            for (int i = 1; i < evidences.Length; ++i)
            {
                retval = retval.Intersect(ResolvePolicy(evidences[i]));
                if (retval == null || retval.IsEmpty())
                {
                    return(retval);
                }
            }

            return(retval);
        }
Exemple #6
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
        }
        public static PermissionSet ResolvePolicy(Evidence[] evidences)
        {
            if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
            {
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
            }
            if (evidences == null || evidences.Length == 0)
            {
                evidences = new Evidence[1];
            }
            PermissionSet permissionSet = SecurityManager.ResolvePolicy(evidences[0]);

            if (permissionSet == null)
            {
                return((PermissionSet)null);
            }
            for (int index = 1; index < evidences.Length; ++index)
            {
                permissionSet = permissionSet.Intersect(SecurityManager.ResolvePolicy(evidences[index]));
                if (permissionSet == null || permissionSet.IsEmpty())
                {
                    return(permissionSet);
                }
            }
            return(permissionSet);
        }
Exemple #8
0
        internal PermissionSetTriple UpdateAssert(PermissionSet in_a)
        {
            PermissionSetTriple retTriple = null;

            if (in_a != null)
            {
                Debug.Assert((!in_a.IsUnrestricted() || RefusedSet == null), "Cannot be unrestricted or refused must be null");
                // if we're already asserting in_a, nothing to do
                if (in_a.IsSubsetOf(AssertSet))
                {
                    return(null);
                }

                PermissionSet retPs;
                if (GrantSet != null)
                {
                    retPs = in_a.Intersect(GrantSet); // Restrict the assert to what we've already been granted
                }
                else
                {
                    GrantSet = new PermissionSet(true);
                    retPs    = in_a.Copy(); // Currently unrestricted Grant: assert the whole assert set
                }
                bool bFailedToCompress = false;
                // removes anything that is already in the refused set from the assert set
                if (RefusedSet != null)
                {
                    retPs = PermissionSet.RemoveRefusedPermissionSet(retPs, RefusedSet, out bFailedToCompress);
                }
                if (!bFailedToCompress)
                {
                    bFailedToCompress = PermissionSet.IsIntersectingAssertedPermissions(retPs, AssertSet);
                }
                if (bFailedToCompress)
                {
                    retTriple = new PermissionSetTriple(this);
                    this.Reset();
                    this.GrantSet = retTriple.GrantSet.Copy();
                }

                if (AssertSet == null)
                {
                    AssertSet = retPs;
                }
                else
                {
                    AssertSet.InplaceUnion(retPs);
                }
            }
            return(retTriple);
        }
Exemple #9
0
        public static PermissionSet ResolvePolicy(Evidence[] evidences)
        {
            if (evidences == null || evidences.Length == 0 || (evidences.Length == 1 && evidences[0].Count == 0))
            {
                return(new PermissionSet(PermissionState.None));
            }
            PermissionSet permissionSet = SecurityManager.ResolvePolicy(evidences[0]);

            for (int i = 1; i < evidences.Length; i++)
            {
                permissionSet = permissionSet.Intersect(SecurityManager.ResolvePolicy(evidences[i]));
            }
            return(permissionSet);
        }
Exemple #10
0
        public static PermissionSet ResolvePolicy(Evidence[] evidences)
        {
            if ((evidences == null) || (evidences.Length == 0) ||
                ((evidences.Length == 1) && (evidences [0].Count == 0)))
            {
                return(new PermissionSet(PermissionState.None));
            }

            // probably not optimal
            PermissionSet ps = ResolvePolicy(evidences [0]);

            for (int i = 1; i < evidences.Length; i++)
            {
                ps = ps.Intersect(ResolvePolicy(evidences [i]));
            }
            return(ps);
        }
Exemple #11
0
        internal PermissionSetTriple UpdateAssert(PermissionSet in_a)
        {
            PermissionSetTriple permissionSetTriple = (PermissionSetTriple)null;

            if (in_a != null)
            {
                if (in_a.IsSubsetOf(this.AssertSet))
                {
                    return((PermissionSetTriple)null);
                }
                PermissionSet permissionSet;
                if (this.GrantSet != null)
                {
                    permissionSet = in_a.Intersect(this.GrantSet);
                }
                else
                {
                    this.GrantSet = new PermissionSet(true);
                    permissionSet = in_a.Copy();
                }
                bool bFailedToCompress = false;
                if (this.RefusedSet != null)
                {
                    permissionSet = PermissionSet.RemoveRefusedPermissionSet(permissionSet, this.RefusedSet, out bFailedToCompress);
                }
                if (!bFailedToCompress)
                {
                    bFailedToCompress = PermissionSet.IsIntersectingAssertedPermissions(permissionSet, this.AssertSet);
                }
                if (bFailedToCompress)
                {
                    permissionSetTriple = new PermissionSetTriple(this);
                    this.Reset();
                    this.GrantSet = permissionSetTriple.GrantSet.Copy();
                }
                if (this.AssertSet == null)
                {
                    this.AssertSet = permissionSet;
                }
                else
                {
                    this.AssertSet.InplaceUnion(permissionSet);
                }
            }
            return(permissionSetTriple);
        }
        internal PermissionSetTriple UpdateAssert(PermissionSet in_a)
        {
            PermissionSetTriple triple = null;

            if (in_a != null)
            {
                PermissionSet set;
                bool          flag;
                if (in_a.IsSubsetOf(this.AssertSet))
                {
                    return(null);
                }
                if (this.GrantSet != null)
                {
                    set = in_a.Intersect(this.GrantSet);
                }
                else
                {
                    this.GrantSet = new PermissionSet(true);
                    set           = in_a.Copy();
                }
                set = PermissionSet.RemoveRefusedPermissionSet(set, this.RefusedSet, out flag);
                if (!flag)
                {
                    flag = PermissionSet.IsIntersectingAssertedPermissions(set, this.AssertSet);
                }
                if (flag)
                {
                    triple = new PermissionSetTriple(this);
                    this.Reset();
                    this.GrantSet = triple.GrantSet.Copy();
                }
                if (this.AssertSet == null)
                {
                    this.AssertSet = set;
                    return(triple);
                }
                this.AssertSet.InplaceUnion(set);
            }
            return(triple);
        }
Exemple #13
0
		internal static bool ResolvePolicyLevel (ref PermissionSet ps, PolicyLevel pl, Evidence evidence)
		{
			PolicyStatement pst = pl.Resolve (evidence);
			if (pst != null) {
				if (ps == null) {
					// only for initial (first) policy level processed
					ps = pst.PermissionSet;
				} else {
					ps = ps.Intersect (pst.PermissionSet);
					if (ps == null) {
						// null is equals to None - exist that null can throw NullReferenceException ;-)
						ps = new PermissionSet (PermissionState.None);
					}
				}

				if ((pst.Attributes & PolicyStatementAttribute.LevelFinal) == PolicyStatementAttribute.LevelFinal)
					return true;
			}
			return false;
		}
Exemple #14
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;
        }       
		public void Intersect_OneNonIUnrestrictedPermission ()
		{
			ZoneIdentityPermission zip = new ZoneIdentityPermission (SecurityZone.MyComputer);
			PermissionSet ps1 = new PermissionSet (PermissionState.None);
			ps1.AddPermission (zip);
			PermissionSet ps2 = new PermissionSet (PermissionState.None);
			Assert.IsNull (ps1.Intersect (null), "PS1 N null");
			Assert.IsNull (ps1.Intersect (ps2), "PS1 N None");
			Assert.IsNull (ps2.Intersect (ps1), "None N PS1");

			PermissionSet ps3 = ps1.Copy ();
			Compare ("PS1 N PS3", ps1.Intersect (ps3), false, 1);
			Compare ("PS3 N PS1", ps3.Intersect (ps1), false, 1);

			PermissionSet ups1 = new PermissionSet (PermissionState.Unrestricted);
			ups1.AddPermission (zip);
			Compare ("PS1 N Unrestricted", ps1.Intersect (ups1), false, 1);
			Compare ("Unrestricted N PS1", ups1.Intersect (ps1), false, 1);

			PermissionSet ups2 = new PermissionSet (PermissionState.Unrestricted);
			Compare ("UPS1 N UPS2", ups1.Intersect (ups2), true, 0);
			Compare ("UPS2 N UPS1", ups2.Intersect (ups1), true, 0);
			ups2.AddPermission (zip);
#if NET_2_0
			// Identity permissions aren't added to unrestricted permission sets in 2.0
			Compare ("UPS1 N UPS2+ZIP", ups1.Intersect (ups2), true, 0);
			Compare ("UPS2+ZIP N UPS1", ups2.Intersect (ups1), true, 0);
#else
			Compare ("UPS1 N UPS2+ZIP", ups1.Intersect (ups2), true, 1);
			Compare ("UPS2+ZIP N UPS1", ups2.Intersect (ups1), true, 1);
#endif
		}
		public void Intersect_OnePermission ()
		{
			SecurityPermission sp = new SecurityPermission (SecurityPermissionFlag.Assertion);
			PermissionSet ps1 = new PermissionSet (PermissionState.None);
			ps1.AddPermission (sp);
			PermissionSet ps2 = new PermissionSet (PermissionState.None);
			Assert.IsNull (ps1.Intersect (null), "PS1 N null");
			Assert.IsNull (ps1.Intersect (ps2), "PS1 N None");
			Assert.IsNull (ps2.Intersect (ps1), "None N PS1");

			PermissionSet ps3 = ps1.Copy ();
			Compare ("PS1 N PS3", ps1.Intersect (ps3), false, 1);
			Compare ("PS3 N PS1", ps3.Intersect (ps1), false, 1);

			PermissionSet ups1 = new PermissionSet (PermissionState.Unrestricted);
			Compare ("PS1 N Unrestricted", ps1.Intersect (ups1), false, 1);
			Compare ("Unrestricted N PS1", ups1.Intersect (ps1), false, 1);
		}
		public void Intersect_Empty ()
		{
			PermissionSet ps1 = new PermissionSet (PermissionState.None);
			PermissionSet ps2 = new PermissionSet (PermissionState.None);
			Assert.IsNull (ps1.Intersect (null), "None N null");
			Assert.IsNull (ps1.Intersect (ps2), "None1 N None2");
			Assert.IsNull (ps2.Intersect (ps1), "None2 N None1");

			PermissionSet ups1 = new PermissionSet (PermissionState.Unrestricted);
			Assert.IsNull (ps1.Intersect (ups1), "None1 N Unrestricted");
			Assert.IsNull (ups1.Intersect (ps1), "Unrestricted N None1");
			Assert.IsNull (ups1.Intersect (null), "Unrestricted N Null");

			PermissionSet ups2 = new PermissionSet (PermissionState.Unrestricted);
			Compare ("ups1 N ups2", ups1.Intersect (ups2), true, 0);
			Compare ("ups2 N ups1", ups2.Intersect (ups1), true, 0);
		}
        /// 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>
        /// <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 NET_3_5

            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);
#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;
        }
Exemple #19
0
        public PermissionSet Resolve(Evidence evidence, PermissionSet request)
        {
#if _DEBUG
            if (debug)
            {
                DEBUG_OUT("PolicyManager::Resolve");
                IEnumerator evidenceEnumerator = evidence.GetEnumerator();
                DEBUG_OUT("Evidence:");
                while (evidenceEnumerator.MoveNext())
                {
                    Object obj = evidenceEnumerator.Current;
                    if (obj is Site)
                    {
                        DEBUG_OUT(((Site)obj).ToXml().ToString());
                    }
                    else if (obj is Zone)
                    {
                        DEBUG_OUT(((Zone)obj).ToXml().ToString());
                    }
                    else if (obj is Url)
                    {
                        DEBUG_OUT(((Url)obj).ToXml().ToString());
                    }
                    else if (obj is StrongName)
                    {
                        DEBUG_OUT(((StrongName)obj).ToXml().ToString());
                    }
                    else if (obj is PermissionRequestEvidence)
                    {
                        DEBUG_OUT(((PermissionRequestEvidence)obj).ToXml().ToString());
                    }
                }
            }
#endif

            // We set grant to null to represent "AllPossible"

            PermissionSet   grant = null;
            PolicyStatement policy;
            PolicyLevel     currentLevel = null;

            IEnumerator levelEnumerator = m_levels.GetEnumerator();

            char[] serializedEvidence = MakeEvidenceArray(evidence, false);
            int    count = evidence.Count;

            bool testApplicationLevels = false;

            while (levelEnumerator.MoveNext())
            {
                currentLevel = (PolicyLevel)levelEnumerator.Current;
                policy       = currentLevel.Resolve(evidence, count, serializedEvidence);

                // If the grant is "AllPossible", the intersection is just the other permission set.
                // Otherwise, do an inplace intersection (since we know we can alter the grant set since
                // it is a copy of the first policy statement's permission set).

                if (grant == null)
                {
                    grant = policy.PermissionSet;
                }
                else
                {
                    // An exception somewhere in here means that a permission
                    // failed some operation.  This simply means that it will be
                    // dropped from the grant set which is safe operation that
                    // can be ignored.

                    try
                    {
                        grant.InplaceIntersect(policy.GetPermissionSetNoCopy());
                    }
                    catch (Exception)
                    {
                    }
                }

    #if _DEBUG
                if (debug)
                {
                    DEBUG_OUT("Level = " + currentLevel.Label);
                    DEBUG_OUT("policy =\n" + policy.ToXml().ToString());
                    DEBUG_OUT("grant so far =\n" + grant.ToXml().ToString());
                }
    #endif

                if (grant.IsEmpty())
                {
                    break;
                }
                else if ((policy.Attributes & PolicyStatementAttribute.LevelFinal) == PolicyStatementAttribute.LevelFinal)
                {
                    if (!currentLevel.Label.Equals("AppDomain"))
                    {
                        testApplicationLevels = true;
                    }

                    break;
                }
            }

            if (testApplicationLevels)
            {
                PolicyLevel appDomainLevel = null;

                for (int i = m_levels.Count - 1; i >= 0; --i)
                {
                    currentLevel = (PolicyLevel)m_levels[i];

                    if (currentLevel.Label.Equals("AppDomain"))
                    {
                        appDomainLevel = currentLevel;
                        break;
                    }
                }

                if (appDomainLevel != null)
                {
                    policy = appDomainLevel.Resolve(evidence, count, serializedEvidence);

                    grant.InplaceIntersect(policy.GetPermissionSetNoCopy());
                }
            }


    #if _DEBUG
            if (debug)
            {
                DEBUG_OUT("granted =\n" + grant.ToString());
                DEBUG_OUT("request =\n" + (request != null ? request.ToString() : "<null>"));
                DEBUG_OUT("awarded =\n" + (request != null ? grant.Intersect(request).ToString() : grant.ToString()));
            }
    #endif

            try
            {
                if (request != null)
                {
                    grant.InplaceIntersect(request);
                }
            }
            catch (Exception)
            {
            }

    #if _DEBUG
            if (debug)
            {
                DEBUG_OUT("granted after intersect w/ request =\n" + grant.ToString());
            }
    #endif

            // Each piece of evidence can possibly create an identity permission that we
            // need to add to our grant set.  Therefore, for all pieces of evidence that
            // implement the IIdentityPermissionFactory interface, ask it for its
            // adjoining identity permission and add it to the grant.

            IEnumerator enumerator = evidence.GetHostEnumerator();
            while (enumerator.MoveNext())
            {
                try
                {
                    Object obj = enumerator.Current;
                    IIdentityPermissionFactory factory = obj as IIdentityPermissionFactory;
                    if (factory != null)
                    {
                        IPermission perm = factory.CreateIdentityPermission(evidence);

                        if (perm != null)
                        {
                            grant.AddPermission(perm);
                        }
                    }
                }
                catch (Exception)
                {
                }
            }

    #if _DEBUG
            if (debug)
            {
                DEBUG_OUT("awarded with identity =\n" + grant.ToString());
            }
    #endif
            return(grant);
        }
        private static bool FrameDescSetHelper(FrameSecurityDescriptor secDesc,
                                               PermissionSet demandSet,
                                               out PermissionSet alteredDemandSet)
        {
            PermissionSet permSet;

            // In the common case we are not going to alter the demand set, so just to
            // be safe we'll set it to null up front.

            // There's some oddness in here to deal with exceptions.  The general idea behind
            // this is that we need some way of dealing with custom permissions that may not
            // handle all possible scenarios of Union(), Intersect(), and IsSubsetOf() properly
            // (they don't support it, throw null reference exceptions, etc.).

            alteredDemandSet = null;

            // An empty demand always succeeds.
            if (demandSet == null || demandSet.IsEmpty())
            {
                return(StackHalt);
            }

            // In the case of permit only, we define an exception to be failure of the check
            // and therefore we throw a security exception.

            try
            {
                permSet = secDesc.GetPermitOnly();
                if (permSet != null)
                {
                    if (!demandSet.IsSubsetOf(permSet))
                    {
                        throw new SecurityException(Environment.GetResourceString("Security_GenericNoType"));
                    }
                }
            }
            catch (Exception)
            {
                throw new SecurityException(Environment.GetResourceString("Security_GenericNoType"));
            }

            // In the case of denial, we define an exception to be failure of the check
            // and therefore we throw a security exception.

            try
            {
                permSet = secDesc.GetDenials();

    #if _DEBUG
                if (debug)
                {
                    DEBUG_OUT("Checking Denials");
                    DEBUG_OUT("denials set =\n" + permSet.ToXml().ToString());
                    DEBUG_OUT("demandSet =\n" + demandSet.ToXml().ToString());
                }
    #endif

                if (permSet != null)
                {
                    PermissionSet intersection = demandSet.Intersect(permSet);

                    if (intersection != null && !intersection.IsEmpty())
                    {
                        throw new SecurityException(Environment.GetResourceString("Security_GenericNoType"));
                    }
                }
            }
            catch (Exception)
            {
                throw new SecurityException(Environment.GetResourceString("Security_GenericNoType"));
            }

            // The assert case is more complex.  Since asserts have the ability to "bleed through"
            // (where part of a demand is handled by an assertion, but the rest is passed on to
            // continue the stackwalk), we need to be more careful in handling the "failure" case.
            // Therefore, if an exception is thrown in performing any operation, we make sure to keep
            // that permission in the demand set thereby continuing the demand for that permission
            // walking down the stack.

            if (secDesc.GetAssertAllPossible())
            {
                return(StackHalt);
            }

            permSet = secDesc.GetAssertions();
            if (permSet != null)
            {
                // If this frame asserts a superset of the demand set we're done

                try
                {
                    if (demandSet.IsSubsetOf(permSet))
                    {
                        return(StackHalt);
                    }
                }
                catch (Exception)
                {
                }

                // Determine whether any of the demand set asserted.  We do this by
                // copying the demand set and removing anything in it that is asserted.

                if (!permSet.IsUnrestricted())
                {
                    PermissionSetEnumerator enumerator = (PermissionSetEnumerator)demandSet.GetEnumerator();
                    while (enumerator.MoveNext())
                    {
                        IPermission perm
                            = (IPermission)enumerator.Current;
                        int i = enumerator.GetCurrentIndex();
                        if (perm != null)
                        {
                            bool        unrestricted = perm is System.Security.Permissions.IUnrestrictedPermission;
                            IPermission assertPerm
                                = (IPermission)permSet.GetPermission(i, unrestricted);

                            bool removeFromAlteredDemand = false;
                            try
                            {
                                removeFromAlteredDemand = perm.IsSubsetOf(assertPerm);
                            }
                            catch (Exception)
                            {
                            }

                            if (removeFromAlteredDemand)
                            {
                                if (alteredDemandSet == null)
                                {
                                    alteredDemandSet = demandSet.Copy();
                                }
                                alteredDemandSet.RemovePermission(i, unrestricted);
                            }
                        }
                    }
                }
            }

            return(StackContinue);
        }
Exemple #21
0
		public static void PermissionSetDemo()
		{
			
			Console.WriteLine("Executing Permission Set Demo");
			try
			{
				// Open a permission set.
				PermissionSet ps1 = new PermissionSet(PermissionState.None);
				Console.WriteLine("Adding permission to open a file from a file dialog box.");
				// Add a permission to the permission set.
				ps1.AddPermission(new FileDialogPermission(FileDialogPermissionAccess.Open));
				Console.WriteLine("Demanding Permission to open a file.");
				ps1.Demand();
				Console.WriteLine("Demand succeeded.");
				Console.WriteLine("Adding permission to save a file from a file dialog box.");
				ps1.AddPermission(new FileDialogPermission(FileDialogPermissionAccess.Save));
				Console.WriteLine("Demanding permission to open and save a file.");
				ps1.Demand();
				Console.WriteLine("Demand succeeded.");
				Console.WriteLine("Adding a permission to read environment variable USERNAME.");
				ps1.AddPermission(new EnvironmentPermission(EnvironmentPermissionAccess.Read, "USERNAME"));
				ps1.Demand();
				Console.WriteLine("Demand succeeded.");
				Console.WriteLine("Adding permission to read environment variable COMPUTERNAME.");
				ps1.AddPermission(new EnvironmentPermission(EnvironmentPermissionAccess.Read, "COMPUTERNAME"));
				// Demand all the permissions in the set.
				Console.WriteLine("Demand all permissions.");
				ps1.Demand();
				Console.WriteLine("Demand succeeded.");
				// Display the number of permissions in the set.
				Console.WriteLine("Number of permissions = " + ps1.Count);
				// Display the value of the IsSynchronized property.
				Console.WriteLine("IsSynchronized property = " + ps1.IsSynchronized);
				// Display the value of the IsReadOnly property.
				Console.WriteLine("IsReadOnly property = " + ps1.IsReadOnly);
				// Display the value of the SyncRoot property.
				Console.WriteLine("SyncRoot property = " + ps1.SyncRoot);
				// Display the result of a call to the ContainsNonCodeAccessPermissions method.
				// Gets a value indicating whether the PermissionSet contains permissions
				// that are not derived from CodeAccessPermission.
				// Returns true if the PermissionSet contains permissions that are not 
				// derived from CodeAccessPermission; otherwise, false.
				Console.WriteLine("ContainsNonCodeAccessPermissions method returned " + ps1.ContainsNonCodeAccessPermissions());
				Console.WriteLine("Value of the permission set ToString = \n" + ps1.ToString());
				PermissionSet ps2 = new PermissionSet(PermissionState.None);
				// Create a second permission set and compare it to the first permission set.
				ps2.AddPermission(new EnvironmentPermission(EnvironmentPermissionAccess.Read, "USERNAME"));
				ps2.AddPermission(new EnvironmentPermission(EnvironmentPermissionAccess.Write, "COMPUTERNAME"));
				Console.WriteLine("Permission set 2 = " + ps2);
				IEnumerator list = ps1.GetEnumerator();
				Console.WriteLine("Permissions in first permission set:");
				foreach (var permission in ps1)
					Console.WriteLine(permission.ToString());
				Console.WriteLine("Second permission IsSubSetOf first permission = " + ps2.IsSubsetOf(ps1));
				// Display the intersection of two permission sets.
				PermissionSet ps3 = ps2.Intersect(ps1);
				Console.WriteLine("The intersection of the first permission set and the second permission set = " + ps3.ToString());
				// Create a new permission set.
				PermissionSet ps4 = new PermissionSet(PermissionState.None);
				ps4.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, "C:\\Temp\\Testfile.txt"));
				ps4.AddPermission(new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, "C:\\Temp\\Testfile.txt"));
				// Display the union of two permission sets.
				PermissionSet ps5 = ps3.Union(ps4);
				Console.WriteLine("The union of permission set 3 and permission set 4 = " + ps5.ToString());
				// Remove FileIOPermission from the permission set.
				ps5.RemovePermission(typeof(FileIOPermission));
				Console.WriteLine("The last permission set after removing FileIOPermission = " + ps5.ToString());
				// Change the permission set using SetPermission
				ps5.SetPermission(new EnvironmentPermission(EnvironmentPermissionAccess.AllAccess, "USERNAME"));
				Console.WriteLine("Permission set after SetPermission = " + ps5.ToString());
				// Display result of ToXml and FromXml operations.
				PermissionSet ps6 = new PermissionSet(PermissionState.None);
				ps6.FromXml(ps5.ToXml());
				Console.WriteLine("Result of ToFromXml = " + ps6.ToString() + "\n");
				// Display result of PermissionSet.GetEnumerator.
				IEnumerator psEnumerator = ps1.GetEnumerator();
				while (psEnumerator.MoveNext())
				{
					Console.WriteLine(psEnumerator.Current.ToString());
				}
				// Check for an unrestricted permission set.
				PermissionSet ps7 = new PermissionSet(PermissionState.Unrestricted);
				Console.WriteLine("Permission set is unrestricted = " + ps7.IsUnrestricted());
				// Create and display a copy of a permission set.
				ps7 = ps5.Copy();
				Console.WriteLine("Result of copy = " + ps7.ToString());
			}
			catch (Exception e)
			{
				Console.WriteLine(e.Message.ToString());
			}
		}
 internal PermissionSetTriple UpdateAssert(PermissionSet in_a)
 {
     PermissionSetTriple triple = null;
     if (in_a != null)
     {
         PermissionSet set;
         bool flag;
         if (in_a.IsSubsetOf(this.AssertSet))
         {
             return null;
         }
         if (this.GrantSet != null)
         {
             set = in_a.Intersect(this.GrantSet);
         }
         else
         {
             this.GrantSet = new PermissionSet(true);
             set = in_a.Copy();
         }
         set = PermissionSet.RemoveRefusedPermissionSet(set, this.RefusedSet, out flag);
         if (!flag)
         {
             flag = PermissionSet.IsIntersectingAssertedPermissions(set, this.AssertSet);
         }
         if (flag)
         {
             triple = new PermissionSetTriple(this);
             this.Reset();
             this.GrantSet = triple.GrantSet.Copy();
         }
         if (this.AssertSet == null)
         {
             this.AssertSet = set;
             return triple;
         }
         this.AssertSet.InplaceUnion(set);
     }
     return triple;
 }
Exemple #23
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
            Evidence e = new Evidence();
            e.AddHostEvidence(new Zone(SecurityZone.Internet));
            return SecurityManager.GetStandardSandbox(e);
#endif
        }       
        [System.Security.SecurityCritical]  // auto-generated
        internal PermissionSetTriple UpdateAssert(PermissionSet in_a)
        {
            PermissionSetTriple retTriple = null;
            if (in_a != null)
            {
                Contract.Assert((!in_a.IsUnrestricted() || RefusedSet == null), "Cannot be unrestricted or refused must be null");
                // if we're already asserting in_a, nothing to do
                if (in_a.IsSubsetOf(AssertSet))
                    return null;

                PermissionSet retPs;
                if (GrantSet != null)
                    retPs = in_a.Intersect(GrantSet); // Restrict the assert to what we've already been granted
                else
                {
                    GrantSet = new PermissionSet(true);
                    retPs = in_a.Copy(); // Currently unrestricted Grant: assert the whole assert set
                }
                bool bFailedToCompress = false;
                // removes anything that is already in the refused set from the assert set
                if (RefusedSet != null)
                {
                    retPs = PermissionSet.RemoveRefusedPermissionSet(retPs, RefusedSet, out bFailedToCompress);
                }
                if (!bFailedToCompress)
                    bFailedToCompress = PermissionSet.IsIntersectingAssertedPermissions(retPs, AssertSet);
                if (bFailedToCompress)
                {
                    retTriple = new PermissionSetTriple(this);
                    this.Reset();
                    this.GrantSet = retTriple.GrantSet.Copy();
                }

                if (AssertSet == null)
                    AssertSet = retPs;
                else
                    AssertSet.InplaceUnion(retPs);

            }
            return retTriple;
        }
Exemple #25
0
        private static bool FrameDescSetHelper(FrameSecurityDescriptor secDesc,
                                               PermissionSet demandSet,
                                               out PermissionSet alteredDemandSet)
        {
            PermissionSet permSet;

            // In the common case we are not going to alter the demand set, so just to
            // be safe we'll set it to null up front.
            
            // There's some oddness in here to deal with exceptions.  The general idea behind
            // this is that we need some way of dealing with custom permissions that may not
            // handle all possible scenarios of Union(), Intersect(), and IsSubsetOf() properly
            // (they don't support it, throw null reference exceptions, etc.).
            
            alteredDemandSet = null;

            // An empty demand always succeeds.
            if (demandSet == null || demandSet.IsEmpty())
                return StackHalt;
            
            // In the case of permit only, we define an exception to be failure of the check
            // and therefore we throw a security exception.
            
            try
            {
                permSet = secDesc.GetPermitOnly();
                if (permSet != null)
                {
                    if (!demandSet.IsSubsetOf(permSet))
                    {
                        throw new SecurityException(Environment.GetResourceString("Security_GenericNoType"));
                    }
                }
            }
            catch (Exception)
            {
                throw new SecurityException(Environment.GetResourceString("Security_GenericNoType"));
            }
                
            // In the case of denial, we define an exception to be failure of the check
            // and therefore we throw a security exception.
                
            try
            {
                permSet = secDesc.GetDenials();

    #if _DEBUG
                if (debug)
                {
                    DEBUG_OUT("Checking Denials");
                    DEBUG_OUT("denials set =\n" + permSet.ToXml().ToString() );
                    DEBUG_OUT("demandSet =\n" + demandSet.ToXml().ToString() );
                }
    #endif

                if (permSet != null)
                {
                    PermissionSet intersection = demandSet.Intersect(permSet);
            
                    if (intersection != null && !intersection.IsEmpty())
                    {
                        throw new SecurityException(Environment.GetResourceString("Security_GenericNoType"));
                    }
                }
            }
            catch (Exception)
            {
                throw new SecurityException(Environment.GetResourceString("Security_GenericNoType"));
            }
            
            // The assert case is more complex.  Since asserts have the ability to "bleed through"
            // (where part of a demand is handled by an assertion, but the rest is passed on to
            // continue the stackwalk), we need to be more careful in handling the "failure" case.
            // Therefore, if an exception is thrown in performing any operation, we make sure to keep
            // that permission in the demand set thereby continuing the demand for that permission
            // walking down the stack.
            
            if (secDesc.GetAssertAllPossible())
            {
                return StackHalt;
            }        
            
            permSet = secDesc.GetAssertions();
            if (permSet != null)
            {
                // If this frame asserts a superset of the demand set we're done
                
                try
                {
                    if (demandSet.IsSubsetOf( permSet ))
                        return StackHalt;
                }
                catch (Exception)
                {
                }
                
                // Determine whether any of the demand set asserted.  We do this by
                // copying the demand set and removing anything in it that is asserted.
                    
                if (!permSet.IsUnrestricted())
                {
                    PermissionSetEnumerator enumerator = (PermissionSetEnumerator)demandSet.GetEnumerator();
                    while (enumerator.MoveNext())
                    {
                        IPermission perm
                            = (IPermission)enumerator.Current;
                        int i = enumerator.GetCurrentIndex();
                        if (perm != null)
                        {
                            bool unrestricted = perm is System.Security.Permissions.IUnrestrictedPermission;
                            IPermission assertPerm
                                = (IPermission)permSet.GetPermission(i, unrestricted);
                            
                            bool removeFromAlteredDemand = false;
                            try
                            {
                                removeFromAlteredDemand = perm.IsSubsetOf(assertPerm);
                            }
                            catch (Exception)
                            {
                            }
                        
                            if (removeFromAlteredDemand)
                            {
                                if (alteredDemandSet == null)
                                    alteredDemandSet = demandSet.Copy();
                                alteredDemandSet.RemovePermission(i, unrestricted);
                            }                        
                        
                        }
                    }
                }
            }
            
            return StackContinue;
        }