IsUnrestricted() public method

public IsUnrestricted ( ) : bool
return bool
コード例 #1
1
		public void SetPermission_Unrestricted ()
		{
			SecurityPermission sp = new SecurityPermission (PermissionState.Unrestricted);
			PermissionSet ps = new PermissionSet (PermissionState.Unrestricted);
			Assert.AreEqual (0, ps.Count, "Empty");
			Assert.IsTrue (ps.IsUnrestricted (), "State-Unrestricted");

			ZoneIdentityPermission zip = new ZoneIdentityPermission (SecurityZone.MyComputer);
			ZoneIdentityPermission zipr = (ZoneIdentityPermission)ps.SetPermission (zip);
			Assert.AreEqual (1, ps.Count, "ZoneIdentityPermission");
			Assert.AreEqual (SecurityZone.MyComputer, zipr.SecurityZone, "SecurityZone");
#if NET_2_0
			// Adding a non unrestricted identity permission now results in 
			// a permission set loosing it's unrestricted status
			Assert.IsTrue (!ps.IsUnrestricted (), "State-Unrestricted-2");
#else
			Assert.IsTrue (ps.IsUnrestricted (), "State-Unrestricted-2");
#endif
			zip = new ZoneIdentityPermission (SecurityZone.Intranet);
			zipr = (ZoneIdentityPermission)ps.SetPermission (zip);
			Assert.AreEqual (1, ps.Count, "ZoneIdentityPermission-2");
			Assert.AreEqual (SecurityZone.Intranet, zipr.SecurityZone, "SecurityZone-2");

			SecurityPermission result = (SecurityPermission)ps.SetPermission (sp);
			Assert.AreEqual (2, ps.Count, "SecurityPermission");
			Assert.AreEqual (SecurityPermissionFlag.AllFlags, result.Flags, "Flags");
			Assert.IsTrue (!ps.IsUnrestricted (), "State-None");

			sp = new SecurityPermission (SecurityPermissionFlag.ControlAppDomain);
			result = (SecurityPermission)ps.SetPermission (sp);
			Assert.AreEqual (2, ps.Count, "SecurityPermission-2");
			Assert.AreEqual (SecurityPermissionFlag.ControlAppDomain, result.Flags, "Flags-2");
		}
コード例 #2
0
		public void PermissionSetNull () 
		{
			// no exception is thrown
			PermissionSet ps = new PermissionSet (null);
#if NET_2_0
			Assert ("PermissionStateNull.IsUnrestricted", !ps.IsUnrestricted ());
			Assert ("PermissionStateNull.IsEmpty", ps.IsEmpty ());
#else
			Assert ("PermissionStateNull.IsUnrestricted", ps.IsUnrestricted ());
			Assert ("PermissionStateNull.IsEmpty", !ps.IsEmpty ());
#endif
			Assert ("PermissionStateNull.IsReadOnly", !ps.IsReadOnly);
			AssertEquals ("PermissionStateNull.ToXml().ToString()==ToString()", ps.ToXml ().ToString (), ps.ToString ());
		}
コード例 #3
0
		public void PermissionSetNull () 
		{
			// no exception is thrown
			PermissionSet ps = new PermissionSet (null);
#if NET_2_0
			Assert.IsTrue (!ps.IsUnrestricted (), "PermissionStateNull.IsUnrestricted");
			Assert.IsTrue (ps.IsEmpty (), "PermissionStateNull.IsEmpty");
#else
			Assert.IsTrue (ps.IsUnrestricted (), "PermissionStateNull.IsUnrestricted");
			Assert.IsTrue (!ps.IsEmpty (), "PermissionStateNull.IsEmpty");
#endif
			Assert.IsTrue (!ps.IsReadOnly, "PermissionStateNull.IsReadOnly");
			Assert.AreEqual (ps.ToXml ().ToString (), ps.ToString (), "PermissionStateNull.ToXml().ToString()==ToString()");
			Assert.IsTrue (!ps.ContainsNonCodeAccessPermissions (), "ContainsNonCodeAccessPermissions");
		}
 private static bool IsFullTrust(PermissionSet perms)
 {
     if (perms != null)
     {
         return perms.IsUnrestricted();
     }
     return true;
 }
コード例 #5
0
		public void PermissionStateUnrestricted () 
		{
			PermissionSet ps = new PermissionSet (PermissionState.Unrestricted);
			Assert ("PermissionStateUnrestricted.IsUnrestricted", ps.IsUnrestricted ());
			Assert ("PermissionStateUnrestricted.IsEmpty", !ps.IsEmpty ());
			Assert ("PermissionStateUnrestricted.IsReadOnly", !ps.IsReadOnly);
			AssertEquals ("PermissionStateUnrestricted.ToXml().ToString()==ToString()", ps.ToXml ().ToString (), ps.ToString ());
		}
コード例 #6
0
		public void PermissionStateUnrestricted () 
		{
			PermissionSet ps = new PermissionSet (PermissionState.Unrestricted);
			Assert.IsTrue (ps.IsUnrestricted (), "PermissionStateUnrestricted.IsUnrestricted");
			Assert.IsTrue (!ps.IsEmpty (), "PermissionStateUnrestricted.IsEmpty");
			Assert.IsTrue (!ps.IsReadOnly, "PermissionStateUnrestricted.IsReadOnly");
			Assert.AreEqual (ps.ToXml ().ToString (), ps.ToString (), "PermissionStateUnrestricted.ToXml().ToString()==ToString()");
			Assert.IsTrue (!ps.ContainsNonCodeAccessPermissions (), "ContainsNonCodeAccessPermissions");
		}
 private static bool CheckAssert(PermissionSet pSet, CodeAccessPermission demand, PermissionToken permToken)
 {
     if (pSet != null)
     {
         pSet.CheckDecoded(demand, permToken);
         CodeAccessPermission asserted = (CodeAccessPermission) pSet.GetPermission(demand);
         try
         {
             if (pSet.IsUnrestricted() || demand.CheckAssert(asserted))
             {
                 return false;
             }
         }
         catch (ArgumentException)
         {
         }
     }
     return true;
 }
コード例 #8
0
        [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;
        }
コード例 #9
0
        internal static QuickCacheEntryType GenerateQuickCache(PolicyLevel level)
        {
            QuickCacheEntryType[] ExecutionMap = new QuickCacheEntryType[]
            { QuickCacheEntryType.ExecutionZoneMyComputer,
              QuickCacheEntryType.ExecutionZoneIntranet,
              QuickCacheEntryType.ExecutionZoneInternet,
              QuickCacheEntryType.ExecutionZoneTrusted,
              QuickCacheEntryType.ExecutionZoneUntrusted };

            QuickCacheEntryType[] UnmanagedMap = new QuickCacheEntryType[]
            { QuickCacheEntryType.UnmanagedZoneMyComputer,
              QuickCacheEntryType.UnmanagedZoneIntranet,
              QuickCacheEntryType.UnmanagedZoneInternet,
              QuickCacheEntryType.UnmanagedZoneTrusted,
              QuickCacheEntryType.UnmanagedZoneUntrusted };

            QuickCacheEntryType[] BindingRedirectMap = new QuickCacheEntryType[]
            { QuickCacheEntryType.BindingRedirectsZoneMyComputer,
              QuickCacheEntryType.BindingRedirectsZoneIntranet,
              QuickCacheEntryType.BindingRedirectsZoneInternet,
              QuickCacheEntryType.BindingRedirectsZoneTrusted,
              QuickCacheEntryType.BindingRedirectsZoneUntrusted };

            QuickCacheEntryType[] SkipVerificationMap = new QuickCacheEntryType[]
            { QuickCacheEntryType.SkipVerificationZoneMyComputer,
              QuickCacheEntryType.SkipVerificationZoneIntranet,
              QuickCacheEntryType.SkipVerificationZoneInternet,
              QuickCacheEntryType.SkipVerificationZoneTrusted,
              QuickCacheEntryType.SkipVerificationZoneUntrusted };

            QuickCacheEntryType[] FullTrustMap = new QuickCacheEntryType[]
            { QuickCacheEntryType.FullTrustZoneMyComputer,
              QuickCacheEntryType.FullTrustZoneIntranet,
              QuickCacheEntryType.FullTrustZoneInternet,
              QuickCacheEntryType.FullTrustZoneTrusted,
              QuickCacheEntryType.FullTrustZoneUntrusted };

            QuickCacheEntryType accumulator = (QuickCacheEntryType)0;

            SecurityPermission execPerm            = new SecurityPermission(SecurityPermissionFlag.Execution);
            SecurityPermission unmanagedPerm       = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
            SecurityPermission skipVerifPerm       = new SecurityPermission(SecurityPermissionFlag.SkipVerification);
            SecurityPermission bindingRedirectPerm = new SecurityPermission(SecurityPermissionFlag.BindingRedirects);

            Evidence noEvidence = new Evidence();

            PermissionSet policy = null;

            try
            {
                policy = level.Resolve(noEvidence).PermissionSet;

                if (policy.Contains(execPerm))
                {
                    accumulator |= QuickCacheEntryType.ExecutionAll;
                }

                if (policy.Contains(unmanagedPerm))
                {
                    accumulator |= QuickCacheEntryType.UnmanagedAll;
                }

                if (policy.Contains(skipVerifPerm))
                {
                    accumulator |= QuickCacheEntryType.SkipVerificationAll;
                }

                if (policy.Contains(bindingRedirectPerm))
                {
                    accumulator |= QuickCacheEntryType.BindingRedirectsAll;
                }

                if (policy.IsUnrestricted())
                {
                    accumulator |= QuickCacheEntryType.FullTrustAll;
                }
            }
            catch (PolicyException)
            {
            }

            Array zones = Enum.GetValues(typeof(SecurityZone));

            for (int i = 0; i < zones.Length; ++i)
            {
                if (((SecurityZone)zones.GetValue(i)) == SecurityZone.NoZone)
                {
                    continue;
                }

                Evidence zoneEvidence = new Evidence();
                zoneEvidence.AddHost(new Zone((SecurityZone)zones.GetValue(i)));

                PermissionSet zonePolicy = null;

                try
                {
                    zonePolicy = level.Resolve(zoneEvidence).PermissionSet;

                    if (zonePolicy.Contains(execPerm))
                    {
                        accumulator |= ExecutionMap[i];
                    }

                    if (zonePolicy.Contains(unmanagedPerm))
                    {
                        accumulator |= UnmanagedMap[i];
                    }

                    if (zonePolicy.Contains(skipVerifPerm))
                    {
                        accumulator |= SkipVerificationMap[i];
                    }

                    if (zonePolicy.Contains(bindingRedirectPerm))
                    {
                        accumulator |= BindingRedirectMap[i];
                    }

                    if (zonePolicy.IsUnrestricted())
                    {
                        accumulator |= FullTrustMap[i];
                    }
                }
                catch (PolicyException)
                {
                }
            }

            return(accumulator);
        }
コード例 #10
0
        internal static int GetSpecialFlags(PermissionSet grantSet, PermissionSet deniedSet)
        {
            if (grantSet != null && grantSet.IsUnrestricted() && (deniedSet == null || deniedSet.IsEmpty()))
            {
                return(-1);
            }
            SecurityPermissionFlag   securityPermissionFlags   = SecurityPermissionFlag.NoFlags;
            ReflectionPermissionFlag reflectionPermissionFlags = ReflectionPermissionFlag.NoFlags;

            CodeAccessPermission[] accessPermissionArray = new CodeAccessPermission[6];
            if (grantSet != null)
            {
                if (grantSet.IsUnrestricted())
                {
                    securityPermissionFlags   = SecurityPermissionFlag.AllFlags;
                    reflectionPermissionFlags = ReflectionPermissionFlag.AllFlags | ReflectionPermissionFlag.RestrictedMemberAccess;
                    for (int index = 0; index < accessPermissionArray.Length; ++index)
                    {
                        accessPermissionArray[index] = SecurityManager.s_UnrestrictedSpecialPermissionMap[index];
                    }
                }
                else
                {
                    SecurityPermission securityPermission = grantSet.GetPermission(6) as SecurityPermission;
                    if (securityPermission != null)
                    {
                        securityPermissionFlags = securityPermission.Flags;
                    }
                    ReflectionPermission reflectionPermission = grantSet.GetPermission(4) as ReflectionPermission;
                    if (reflectionPermission != null)
                    {
                        reflectionPermissionFlags = reflectionPermission.Flags;
                    }
                    for (int index = 0; index < accessPermissionArray.Length; ++index)
                    {
                        accessPermissionArray[index] = grantSet.GetPermission(SecurityManager.s_BuiltInPermissionIndexMap[index][0]) as CodeAccessPermission;
                    }
                }
            }
            if (deniedSet != null)
            {
                if (deniedSet.IsUnrestricted())
                {
                    securityPermissionFlags   = SecurityPermissionFlag.NoFlags;
                    reflectionPermissionFlags = ReflectionPermissionFlag.NoFlags;
                    for (int index = 0; index < SecurityManager.s_BuiltInPermissionIndexMap.Length; ++index)
                    {
                        accessPermissionArray[index] = (CodeAccessPermission)null;
                    }
                }
                else
                {
                    SecurityPermission securityPermission = deniedSet.GetPermission(6) as SecurityPermission;
                    if (securityPermission != null)
                    {
                        securityPermissionFlags &= ~securityPermission.Flags;
                    }
                    ReflectionPermission reflectionPermission = deniedSet.GetPermission(4) as ReflectionPermission;
                    if (reflectionPermission != null)
                    {
                        reflectionPermissionFlags &= ~reflectionPermission.Flags;
                    }
                    for (int index = 0; index < SecurityManager.s_BuiltInPermissionIndexMap.Length; ++index)
                    {
                        CodeAccessPermission accessPermission = deniedSet.GetPermission(SecurityManager.s_BuiltInPermissionIndexMap[index][0]) as CodeAccessPermission;
                        if (accessPermission != null && !accessPermission.IsSubsetOf((IPermission)null))
                        {
                            accessPermissionArray[index] = (CodeAccessPermission)null;
                        }
                    }
                }
            }
            int specialFlags = SecurityManager.MapToSpecialFlags(securityPermissionFlags, reflectionPermissionFlags);

            if (specialFlags != -1)
            {
                for (int index = 0; index < accessPermissionArray.Length; ++index)
                {
                    if (accessPermissionArray[index] != null && ((IUnrestrictedPermission)accessPermissionArray[index]).IsUnrestricted())
                    {
                        specialFlags |= 1 << SecurityManager.s_BuiltInPermissionIndexMap[index][1];
                    }
                }
            }
            return(specialFlags);
        }
コード例 #11
0
		public void PermissionSetNamedPermissionSet ()
		{
			NamedPermissionSet nps = new NamedPermissionSet ("Test", PermissionState.Unrestricted);
			PermissionSet ps = new PermissionSet (nps);
			Assert.IsTrue (ps.IsUnrestricted (), "IsUnrestricted");
			Assert.IsTrue (!ps.ContainsNonCodeAccessPermissions (), "ContainsNonCodeAccessPermissions");
		}
コード例 #12
0
ファイル: permissionlistset.cs プロジェクト: ArildF/masters
        // Returns true if it is necessary to continue compression,
        // or false if there is no value in continuing.
        public bool AppendPermissions(PermissionSet permSet, int type)
        {
            if (permSet == null)
            {
                // The null permission set has no meaning accept for the case of
                // PermitOnly and Checked where it will make all demands fail (except
                // demands for empty permissions). 
                
                if (type == PermissionList.MatchChecked || type == PermissionList.MatchPermitOnly)
                {
                    TerminateSet( type );
                    m_unrestricted = false;
                    return false;
                }

                return true;
            }
            
            if (((m_state & (PermissionListSetState.UnrestrictedAssert | PermissionListSetState.UnrestrictedDeny)) == 0))
            {
                if (permSet.IsUnrestricted())
                {
                    switch (type)
                    {
                    case PermissionList.MatchDeny:
                        m_state |= PermissionListSetState.UnrestrictedDeny;
                        m_unrestricted = false;
                        TerminateSet( type );
                        break;

                    case PermissionList.MatchAssert:
                        m_state |= PermissionListSetState.UnrestrictedAssert;
                        TerminateSet( type );
                        break;
                    
                    case PermissionList.MatchPermitOnly:
                    case PermissionList.MatchChecked:
                        break;
                    
                    default:
                        throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionListType"));
                    }
                }
                else
                {
                    // Handle the "unrestricted" permissions.
                
                    AppendTokenBasedSets( this.m_unrestrictedPermSet, permSet.m_unrestrictedPermSet, type, true );
                
                    if (type != PermissionList.MatchAssert && type != PermissionList.MatchDeny)
                        m_unrestricted = false;
                }
            }
            
            // Handle the "normal" permissions
            
            AppendTokenBasedSets( this.m_normalPermSet, permSet.m_normalPermSet, type, false );
            
            return true;
        }
コード例 #13
0
        [System.Security.SecurityCritical]  // auto-generated
#pragma warning disable 618
        internal static bool CheckHelper(PermissionSet grantedSet,
#pragma warning restore 618
                                        PermissionSet refusedSet,
                                        CodeAccessPermission demand, 
                                        PermissionToken permToken,
                                        RuntimeMethodHandleInternal rmh,
                                        Object assemblyOrString,
                                        SecurityAction action,
                                        bool throwException)
        {
            // We should never get here with a null demand
            Contract.Assert(demand != null, "Should not reach here with a null demand");
            
#if _DEBUG && FEATURE_CAS_POLICY
            if (debug)
            {
                DEBUG_OUT("Granted: ");
                DEBUG_OUT(grantedSet.ToXml().ToString());
                DEBUG_OUT("Refused: ");
                DEBUG_OUT(refusedSet != null ? refusedSet.ToXml().ToString() : "<null>");
                DEBUG_OUT("Demanded: ");
                DEBUG_OUT(demand.ToString());
            }
#endif // _DEBUG && FEATURE_CAS_POLICY

            if (permToken == null)
                permToken = PermissionToken.GetToken(demand);

            if (grantedSet != null)
                grantedSet.CheckDecoded(permToken.m_index);
            if (refusedSet != null)
                refusedSet.CheckDecoded(permToken.m_index);

            // If PermissionSet is null, then module does not have Permissions... Fail check.

            bool bThreadSecurity = SecurityManager._SetThreadSecurity(false);

            try
            {
                if (grantedSet == null)
                {
                    if (throwException)
                        ThrowSecurityException(assemblyOrString, grantedSet, refusedSet, rmh, action, demand, demand);
                    else
                        return false;
                }
                
                else if (!grantedSet.IsUnrestricted())
                {
                    // If we aren't unrestricted, there is a refused set, or our permission is not of the unrestricted
                    // variety, we need to do the proper callback.

                    Contract.Assert(demand != null,"demand != null");

                    // Find the permission of matching type in the permission set.

                    CodeAccessPermission grantedPerm = 
                                (CodeAccessPermission)grantedSet.GetPermission(permToken);

                    // Make sure the demand has been granted
                    if (!demand.CheckDemand( grantedPerm ))
                    {
                        if (throwException)
                            ThrowSecurityException(assemblyOrString, grantedSet, refusedSet, rmh, action, demand, demand);
                        else
                            return false;
                    }
                }

                // Make the sure the permission is not refused.

                if (refusedSet != null)
                {
                    CodeAccessPermission refusedPerm = 
                        (CodeAccessPermission)refusedSet.GetPermission(permToken);
                    if (refusedPerm != null)
                    {
                        if (!refusedPerm.CheckDeny(demand))
                        {
        #if _DEBUG
                            if (debug)
                                DEBUG_OUT( "Permission found in refused set" );
        #endif
                                if (throwException)
                                    ThrowSecurityException(assemblyOrString, grantedSet, refusedSet, rmh, action, demand, demand);
                                else
                                    return false;

                        }
                    }

                    if (refusedSet.IsUnrestricted())
                    {
                        if (throwException)
                            ThrowSecurityException(assemblyOrString, grantedSet, refusedSet, rmh, action, demand, demand);
                        else
                            return false;
                    }
                }
            }
            catch (SecurityException)
            {
                throw;
            }
            catch (Exception)
            {
                // Any exception besides a security exception in this code means that
                // a permission was unable to properly handle what we asked of it.
                // We will define this to mean that the demand failed.
                if (throwException)
                    ThrowSecurityException(assemblyOrString, grantedSet, refusedSet, rmh, action, demand, demand);
                else
                    return false;
            }
            finally
            {
                if (bThreadSecurity)
                    SecurityManager._SetThreadSecurity(true);
            }

            DEBUG_OUT( "Check passed" );
            return true;
        }
コード例 #14
0
ファイル: PermissionSet.cs プロジェクト: zxlin25/mono
		public bool IsSubsetOf (PermissionSet target)
		{
			// if target is empty we must be empty too
			if ((target == null) || (target.IsEmpty ()))
				return this.IsEmpty ();

			// all permissions support unrestricted in 2.0
			if (target.IsUnrestricted ())
				return true;
			if (this.IsUnrestricted ())
				return false;

			if (this.IsUnrestricted () && ((target == null) || !target.IsUnrestricted ()))
				return false;

			// if each of our permission is (a) present and (b) a subset of target
			foreach (IPermission p in list) {
				// non CAS permissions must be evaluated for unrestricted
				Type t = p.GetType ();
				IPermission i = null;
				if (target.IsUnrestricted () && (p is CodeAccessPermission) && (p is IUnrestrictedPermission)) {
					i = (IPermission) Activator.CreateInstance (t, psUnrestricted);
				} else {
					i = target.GetPermission (t);
				}
				
				if (!p.IsSubsetOf (i))
					return false; // not a subset (condition b)
			}
			return true;
		}
コード例 #15
0
ファイル: PermissionSet.cs プロジェクト: l1183479157/coreclr
        public PermissionSet Intersect(PermissionSet other)
        {
            if (other == null || other.FastIsEmpty() || this.FastIsEmpty())
            {
                return null;
            }

            int thisMax = this.m_permSet == null ? -1 : this.m_permSet.GetMaxUsedIndex();
            int otherMax = other.m_permSet == null ? -1 : other.m_permSet.GetMaxUsedIndex();
            int minMax = thisMax < otherMax ? thisMax : otherMax;

            if (this.IsUnrestricted() && minMax < otherMax)
            {
                minMax = otherMax;
                this.CheckSet();
            }

            if (other.IsUnrestricted() && minMax < thisMax)
            {
                minMax = thisMax;
                other.CheckSet();
            }

            PermissionSet pset = new PermissionSet( false );

            if (minMax > -1)
            {
                pset.m_permSet = new TokenBasedSet();
            }

            for (int i = 0; i <= minMax; ++i)
            {
                Object thisObj = this.m_permSet.GetItem( i );
                IPermission thisPerm = thisObj as IPermission;
#if FEATURE_CAS_POLICY
                ISecurityElementFactory thisElem = thisObj as ISecurityElementFactory;
#endif // FEATURE_CAS_POLICY

                Object otherObj = other.m_permSet.GetItem( i );
                IPermission otherPerm = otherObj as IPermission;
#if FEATURE_CAS_POLICY
                ISecurityElementFactory otherElem = otherObj as ISecurityElementFactory;
#endif // FEATURE_CAS_POLICY

                if (thisObj == null && otherObj == null)
                    continue;

#if FEATURE_CAS_POLICY
                if (thisElem != null && otherElem != null)
                {
                    bool copyOther = true;
                    bool copyThis = true;
                    SecurityElement newElem = new SecurityElement( s_str_PermissionIntersection );
                    newElem.AddAttribute( "class", otherElem.Attribute( "class" ) );
                    if (this.IsUnrestricted())
                    {
                        SecurityElement newElemUU = new SecurityElement( s_str_PermissionUnrestrictedUnion );
                        newElemUU.AddAttribute( "class", thisElem.Attribute( "class" ) );
                        SafeChildAdd( newElemUU, thisElem, true );
                        copyThis = false;
                        thisElem = newElemUU;
                    }
                    if (other.IsUnrestricted())
                    {
                        SecurityElement newElemUU = new SecurityElement( s_str_PermissionUnrestrictedUnion );
                        newElemUU.AddAttribute( "class", otherElem.Attribute( "class" ) );
                        SafeChildAdd( newElemUU, otherElem, true );
                        copyOther = false;
                        otherElem = newElemUU;
                    }

                    SafeChildAdd( newElem, otherElem, copyOther );
                    SafeChildAdd( newElem, thisElem, copyThis );
                    pset.m_permSet.SetItem( i, newElem );
                }
                else
#endif // FEATURE_CAS_POLICY
                if (thisObj == null)
                {
                    if (this.m_Unrestricted)
                    {
#if FEATURE_CAS_POLICY
                        if (otherElem != null)
                        {
                            SecurityElement newElem = new SecurityElement( s_str_PermissionUnrestrictedIntersection );
                            newElem.AddAttribute( "class", otherElem.Attribute( "class" ) );
                            SafeChildAdd( newElem, otherElem, true );
                            pset.m_permSet.SetItem( i, newElem );
                            Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
                        }
                        else
#endif // FEATURE_CAS_POLICY
                        if (otherPerm != null)
                        {
                            PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
                            if ((token.m_type & PermissionTokenType.IUnrestricted) != 0)
                            {
                                pset.m_permSet.SetItem( i, otherPerm.Copy() );
                                Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
                            }
                        }
                    }
                }
                else if (otherObj == null)
                {
                    if (other.m_Unrestricted)
                    {
#if FEATURE_CAS_POLICY
                        if (thisElem != null)
                        {
                            SecurityElement newElem = new SecurityElement( s_str_PermissionUnrestrictedIntersection );
                            newElem.AddAttribute( "class", thisElem.Attribute( "class" ) );
                            SafeChildAdd( newElem, thisElem, true );
                            pset.m_permSet.SetItem( i, newElem );
                            Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
                        }
                        else
#endif // FEATURE_CAS_POLICY
                        if (thisPerm != null)
                        {
                            PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
                            if ((token.m_type & PermissionTokenType.IUnrestricted) != 0)
                            {
                                pset.m_permSet.SetItem( i, thisPerm.Copy() );
                                Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
                            }
                        }
                    }
                }
                else
                {
#if FEATURE_CAS_POLICY
                    if (thisElem != null)
                        thisPerm = this.CreatePermission(thisElem, i);
                    if (otherElem != null)
                        otherPerm = other.CreatePermission(otherElem, i);
#endif // FEATURE_CAS_POLICY

                    IPermission intersectPerm;
                    if (thisPerm == null)
                        intersectPerm = otherPerm;
                    else if(otherPerm == null)
                        intersectPerm = thisPerm;
                    else
                        intersectPerm = thisPerm.Intersect( otherPerm );
                    pset.m_permSet.SetItem( i, intersectPerm );
                    Contract.Assert( intersectPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
                }
            }

            pset.m_Unrestricted = this.m_Unrestricted && other.m_Unrestricted;
            if (pset.FastIsEmpty())
                return null;
            else
                return pset;
        }
コード例 #16
0
ファイル: PermissionSet.cs プロジェクト: l1183479157/coreclr
        internal void InplaceIntersect( PermissionSet other )
        {
            Exception savedException = null;
        
            m_CheckedForNonCas = false;
            
            if (this == other)
                return;
            
            if (other == null || other.FastIsEmpty())
            {
                // If the other is empty or null, make this empty.
                Reset();
                return;
            }

            if (this.FastIsEmpty())
                return;

            int maxMax = this.m_permSet == null ? -1 : this.m_permSet.GetMaxUsedIndex();
            int otherMax = other.m_permSet == null ? -1 : other.m_permSet.GetMaxUsedIndex();

            if (this.IsUnrestricted() && maxMax < otherMax)
            {
                maxMax = otherMax;
                this.CheckSet();
            }
                
            if (other.IsUnrestricted())
            {
                other.CheckSet();
            }
                
            for (int i = 0; i <= maxMax; ++i)
            {
                Object thisObj = this.m_permSet.GetItem( i );
                IPermission thisPerm = thisObj as IPermission;
#if FEATURE_CAS_POLICY
                ISecurityElementFactory thisElem = thisObj as ISecurityElementFactory;
#endif // FEATURE_CAS_POLICY

                Object otherObj = other.m_permSet.GetItem( i );
                IPermission otherPerm = otherObj as IPermission;
#if FEATURE_CAS_POLICY
                ISecurityElementFactory otherElem = otherObj as ISecurityElementFactory;
#endif // FEATURE_CAS_POLICY

                if (thisObj == null && otherObj == null)
                    continue;

#if FEATURE_CAS_POLICY
                if (thisElem != null && otherElem != null)
                {
                    // If we already have an intersection node, just add another child
                    if (thisElem.GetTag().Equals( s_str_PermissionIntersection ) ||
                        thisElem.GetTag().Equals( s_str_PermissionUnrestrictedIntersection ))
                    {
                        Contract.Assert( thisElem is SecurityElement, "SecurityElement expected" );
                        SafeChildAdd( (SecurityElement)thisElem, otherElem, true );
                    }
                    // If either set is unrestricted, intersect the nodes unrestricted
                    else
                    {
                        bool copyOther = true;
                        if (this.IsUnrestricted())
                        {
                            SecurityElement newElemUU = new SecurityElement( s_str_PermissionUnrestrictedUnion );
                            newElemUU.AddAttribute( "class", thisElem.Attribute( "class" ) );
                            SafeChildAdd( newElemUU, thisElem, false );
                            thisElem = newElemUU;
                        }
                        if (other.IsUnrestricted())
                        {
                            SecurityElement newElemUU = new SecurityElement( s_str_PermissionUnrestrictedUnion );
                            newElemUU.AddAttribute( "class", otherElem.Attribute( "class" ) );
                            SafeChildAdd( newElemUU, otherElem, true );
                            otherElem = newElemUU;
                            copyOther = false;
                        }
                        
                        SecurityElement newElem = new SecurityElement( s_str_PermissionIntersection );
                        newElem.AddAttribute( "class", thisElem.Attribute( "class" ) );
                        
                        SafeChildAdd( newElem, thisElem, false );
                        SafeChildAdd( newElem, otherElem, copyOther );
                        this.m_permSet.SetItem( i, newElem );
                    }
                }
                else
#endif // FEATURE_CAS_POLICY
                if (thisObj == null)
                {
                    // There is no object in <this>, so intersection is empty except for IUnrestrictedPermissions
                    if (this.IsUnrestricted())
                    {
#if FEATURE_CAS_POLICY
                        if (otherElem != null)
                        {
                            SecurityElement newElem = new SecurityElement( s_str_PermissionUnrestrictedIntersection );
                            newElem.AddAttribute( "class", otherElem.Attribute( "class" ) );
                            SafeChildAdd( newElem, otherElem, true );
                            this.m_permSet.SetItem( i, newElem );
                            Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
                        }
                        else
#endif // FEATURE_CAS_POLICY
                        {
                            PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
                            if ((token.m_type & PermissionTokenType.IUnrestricted) != 0)
                            {
                                this.m_permSet.SetItem( i, otherPerm.Copy() );
                                Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
                            }
                        }
                    }
                }
                else if (otherObj == null)
                {
                    if (other.IsUnrestricted())
                    {
#if FEATURE_CAS_POLICY
                        if (thisElem != null)
                        {
                            SecurityElement newElem = new SecurityElement( s_str_PermissionUnrestrictedIntersection );
                            newElem.AddAttribute( "class", thisElem.Attribute( "class" ) );
                            SafeChildAdd( newElem, thisElem, false );
                            this.m_permSet.SetItem( i, newElem );
                        }
                        else
#endif // FEATURE_CAS_POLICY
                        {
                            PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
                            if ((token.m_type & PermissionTokenType.IUnrestricted) == 0)
                                this.m_permSet.SetItem( i, null );
                        }
                    }
                    else
                    {
                        this.m_permSet.SetItem( i, null );
                    }
                }
                else
                {
#if FEATURE_CAS_POLICY
                    if (thisElem != null)
                        thisPerm = this.CreatePermission(thisElem, i);
                    if (otherElem != null)
                        otherPerm = other.CreatePermission(otherElem, i);
#endif // FEATURE_CAS_POLICY

                    try
                    {
                        IPermission intersectPerm;
                        if (thisPerm == null)
                            intersectPerm = otherPerm;
                        else if(otherPerm == null)
                            intersectPerm = thisPerm;
                        else
                            intersectPerm = thisPerm.Intersect( otherPerm );
                        this.m_permSet.SetItem( i, intersectPerm );
                    }
                    catch (Exception e)
                    {
                        if (savedException == null)
                            savedException = e;
                    }
                }
            }

            this.m_Unrestricted = this.m_Unrestricted && other.m_Unrestricted;

            if (savedException != null)
                throw savedException;
        }
コード例 #17
0
        [System.Security.SecurityCritical]  // auto-generated
        static private PermissionSet ResolvePolicy(Evidence evidence,
                                                   PermissionSet reqdPset,
                                                   PermissionSet optPset,
                                                   PermissionSet denyPset,
                                                   out PermissionSet denied,
                                                   bool checkExecutionPermission)
        {
            Contract.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled);

            if (executionSecurityPermission == null)
            {
                executionSecurityPermission = new SecurityPermission(SecurityPermissionFlag.Execution);
            }

            PermissionSet requested = null;
            PermissionSet optional;
            PermissionSet allowed;

            Exception savedException = null;

            // We don't want to recurse back into here as a result of a
            // stackwalk during resolution. So simply assert full trust (this
            // implies that custom permissions cannot use any permissions that
            // don't implement IUnrestrictedPermission.
            // PermissionSet.s_fullTrust.Assert();

            // The requested set is the union of the minimal request and the
            // optional request. Minimal request defaults to empty, optional
            // is "AllPossible" (includes any permission that can be defined)
            // which is symbolized by null.
            optional = optPset;

            if (reqdPset == null)
            {
                requested = optional;
            }
            else
            {
                // If optional is null, the requested set becomes null/"AllPossible".
                requested = optional == null ? null : reqdPset.Union(optional);
            }

            // Make sure that the right to execute is requested (if this feature is
            // enabled).

            if (requested != null && !requested.IsUnrestricted())
            {
                requested.AddPermission(executionSecurityPermission);
            }

            // If we aren't passed any evidence, just make an empty object
            if (evidence == null)
            {
                evidence = new Evidence();
            }

            allowed = polmgr.Resolve(evidence);
            // Intersect the grant with the RequestOptional
            if (requested != null)
            {
                allowed.InplaceIntersect(requested);
            }

            // Check that we were granted the right to execute.
            if (checkExecutionPermission)
            {
                if (!allowed.Contains(executionSecurityPermission) ||
                    (denyPset != null && denyPset.Contains(executionSecurityPermission)))
                {
                    throw new PolicyException(Environment.GetResourceString("Policy_NoExecutionPermission"),
                                              System.__HResults.CORSEC_E_NO_EXEC_PERM,
                                              savedException);
                }
            }

            // Check that we were granted at least the minimal set we asked for. Do
            // this before pruning away any overlap with the refused set so that
            // users have the flexability of defining minimal permissions that are
            // only expressable as set differences (e.g. allow access to "C:\" but
            // disallow "C:\Windows").
            if (reqdPset != null && !reqdPset.IsSubsetOf(allowed))
            {
                BCLDebug.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled, "Evaluating assembly level declarative security without legacy CAS policy enabled");
                throw new PolicyException(Environment.GetResourceString("Policy_NoRequiredPermission"),
                                          System.__HResults.CORSEC_E_MIN_GRANT_FAIL,
                                          savedException);
            }

            // Remove any granted permissions that are safe subsets of some denied
            // permission. The remaining denied permissions (if any) are returned
            // along with the modified grant set for use in checks.
            if (denyPset != null)
            {
                BCLDebug.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled, "Evaluating assembly level declarative security without legacy CAS policy enabled");
                denied = denyPset.Copy();
                allowed.MergeDeniedSet(denied);
                if (denied.IsEmpty())
                {
                    denied = null;
                }
            }
            else
            {
                denied = null;
            }

            allowed.IgnoreTypeLoadFailures = true;

            return(allowed);
        }
コード例 #18
0
 [System.Security.SecurityCritical]  // auto-generated
 internal void SetAssert(PermissionSet permSet)
 {            
     m_assertions = permSet.Copy();
     m_AssertFT = m_AssertFT || m_assertions.IsUnrestricted();
     IncrementAssertCount();
 }
コード例 #19
0
ファイル: PermissionSet.cs プロジェクト: zxlin25/mono
		public PermissionSet Intersect (PermissionSet other)
		{
			// no intersection possible
			if ((other == null) || (other.IsEmpty ()) || (this.IsEmpty ()))
				return null;

			PermissionState state = PermissionState.None;
			if (this.IsUnrestricted () && other.IsUnrestricted ())
				state = PermissionState.Unrestricted;

			PermissionSet interSet = null;
			// much simpler with 2.0
			if (state == PermissionState.Unrestricted) {
				interSet = new PermissionSet (state);
			} else if (this.IsUnrestricted ()) {
				interSet = other.Copy ();
			} else if (other.IsUnrestricted ()) {
				interSet = this.Copy ();
			} else {
				interSet = new PermissionSet (state);
				InternalIntersect (interSet, this, other, false);
			}
			return interSet;
		}
コード例 #20
0
ファイル: PluginManager.cs プロジェクト: phelom/Procon-1
        public void CompilePlugins(PermissionSet pluginSandboxPermissions, List<String> ignoredPluginClassNames = null) {
            try {

                if (File.Exists(Path.Combine(this.PluginBaseDirectory, "PluginCache.xml")) == true) {
                    WritePluginConsole("Loading plugin cache..");

                    try {
                        this.PluginCache = XDocument.Load(Path.Combine(this.PluginBaseDirectory, "PluginCache.xml")).Root.FromXElement<PluginCache>();
                    }
                    catch (Exception e) {
                        WritePluginConsole("Error loading plugin cache: {0}", e.Message);
                    }
                }

                // Recover from exceptions or logic errors if the document parsed correctly, but didn't deserialize correctly.
                if (this.PluginCache == null) {
                    this.PluginCache = new PluginCache();
                }

                // Make sure we ignore any plugins passed in. These won't even be loaded again.
                if (ignoredPluginClassNames != null) {
                    IgnoredPluginClassNames = ignoredPluginClassNames;
                }

                // Clear out all invocations if this is a reload.
                Invocations.Clear();

                WritePluginConsole("Preparing plugins directory..");
                PreparePluginsDirectory();

                WritePluginConsole("Moving legacy plugins..");
                MoveLegacyPlugins();

                WritePluginConsole("Creating compiler..");
                // CodeDomProvider pluginsCodeDomProvider = CodeDomProvider.CreateProvider("CSharp");
                var providerOptions = new Dictionary<String, String>();
                providerOptions.Add("CompilerVersion", "v3.5");
                CodeDomProvider pluginsCodeDomProvider = new CSharpCodeProvider(providerOptions);

                WritePluginConsole("Configuring compiler..");
                CompilerParameters parameters = GenerateCompilerParameters();
                // AppDomainSetup domainSetup = new AppDomainSetup() { ApplicationBase = this.PluginBaseDirectory };
                // Start of XpKillers mono workaround

                AppDomainSetup domainSetup = null;
                Type t = Type.GetType("Mono.Runtime");
                if (t != null) {
                    //Console.WriteLine("You are running with the Mono VM");
                    WritePluginConsole("Running with Mono VM..");
                    //AppDomain.CurrentDomain.BaseDirectory
                    domainSetup = new AppDomainSetup() {
                        ApplicationBase = AppDomain.CurrentDomain.BaseDirectory
                    };
                    domainSetup.PrivateBinPath = PluginBaseDirectory;
                }
                else {
                    // Console.WriteLine("You are running something else (native .Net)");
                    WritePluginConsole("Running with native .Net..");
                    domainSetup = new AppDomainSetup() {
                        ApplicationBase = PluginBaseDirectory
                    };
                }
                // Workaround end

                WritePluginConsole("Building sandbox..");
                var hostEvidence = new Evidence();
                hostEvidence.AddHost(new Zone(SecurityZone.MyComputer));

                AppDomainSandbox = AppDomain.CreateDomain(ProconClient.HostName + ProconClient.Port + "Engine", hostEvidence, domainSetup, pluginSandboxPermissions);

                WritePluginConsole("Configuring sandbox..");
                // create the factory class in the secondary app-domain
                PluginFactory = (CPRoConPluginLoaderFactory) AppDomainSandbox.CreateInstance("PRoCon.Core", "PRoCon.Core.Plugin.CPRoConPluginLoaderFactory").Unwrap();
                PluginCallbacks = new CPRoConPluginCallbacks(ProconClient.ExecuteCommand, ProconClient.GetAccountPrivileges, ProconClient.GetVariable, ProconClient.GetSvVariable, ProconClient.GetMapDefines, ProconClient.TryGetLocalized, RegisterCommand, UnregisterCommand, GetRegisteredCommands, ProconClient.GetWeaponDefines, ProconClient.GetSpecializationDefines, ProconClient.Layer.GetLoggedInAccounts, RegisterPluginEvents);

                WritePluginConsole("Compiling and loading plugins..");


                var pluginsDirectoryInfo = new DirectoryInfo(PluginBaseDirectory);

                foreach (FileInfo pluginFile in pluginsDirectoryInfo.GetFiles("*.cs")) {
                    string className = Regex.Replace(pluginFile.Name, "\\.cs$", "");

                    if (IgnoredPluginClassNames.Contains(className) == false) {
                        CompilePlugin(pluginFile, className, pluginsCodeDomProvider, parameters);

                        LoadPlugin(className, PluginFactory, pluginSandboxPermissions.IsUnrestricted());
                    }
                    else {
                        WritePluginConsole("Compiling {0}... ^1^bIgnored", className);
                    }
                }

                XDocument pluginCacheDocument = new XDocument(this.PluginCache.ToXElement());

                pluginCacheDocument.Save(Path.Combine(this.PluginBaseDirectory, "PluginCache.xml"));

                pluginsCodeDomProvider.Dispose();
            }
            catch (Exception e) {
                WritePluginConsole(e.Message);
            }
        }
コード例 #21
0
ファイル: PermissionSet.cs プロジェクト: zxlin25/mono
		public PermissionSet Union (PermissionSet other)
		{
			if (other == null)
				return this.Copy ();

			PermissionSet copy = null;
			if (this.IsUnrestricted () || other.IsUnrestricted ()) {
				// there are no child elements in unrestricted permission sets
				return new PermissionSet (PermissionState.Unrestricted);
			} else {
				copy = this.Copy ();
				// PermissionState.None -> copy all permissions
				foreach (IPermission p in other.list) {
					copy.AddPermission (p);
				}
			}
			return copy;
		}
コード例 #22
0
ファイル: permissionlistset.cs プロジェクト: ArildF/masters
        public bool CheckSetDemandInternal(PermissionSet permSet, out Exception exception, bool bNeedAlteredSet, out PermissionSet alteredSet)
        {
            alteredSet = null;

            BCLDebug.Assert(permSet != null, "permSet != null");
            
            // If the compressed stack is not unrestricted and the demand is
            // then we just throw an exception.
            if (!this.m_unrestricted && permSet.IsUnrestricted())
            {
                exception = new SecurityException(Environment.GetResourceString("Security_GenericNoType") );
                return false;
            }
            
            
            TokenBasedSet normalAlteredSet = null;
            TokenBasedSet unrestrictedAlteredSet = null;

            // Check the "normal" permissions since we always know we have to check them.

            bool normalContinue = CheckTokenBasedSets( this.m_normalPermSet, permSet.m_normalPermSet, false, PermissionListSetState.None, out exception, bNeedAlteredSet, out normalAlteredSet );

            if (exception != null)
            {
                return false;
            }
            
            bool unrestrictedContinue = CheckTokenBasedSets( this.m_unrestrictedPermSet, permSet.m_unrestrictedPermSet, m_unrestricted, m_state, out exception, bNeedAlteredSet, out unrestrictedAlteredSet );

            if (exception != null)
            {
                return false;
            }

            if ((m_state & PermissionListSetState.UnrestrictedAssert) != 0)
            {
                // If we are unrestricted, we want to terminate the stack walk based
                // on us having an unrestricted assert.

                if (bNeedAlteredSet)
                    unrestrictedAlteredSet = new TokenBasedSet( 1, 4 );
                unrestrictedContinue = false;
            }

            if (normalContinue || unrestrictedContinue)
            {
                if (!bNeedAlteredSet)
                    return true;

                // If we need to continue, let's build the altered set.  We only
                // need to do this if 1) our original demand is not unrestricted
                // and 2) if we have altered token based sets.

                if (!permSet.IsUnrestricted())
                {
                    if (normalAlteredSet != null || unrestrictedAlteredSet != null)
                    {
                        alteredSet = new PermissionSet( false );

                        if (normalAlteredSet != null)
                            alteredSet.m_normalPermSet = normalAlteredSet;
                        else
                            alteredSet.m_normalPermSet = CopyTokenBasedSet( permSet.m_normalPermSet );

                        if (unrestrictedAlteredSet != null)
                            alteredSet.m_unrestrictedPermSet = unrestrictedAlteredSet;
                        else
                            alteredSet.m_unrestrictedPermSet = CopyTokenBasedSet( permSet.m_unrestrictedPermSet );

                        if (alteredSet.IsEmpty())
                            return false;
                    }
                }

                return true;
            }
            else
            {
                return false;
            }
        }
コード例 #23
0
		private void Compare (string msg, PermissionSet ps, bool unrestricted, int count)
		{
			Assert.IsNotNull (ps, msg + "-NullCheck");
			Assert.IsTrue ((ps.IsUnrestricted () == unrestricted), msg + "-State");
			Assert.AreEqual (count, ps.Count, msg + "-Count");
		}
コード例 #24
0
ファイル: isolatedstoragefile.cs プロジェクト: ArildF/masters
        /// <include file='doc\IsolatedStorageFile.uex' path='docs/doc[@for="IsolatedStorageFile.GetPermission"]/*' />
        protected override IsolatedStoragePermission GetPermission(
                PermissionSet ps)
        {
            if (ps == null)
                return null;
            else if (ps.IsUnrestricted())
                return new IsolatedStorageFilePermission(
                        PermissionState.Unrestricted);

            return (IsolatedStoragePermission) ps.
                    GetPermission(typeof(IsolatedStorageFilePermission));
        }
コード例 #25
0
		public void SetPermission_None ()
		{
			PermissionSet ps = new PermissionSet (PermissionState.None);
			Assert.AreEqual (0, ps.Count, "Empty");
			Assert.IsTrue (!ps.IsUnrestricted (), "State-None");

			SecurityPermission sp = new SecurityPermission (PermissionState.Unrestricted);
			SecurityPermission result = (SecurityPermission)ps.SetPermission (sp);
			Assert.AreEqual (1, ps.Count, "SecurityPermission");
			Assert.AreEqual (SecurityPermissionFlag.AllFlags, result.Flags, "Flags");
			Assert.IsTrue (!ps.IsUnrestricted (), "State-None-2");

			sp = new SecurityPermission (SecurityPermissionFlag.ControlAppDomain);
			result = (SecurityPermission)ps.SetPermission (sp);
			Assert.AreEqual (1, ps.Count, "SecurityPermission-2");
			Assert.AreEqual (SecurityPermissionFlag.ControlAppDomain, result.Flags, "Flags");

			ZoneIdentityPermission zip = new ZoneIdentityPermission (SecurityZone.MyComputer);
			ZoneIdentityPermission zipr = (ZoneIdentityPermission) ps.SetPermission (zip);
			Assert.AreEqual (2, ps.Count, "ZoneIdentityPermission");
			Assert.AreEqual (SecurityZone.MyComputer, zipr.SecurityZone, "SecurityZone");

			zip = new ZoneIdentityPermission (SecurityZone.Intranet);
			zipr = (ZoneIdentityPermission)ps.SetPermission (zip);
			Assert.AreEqual (2, ps.Count, "ZoneIdentityPermission");
			Assert.AreEqual (SecurityZone.Intranet, zipr.SecurityZone, "SecurityZone");
		}
コード例 #26
0
		public void AddPermission_PermissionUnrestricted ()
		{
			PermissionSet ps = new PermissionSet (PermissionState.None);
			SecurityPermission sp = new SecurityPermission (PermissionState.Unrestricted);
			IPermission result = ps.AddPermission (sp);
			Assert.IsNotNull (result, "Add(SecurityPermission)");
			Assert.AreEqual (SecurityPermissionFlag.AllFlags, (result as SecurityPermission).Flags, "SecurityPermission");
			Assert.AreEqual (1, ps.Count, "1");
			Assert.IsTrue (!ps.IsUnrestricted (), "State");
		}
コード例 #27
0
ファイル: SecurityManager.cs プロジェクト: shana/mono
		internal static IPermission CheckPermissionSet (AppDomain ad, PermissionSet ps)
		{
			if ((ps == null) || ps.IsEmpty ())
				return null;

			PermissionSet granted = ad.GrantedPermissionSet;
			if (granted == null)
				return null;
			if (granted.IsUnrestricted ())
				return null;
			if (ps.IsUnrestricted ())
				return new SecurityPermission (SecurityPermissionFlag.NoFlags);

			foreach (IPermission p in ps) {
				if (p is CodeAccessPermission) {
					CodeAccessPermission grant = (CodeAccessPermission) granted.GetPermission (p.GetType ());
					if (grant == null) {
						if (!granted.IsUnrestricted () || !(p is IUnrestrictedPermission)) {
							if (!p.IsSubsetOf (null))
								return p;
						}
					} else if (!p.IsSubsetOf (grant)) {
						return p;
					}
				} else {
					// but non-CAS will throw on failure...
					try {
						p.Demand ();
					}
					catch (SecurityException) {
						// ... so we catch
						return p;
					}
				}
			}
			return null;
		}
コード例 #28
0
        private static void CheckSetHelper(PermissionSet grants,
                                           PermissionSet denied,
                                           PermissionSet demands)
        {

    #if _DEBUG
            if (debug)
            {
                DEBUG_OUT("Granted: ");
                DEBUG_OUT(grants.ToXml().ToString());
                DEBUG_OUT("Denied: ");
                DEBUG_OUT(denied!=null ? denied.ToXml().ToString() : "<null>");
                DEBUG_OUT("Demanded: ");
                DEBUG_OUT(demands!=null ? demands.ToXml().ToString() : "<null>");
            }
    #endif

            if (demands == null || demands.IsEmpty())
                return;  // demanding the empty set always passes.

            if (grants == null)
            {
                throw new SecurityException(Environment.GetResourceString("Security_GenericNoType"));
            }
            
            if (!grants.IsUnrestricted() || (denied != null))
            {
                if (demands.IsUnrestricted())
                {
                    throw new SecurityException(Environment.GetResourceString("Security_GenericNoType"));
                }
                
                CheckTokenBasedSetHelper( grants.IsUnrestricted(), grants.m_unrestrictedPermSet, denied != null ? denied.m_unrestrictedPermSet : null, demands.m_unrestrictedPermSet );
            }
            
            CheckTokenBasedSetHelper( false, grants.m_normalPermSet, denied != null ? denied.m_normalPermSet : null, demands.m_normalPermSet );
        }
コード例 #29
0
        internal static int GetSpecialFlags(PermissionSet grantSet, PermissionSet deniedSet)
        {
            if ((grantSet != null && grantSet.IsUnrestricted()) && (deniedSet == null || deniedSet.IsEmpty()))
            {
                return(-1);
            }
            else
            {
                SecurityPermission securityPermission = null;
#pragma warning disable 618
                SecurityPermissionFlag securityPermissionFlags = SecurityPermissionFlag.NoFlags;
#pragma warning restore 618
                ReflectionPermission     reflectionPermission      = null;
                ReflectionPermissionFlag reflectionPermissionFlags = ReflectionPermissionFlag.NoFlags;

                CodeAccessPermission[] specialPermissions = new CodeAccessPermission[6];
                if (grantSet != null)
                {
                    if (grantSet.IsUnrestricted())
                    {
                        securityPermissionFlags   = SecurityPermissionFlag.AllFlags;
                        reflectionPermissionFlags = ReflectionPermission.AllFlagsAndMore;
                        for (int i = 0; i < specialPermissions.Length; i++)
                        {
                            specialPermissions[i] = s_UnrestrictedSpecialPermissionMap[i];
                        }
                    }
                    else
                    {
                        securityPermission = grantSet.GetPermission(BuiltInPermissionIndex.SecurityPermissionIndex) as SecurityPermission;
                        if (securityPermission != null)
                        {
                            securityPermissionFlags = securityPermission.Flags;
                        }
                        reflectionPermission = grantSet.GetPermission(BuiltInPermissionIndex.ReflectionPermissionIndex) as ReflectionPermission;
                        if (reflectionPermission != null)
                        {
                            reflectionPermissionFlags = reflectionPermission.Flags;
                        }
                        for (int i = 0; i < specialPermissions.Length; i++)
                        {
                            specialPermissions[i] = grantSet.GetPermission(s_BuiltInPermissionIndexMap[i][0]) as CodeAccessPermission;
                        }
                    }
                }

                if (deniedSet != null)
                {
                    if (deniedSet.IsUnrestricted())
                    {
                        securityPermissionFlags   = SecurityPermissionFlag.NoFlags;
                        reflectionPermissionFlags = ReflectionPermissionFlag.NoFlags;
                        for (int i = 0; i < s_BuiltInPermissionIndexMap.Length; i++)
                        {
                            specialPermissions[i] = null;
                        }
                    }
                    else
                    {
                        securityPermission = deniedSet.GetPermission(BuiltInPermissionIndex.SecurityPermissionIndex) as SecurityPermission;
                        if (securityPermission != null)
                        {
                            securityPermissionFlags &= ~securityPermission.Flags;
                        }
                        reflectionPermission = deniedSet.GetPermission(BuiltInPermissionIndex.ReflectionPermissionIndex) as ReflectionPermission;
                        if (reflectionPermission != null)
                        {
                            reflectionPermissionFlags &= ~reflectionPermission.Flags;
                        }
                        for (int i = 0; i < s_BuiltInPermissionIndexMap.Length; i++)
                        {
                            CodeAccessPermission deniedSpecialPermission = deniedSet.GetPermission(s_BuiltInPermissionIndexMap[i][0]) as CodeAccessPermission;
                            if (deniedSpecialPermission != null && !deniedSpecialPermission.IsSubsetOf(null))
                            {
                                specialPermissions[i] = null; // we don't care about the exact value here.
                            }
                        }
                    }
                }
                int flags = MapToSpecialFlags(securityPermissionFlags, reflectionPermissionFlags);
                if (flags != -1)
                {
                    for (int i = 0; i < specialPermissions.Length; i++)
                    {
                        if (specialPermissions[i] != null && ((IUnrestrictedPermission)specialPermissions[i]).IsUnrestricted())
                        {
                            flags |= (1 << (int)s_BuiltInPermissionIndexMap[i][1]);
                        }
                    }
                }
                return(flags);
            }
        }
コード例 #30
0
		public void PermissionSetPermissionSet () 
		{
			FileDialogPermission fdp = new FileDialogPermission (FileDialogPermissionAccess.Open);
			PermissionSet ps1 = new PermissionSet (PermissionState.None);
			ps1.AddPermission (fdp);
			Assert.IsTrue (!ps1.IsEmpty (), "ps1.IsEmpty");

			PermissionSet ps = new PermissionSet (ps1);
			Assert.IsTrue (!ps.IsUnrestricted (), "PermissionSetPermissionSet.IsUnrestricted");
			Assert.IsTrue (!ps.IsEmpty (), "PermissionSetPermissionSet.IsEmpty");
			Assert.IsTrue (!ps.IsReadOnly, "PermissionSetPermissionSet.IsReadOnly");
			Assert.AreEqual (ps.ToXml ().ToString (), ps.ToString (), "PermissionSetPermissionSet.ToXml().ToString()==ToString()");
			Assert.IsTrue (!ps.ContainsNonCodeAccessPermissions (), "ContainsNonCodeAccessPermissions");
		}
コード例 #31
0
        private static void CheckHelper(PermissionSet grantedSet,
                                        PermissionSet deniedSet,
                                        CodeAccessPermission demand, 
                                        PermissionToken permToken)
        {
    #if _DEBUG
            if (debug)
            {
                DEBUG_OUT("Granted: ");
                DEBUG_OUT(grantedSet.ToXml().ToString());
                DEBUG_OUT("Denied: ");
                DEBUG_OUT(deniedSet!=null ? deniedSet.ToXml().ToString() : "<null>");
                DEBUG_OUT("Demanded: ");
                DEBUG_OUT(demand.ToString());
            }
    #endif
            
            if (permToken == null)
                permToken = PermissionToken.GetToken(demand);

            // If PermissionSet is null, then module does not have Permissions... Fail check.
            
            try
            {
                if (grantedSet == null)
                {
                    throw new SecurityException(Environment.GetResourceString("Security_GenericNoType"));
                } 
                else if (!grantedSet.IsUnrestricted() || !(demand is IUnrestrictedPermission))
                {
                    // If we aren't unrestricted, there is a denied set, or our permission is not of the unrestricted
                    // variety, we need to do the proper callback.
                
                    BCLDebug.Assert(demand != null,"demand != null");
                    
                    // Find the permission of matching type in the permission set.
                    
                    CodeAccessPermission grantedPerm = 
                                (CodeAccessPermission)grantedSet.GetPermission(permToken);
                                
                    // If there isn't a matching permission in the set and our demand is not a subset of null (i.e. empty)
                    // then throw an exception.
                                
                    if (grantedPerm == null)
                    {
                        if (!demand.IsSubsetOf( null ))
                            throw new SecurityException(String.Format(Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName), demand.GetType(), demand.ToXml().ToString());
                        else
                            return;
                    }
                    
                    // Call the check demand for our permission.
                    
                    grantedPerm.CheckDemand(demand);
                }
                
                
                // Make the sure the permission is not denied.
    
                if (deniedSet != null)
                {
                    CodeAccessPermission deniedPerm = 
                        (CodeAccessPermission)deniedSet.GetPermission(permToken);
                    if (deniedPerm != null)
                    {
                        if (deniedPerm.Intersect(demand) != null)
                        {
        #if _DEBUG
                            if (debug)
                                DEBUG_OUT( "Permission found in denied set" );
        #endif
                            throw new SecurityException(String.Format(Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName), demand.GetType(), demand.ToXml().ToString());
                        }
                    }
                }
            }
            catch (Exception e)
            {
                // Any exception besides a security exception in this code means that
                // a permission was unable to properly handle what we asked of it.
                // We will define this to mean that the demand failed.
                        
                if (e is SecurityException)
                    throw e;
                else
                    throw new SecurityException(String.Format(Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName), demand.GetType(), demand.ToXml().ToString());
            }

            
            DEBUG_OUT( "Check passed" );

        }
コード例 #32
0
        internal static int GetSpecialFlags (PermissionSet grantSet, PermissionSet deniedSet) {
            if ((grantSet != null && grantSet.IsUnrestricted()) && (deniedSet == null || deniedSet.IsEmpty())) {
                return -1;
            }
            else {
                SecurityPermission securityPermission = null;
#pragma warning disable 618
                SecurityPermissionFlag securityPermissionFlags = SecurityPermissionFlag.NoFlags;
#pragma warning restore 618
                ReflectionPermission reflectionPermission = null;
                ReflectionPermissionFlag reflectionPermissionFlags = ReflectionPermissionFlag.NoFlags;

                CodeAccessPermission[] specialPermissions = new CodeAccessPermission[6];
                if (grantSet != null) {
                    if (grantSet.IsUnrestricted()) {
                        securityPermissionFlags = SecurityPermissionFlag.AllFlags;
                        reflectionPermissionFlags = ReflectionPermission.AllFlagsAndMore;
                        for (int i = 0; i < specialPermissions.Length; i++) {
                            specialPermissions[i] = s_UnrestrictedSpecialPermissionMap[i];
                        }
                    }
                    else {
                        securityPermission = grantSet.GetPermission(BuiltInPermissionIndex.SecurityPermissionIndex) as SecurityPermission;
                        if (securityPermission != null)
                            securityPermissionFlags = securityPermission.Flags;
                        reflectionPermission = grantSet.GetPermission(BuiltInPermissionIndex.ReflectionPermissionIndex) as ReflectionPermission;
                        if (reflectionPermission != null)
                            reflectionPermissionFlags = reflectionPermission.Flags;
                        for (int i = 0; i < specialPermissions.Length; i++) {
                            specialPermissions[i] = grantSet.GetPermission(s_BuiltInPermissionIndexMap[i][0]) as CodeAccessPermission;
                        }
                    }
                }

                if (deniedSet != null) {
                    if (deniedSet.IsUnrestricted()) {
                        securityPermissionFlags = SecurityPermissionFlag.NoFlags;
                        reflectionPermissionFlags = ReflectionPermissionFlag.NoFlags;
                        for (int i = 0; i < s_BuiltInPermissionIndexMap.Length; i++) {
                            specialPermissions[i] = null;
                        }
                    }
                    else {
                        securityPermission = deniedSet.GetPermission(BuiltInPermissionIndex.SecurityPermissionIndex) as SecurityPermission;
                        if (securityPermission != null)
                            securityPermissionFlags &= ~securityPermission.Flags;
                        reflectionPermission = deniedSet.GetPermission(BuiltInPermissionIndex.ReflectionPermissionIndex) as ReflectionPermission;
                        if (reflectionPermission != null)
                            reflectionPermissionFlags &= ~reflectionPermission.Flags;
                        for (int i = 0; i < s_BuiltInPermissionIndexMap.Length; i++) {
                            CodeAccessPermission deniedSpecialPermission = deniedSet.GetPermission(s_BuiltInPermissionIndexMap[i][0]) as CodeAccessPermission;
                            if (deniedSpecialPermission != null && !deniedSpecialPermission.IsSubsetOf(null))
                                specialPermissions[i] = null; // we don't care about the exact value here.
                        }
                    }
                }
                int flags = MapToSpecialFlags(securityPermissionFlags, reflectionPermissionFlags);
                if (flags != -1) {
                    for (int i = 0; i < specialPermissions.Length; i++) {
                        if (specialPermissions[i] != null && ((IUnrestrictedPermission) specialPermissions[i]).IsUnrestricted())
                            flags |= (1 << (int) s_BuiltInPermissionIndexMap[i][1]);
                    }
                }
                return flags;
            }
        }
コード例 #33
0
        [System.Security.SecurityCritical]  // auto-generated
        static bool CheckAssert(PermissionSet pSet, CodeAccessPermission demand, PermissionToken permToken)
        {
            if (pSet != null)
            {
                pSet.CheckDecoded(demand, permToken);

                CodeAccessPermission perm = (CodeAccessPermission)pSet.GetPermission(demand);
            
                // If the assert set does contain the demanded permission, halt the stackwalk

                try
                {
                    if (pSet.IsUnrestricted() || demand.CheckAssert(perm))
                    {
                        return SecurityRuntime.StackHalt;
                    }
                }
                catch (ArgumentException)
                {
                }
            }
            return SecurityRuntime.StackContinue;
        }
コード例 #34
0
ファイル: SecurityManager.cs プロジェクト: shana/mono
		internal static void ResolveIdentityPermissions (PermissionSet ps, Evidence evidence)
		{
			// in 2.0 identity permissions can now be unrestricted
			if (ps.IsUnrestricted ())
				return;

			// Only host evidence are used for policy resolution
			IEnumerator ee = evidence.GetHostEnumerator ();
			while (ee.MoveNext ()) {
				IIdentityPermissionFactory ipf = (ee.Current as IIdentityPermissionFactory);
				if (ipf != null) {
					IPermission p = ipf.CreateIdentityPermission (evidence);
					ps.AddPermission (p);
				}
			}
		}
コード例 #35
0
ファイル: PermissionListSet.cs プロジェクト: shrah/coreclr
        private bool Update2(PermissionSetTriple currentTriple, FrameSecurityDescriptor fsd, bool fDeclarative)
        {
            // Deny
            PermissionSet deniedPset = fsd.GetDenials(fDeclarative);

            if (deniedPset != null)
            {
                currentTriple.UpdateRefused(deniedPset);
            }

            // permit only
            PermissionSet permitOnlyPset = fsd.GetPermitOnly(fDeclarative);

            if (permitOnlyPset != null)
            {
                currentTriple.UpdateGrant(permitOnlyPset);
            }

            // Assert all possible
            if (fsd.GetAssertAllPossible())
            {
                // If we have no grant set, it means that the only assembly we've seen on the stack so
                // far is mscorlib. Since mscorlib will always be fully trusted, the grant set of the
                // compressed stack is also FullTrust.
                if (currentTriple.GrantSet == null)
                {
                    currentTriple.GrantSet = PermissionSet.s_fullTrust;
                }

                UpdateTripleListAndCreateNewTriple(currentTriple, m_permSetTriples);
                currentTriple.GrantSet = PermissionSet.s_fullTrust;
                currentTriple.UpdateAssert(fsd.GetAssertions(fDeclarative));
                return(true);
            }

            // Assert
            PermissionSet assertPset = fsd.GetAssertions(fDeclarative);

            if (assertPset != null)
            {
                if (assertPset.IsUnrestricted())
                {
                    // If we have no grant set, it means that the only assembly we've seen on the stack so
                    // far is mscorlib. Since mscorlib will always be fully trusted, the grant set of the
                    // compressed stack is also FullTrust.
                    if (currentTriple.GrantSet == null)
                    {
                        currentTriple.GrantSet = PermissionSet.s_fullTrust;
                    }

                    UpdateTripleListAndCreateNewTriple(currentTriple, m_permSetTriples);
                    currentTriple.GrantSet = PermissionSet.s_fullTrust;
                    currentTriple.UpdateAssert(assertPset);
                    return(true);
                }

                PermissionSetTriple retTriple = currentTriple.UpdateAssert(assertPset);
                if (retTriple != null)
                {
                    EnsureTriplesListCreated();
                    m_permSetTriples.Add(retTriple);
                }
            }

            return(false);
        }