ToXml() public method

public ToXml ( ) : SecurityElement
return SecurityElement
示例#1
0
        public void AddTo(CodeGen code_gen, PEAPI.MetaDataElement elem)
        {
            System.Text.UnicodeEncoding ue = new System.Text.UnicodeEncoding();
            foreach (DictionaryEntry entry in permissionset_table)
            {
                PEAPI.SecurityAction sec_action = (PEAPI.SecurityAction)entry.Key;
                SSPermissionSet      ps         = (SSPermissionSet)entry.Value;

                code_gen.PEFile.AddDeclSecurity(sec_action,
                                                ue.GetBytes(ps.ToXml().ToString()),
                                                elem);
            }

            if (permissionset20_table == null)
            {
                return;
            }

            foreach (DictionaryEntry entry in permissionset20_table)
            {
                PEAPI.SecurityAction sec_action = (PEAPI.SecurityAction)entry.Key;
                MIPermissionSet      ps         = (MIPermissionSet)entry.Value;

                code_gen.PEFile.AddDeclSecurity(sec_action,
                                                ps.Resolve(code_gen),
                                                elem);
            }
        }
		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 ());
		}
		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");
		}
示例#4
0
		public void PermissionSetNull () 
		{
			// no exception is thrown
			PermissionSet ps = new PermissionSet (null);
			Assert.IsTrue (!ps.IsUnrestricted (), "PermissionStateNull.IsUnrestricted");
			Assert.IsTrue (ps.IsEmpty (), "PermissionStateNull.IsEmpty");
			Assert.IsTrue (!ps.IsReadOnly, "PermissionStateNull.IsReadOnly");
			Assert.AreEqual (ps.ToXml ().ToString (), ps.ToString (), "PermissionStateNull.ToXml().ToString()==ToString()");
			Assert.IsTrue (!ps.ContainsNonCodeAccessPermissions (), "ContainsNonCodeAccessPermissions");
		}
		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 ());
		}
        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);
        }
		public void ToXmlUnrestricted () 
		{
			PermissionSet ps = new PermissionSet (PermissionState.Unrestricted);
			SecurityElement se = ps.ToXml ();
			Assert ("Unrestricted.ToString().StartsWith", ps.ToString().StartsWith ("<PermissionSet"));
			AssertEquals ("Unrestricted.class", "System.Security.PermissionSet", (se.Attributes ["class"] as string));
			AssertEquals ("Unrestricted.version", "1", (se.Attributes ["version"] as string));
			AssertEquals ("Unrestricted.Unrestricted", "true", (se.Attributes ["Unrestricted"] as string));
		}
		public void FromXmlInvalidPermission () 
		{
			PermissionSet ps = new PermissionSet (PermissionState.None);
			SecurityElement se = ps.ToXml ();
			// can't modify - so we create our own
			SecurityElement se2 = new SecurityElement ("InvalidPermissionSet", se.Text);
			se2.AddAttribute ("class", se.Attribute ("class"));
			se2.AddAttribute ("version", se.Attribute ("version"));
			ps.FromXml (se2);
		}
示例#9
0
		internal void AddPermissionRequests (PermissionSet required, PermissionSet optional, PermissionSet refused)
		{
#if !NET_2_1
			if (created)
				throw new InvalidOperationException ("Assembly was already saved.");

			// required for base Assembly class (so the permissions
			// can be used even if the assembly isn't saved to disk)
			_minimum = required;
			_optional = optional;
			_refuse = refused;

			// required to reuse AddDeclarativeSecurity support 
			// already present in the runtime
			if (required != null) {
				permissions_minimum = new RefEmitPermissionSet [1];
				permissions_minimum [0] = new RefEmitPermissionSet (
					SecurityAction.RequestMinimum, required.ToXml ().ToString ());
			}
			if (optional != null) {
				permissions_optional = new RefEmitPermissionSet [1];
				permissions_optional [0] = new RefEmitPermissionSet (
					SecurityAction.RequestOptional, optional.ToXml ().ToString ());
			}
			if (refused != null) {
				permissions_refused = new RefEmitPermissionSet [1];
				permissions_refused [0] = new RefEmitPermissionSet (
					SecurityAction.RequestRefuse, refused.ToXml ().ToString ());
			}
#endif
		}
示例#10
0
 [System.Security.SecuritySafeCritical]  // auto-generated 
 public SecurityException(string message, AssemblyName assemblyName, PermissionSet grant, PermissionSet refused, MethodInfo method, SecurityAction action, Object demanded, IPermission permThatFailed, Evidence evidence)
     : base(message) 
 {
     PermissionSet.s_fullTrust.Assert();
     SetErrorCode(System.__HResults.COR_E_SECURITY);
     Action = action; 
     if(permThatFailed != null)
         m_typeOfPermissionThatFailed = permThatFailed.GetType(); 
     FirstPermissionThatFailed = permThatFailed; 
     Demanded = demanded;
     m_granted = (grant == null ? "" : grant.ToXml().ToString()); 
     m_refused = (refused == null ? "" : refused.ToXml().ToString());
     m_denied = "";
     m_permitOnly = "";
     m_assemblyName = assemblyName; 
     Method = method;
     m_url = ""; 
     m_zone = SecurityZone.NoZone; 
     if(evidence != null)
     { 
         Url url = evidence.GetHostEvidence<Url>();
         if(url != null)
             m_url = url.GetURLString().ToString();
         Zone zone = evidence.GetHostEvidence<Zone>(); 
         if(zone != null)
             m_zone = zone.SecurityZone; 
     } 
     m_debugString = this.ToString(true, false);
 } 
        [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;
        }
        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);
        }
示例#13
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" );

        }
        ConvertPermissionSet(String inFormat,
                             byte[] inData,
                             String outFormat)
        {
            if(inData == null) 
                return null;
            if(inFormat == null)
                throw new ArgumentNullException("inFormat");
            if(outFormat == null)
                throw new ArgumentNullException("outFormat");
    
            PermissionSet permSet = new PermissionSet( false );
    
            inFormat = String.SmallCharToUpper(inFormat);
            outFormat = String.SmallCharToUpper(outFormat);

            if (inFormat.Equals( "XMLASCII" ) || inFormat.Equals( "XML" ))
            {
                permSet.FromXml( new Parser( inData, Tokenizer.ByteTokenEncoding.ByteTokens ).GetTopElement() );
            }
            else if (inFormat.Equals( "XMLUNICODE" ))
            {
                permSet.FromXml( new Parser( inData, Tokenizer.ByteTokenEncoding.UnicodeTokens ).GetTopElement() );
            }
            else if (inFormat.Equals( "BINARY" ))
            {
                permSet.DecodeUsingSerialization( inData );
            }
            else
            {
                return null;
            }
            
            if (outFormat.Equals( "XMLASCII" ) || outFormat.Equals( "XML" ))
            {
                MemoryStream ms = new MemoryStream();
                StreamWriter writer = new StreamWriter( ms, Encoding.ASCII );
                writer.Write( permSet.ToXml().ToString() );
                writer.Flush();
                return ms.ToArray();
            }
            else if (outFormat.Equals( "XMLUNICODE" ))
            {
                MemoryStream ms = new MemoryStream();
                StreamWriter writer = new StreamWriter( ms, Encoding.Unicode );
                writer.Write( permSet.ToXml().ToString() );
                writer.Flush();

                ms.Position = 2;
                int countBytes = (int)ms.Length - 2;
                byte[] retval = new byte[countBytes];
                ms.Read( retval, 0, retval.Length );
                return retval;
            }
            else if (outFormat.Equals( "BINARY" ))
            {
                return permSet.EncodeUsingSerialization();
            }
            else
            {
                return null;
            }
        }
        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());
                        }
                    }

                    if (deniedSet.IsUnrestricted() && (demand is IUnrestrictedPermission))
                    {
                        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");
        }
 private static PermissionSet RemoveNonReferencedPermissions(string[] setToFilter, ITaskItem[] dependencies)
 {
     PermissionSet set = new PermissionSet(PermissionState.None);
     if (((dependencies == null) || (setToFilter == null)) || (setToFilter.Length == 0))
     {
         return set;
     }
     List<string> list = new List<string>();
     foreach (ITaskItem item in dependencies)
     {
         AssemblyName assemblyName = AssemblyName.GetAssemblyName(item.ItemSpec);
         list.Add(assemblyName.Name + ", " + assemblyName.Version.ToString());
     }
     SecurityElement permissionSetXml = set.ToXml();
     foreach (string str in setToFilter)
     {
         string str2;
         string str3;
         string str4;
         if ((!string.IsNullOrEmpty(str) && ParseElementForAssemblyIdentification(SecurityElement.FromString(str), out str3, out str2, out str4)) && list.Contains(str2 + ", " + str4))
         {
             permissionSetXml.AddChild(SecurityElement.FromString(str));
         }
     }
     return new ReadOnlyPermissionSet(permissionSetXml);
 }
示例#17
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);
        }
示例#18
0
        // Convert a permission set from one format to another.
        public static byte[] ConvertPermissionSet
            (String inFormat, byte[] inData, String outFormat)
        {
            // Validate the parameters.
            if (inFormat == null)
            {
                throw new ArgumentNullException("inFormat");
            }
            if (inData == null)
            {
                throw new ArgumentNullException("inData");
            }
            if (outFormat == null)
            {
                throw new ArgumentNullException("outFormat");
            }

            // Convert the input data into a permission set.
            PermissionSet   permSet;
            SecurityElement e;

            switch (inFormat.ToLower(CultureInfo.InvariantCulture))
            {
            case "xml":
            case "xmlascii":
            {
                permSet = new PermissionSet(PermissionState.None);
                e       = (new MiniXml(Encoding.UTF8.GetString(inData)))
                          .Parse();
                permSet.FromXml(e);
            }
            break;

            case "xmlunicode":
            {
                permSet = new PermissionSet(PermissionState.None);
                e       = (new MiniXml(Encoding.Unicode.GetString(inData)))
                          .Parse();
                permSet.FromXml(e);
            }
            break;

                                #if CONFIG_SERIALIZATION
            case "binary":
            {
                MemoryStream inStream = new MemoryStream(inData);
                permSet = (PermissionSet)
                          ((new BinaryFormatter()).Deserialize(inStream));
            }
            break;
                                #endif

            default: return(null);
            }

            // Convert the output data into a permission set.
            switch (outFormat.ToLower(CultureInfo.InvariantCulture))
            {
            case "xml":
            case "xmlascii":
            {
                e = permSet.ToXml();
                return(Encoding.UTF8.GetBytes(e.ToString()));
            }
            // Not reached.

            case "xmlunicode":
            {
                e = permSet.ToXml();
                return(Encoding.Unicode.GetBytes(e.ToString()));
            }
                // Not reached.

                                #if CONFIG_SERIALIZATION
            case "binary":
            {
                MemoryStream outStream = new MemoryStream();
                (new BinaryFormatter()).Serialize(outStream, permSet);
                return(outStream.ToArray());
            }
                // Not reached.
                                #endif
            }
            return(null);
        }
示例#19
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;
        }
示例#20
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 );
        }
 public SecurityException(string message, AssemblyName assemblyName, PermissionSet grant, PermissionSet refused, MethodInfo method, SecurityAction action, object demanded, IPermission permThatFailed, Evidence evidence) : base(message)
 {
     PermissionSet.s_fullTrust.Assert();
     base.SetErrorCode(-2146233078);
     this.Action = action;
     if (permThatFailed != null)
     {
         this.m_typeOfPermissionThatFailed = permThatFailed.GetType();
     }
     this.FirstPermissionThatFailed = permThatFailed;
     this.Demanded = demanded;
     this.m_granted = (grant == null) ? "" : grant.ToXml().ToString();
     this.m_refused = (refused == null) ? "" : refused.ToXml().ToString();
     this.m_denied = "";
     this.m_permitOnly = "";
     this.m_assemblyName = assemblyName;
     this.Method = method;
     this.m_url = "";
     this.m_zone = SecurityZone.NoZone;
     if (evidence != null)
     {
         System.Security.Policy.Url hostEvidence = evidence.GetHostEvidence<System.Security.Policy.Url>();
         if (hostEvidence != null)
         {
             this.m_url = hostEvidence.GetURLString().ToString();
         }
         System.Security.Policy.Zone zone = evidence.GetHostEvidence<System.Security.Policy.Zone>();
         if (zone != null)
         {
             this.m_zone = zone.SecurityZone;
         }
     }
     this.m_debugString = this.ToString(true, false);
 }
示例#22
0
        private static PermissionSet RemoveNonReferencedPermissions(string[] setToFilter, ITaskItem[] dependencies)
        {
            PermissionSet retSet = new PermissionSet(PermissionState.None);
            if (dependencies == null || setToFilter == null || setToFilter.Length == 0)
                return retSet;

            List<string> assemblyNameList = new List<string>();
            foreach (ITaskItem dependency in dependencies)
            {
                AssemblyName dependentAssemblyName = AssemblyName.GetAssemblyName(dependency.ItemSpec);
                assemblyNameList.Add(dependentAssemblyName.Name + ", " + dependentAssemblyName.Version.ToString());
            }
            SecurityElement retSetElement = retSet.ToXml();
            foreach (string permissionXml in setToFilter)
            {
                if (!String.IsNullOrEmpty(permissionXml))
                {
                    string permissionAssemblyName;
                    string className;
                    string assemblyVersion;

                    SecurityElement permission = SecurityElement.FromString(permissionXml);

                    if (!ParseElementForAssemblyIdentification(permission, out className, out permissionAssemblyName, out assemblyVersion))
                        continue;
                    if (assemblyNameList.Contains(permissionAssemblyName + ", " + assemblyVersion))
                    {
                        retSetElement.AddChild(SecurityElement.FromString(permissionXml));
                    }
                }
            }
            retSet = new ReadOnlyPermissionSet(retSetElement);
            return retSet;
        }
 internal SecurityException(PermissionSet grantedSetObj, PermissionSet refusedSetObj) : base(GetResString("Arg_SecurityException"))
 {
     PermissionSet.s_fullTrust.Assert();
     base.SetErrorCode(-2146233078);
     if (grantedSetObj != null)
     {
         this.m_granted = grantedSetObj.ToXml().ToString();
     }
     if (refusedSetObj != null)
     {
         this.m_refused = refusedSetObj.ToXml().ToString();
     }
 }
        [System.Security.SecurityCritical]  // auto-generated
#pragma warning disable 618
        internal static bool CheckSetHelper(PermissionSet grants,
#pragma warning restore 618
                                           PermissionSet refused,
                                           PermissionSet demands,
                                           RuntimeMethodHandleInternal rmh,
                                           Object assemblyOrString,
                                           SecurityAction action,
                                           bool throwException)
        {

            Contract.Assert(demands != null, "Should not reach here with a null demand set");
#if _DEBUG && FEATURE_CAS_POLICY
            if (debug)
            {
                DEBUG_OUT("Granted: ");
                DEBUG_OUT(grants.ToXml().ToString());
                DEBUG_OUT("Refused: ");
                DEBUG_OUT(refused != null ? refused.ToXml().ToString() : "<null>");
                DEBUG_OUT("Demanded: ");
                DEBUG_OUT(demands!=null ? demands.ToXml().ToString() : "<null>");
            }
#endif // _DEBUG && FEATURE_CAS_POLICY

            IPermission permThatFailed = null;
            if (grants != null)
                grants.CheckDecoded(demands);
            if (refused != null)
                refused.CheckDecoded(demands);

            bool bThreadSecurity = SecurityManager._SetThreadSecurity(false);

            try
            {

                // Check grant set
                if (!demands.CheckDemand(grants, out permThatFailed))
                {
                    if (throwException)
                        ThrowSecurityException(assemblyOrString, grants, refused, rmh, action, demands, permThatFailed);
                    else
                        return false;
                }

                // Check refused set
                if (!demands.CheckDeny(refused, out permThatFailed))
                {
                    if (throwException)
                        ThrowSecurityException(assemblyOrString, grants, refused, rmh, action, demands, permThatFailed);
                    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, grants, refused, rmh, action, demands, permThatFailed);
                else
                    return false;
            }
            finally
            {
                if (bThreadSecurity)
                    SecurityManager._SetThreadSecurity(true);
            }
            return true;
        }
        [System.Security.SecurityCritical]  // auto-generated
#pragma warning disable 618
        internal static bool CheckSetHelper(PermissionSet grants,
#pragma warning restore 618
                                            PermissionSet refused,
                                            PermissionSet demands,
                                            RuntimeMethodHandleInternal rmh,
                                            Object assemblyOrString,
                                            SecurityAction action,
                                            bool throwException)
        {
            Contract.Assert(demands != null, "Should not reach here with a null demand set");
#if _DEBUG && FEATURE_CAS_POLICY
            if (debug)
            {
                DEBUG_OUT("Granted: ");
                DEBUG_OUT(grants.ToXml().ToString());
                DEBUG_OUT("Refused: ");
                DEBUG_OUT(refused != null ? refused.ToXml().ToString() : "<null>");
                DEBUG_OUT("Demanded: ");
                DEBUG_OUT(demands != null ? demands.ToXml().ToString() : "<null>");
            }
#endif // _DEBUG && FEATURE_CAS_POLICY

            IPermission permThatFailed = null;
            if (grants != null)
            {
                grants.CheckDecoded(demands);
            }
            if (refused != null)
            {
                refused.CheckDecoded(demands);
            }

            bool bThreadSecurity = SecurityManager._SetThreadSecurity(false);

            try
            {
                // Check grant set
                if (!demands.CheckDemand(grants, out permThatFailed))
                {
                    if (throwException)
                    {
                        ThrowSecurityException(assemblyOrString, grants, refused, rmh, action, demands, permThatFailed);
                    }
                    else
                    {
                        return(false);
                    }
                }

                // Check refused set
                if (!demands.CheckDeny(refused, out permThatFailed))
                {
                    if (throwException)
                    {
                        ThrowSecurityException(assemblyOrString, grants, refused, rmh, action, demands, permThatFailed);
                    }
                    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, grants, refused, rmh, action, demands, permThatFailed);
                }
                else
                {
                    return(false);
                }
            }
            finally
            {
                if (bThreadSecurity)
                {
                    SecurityManager._SetThreadSecurity(true);
                }
            }
            return(true);
        }
示例#26
0
 [System.Security.SecurityCritical]  // auto-generated 
 internal SecurityException( String message, PermissionSet grantedSetObj, PermissionSet refusedSetObj )
     : base(message) 
 {
     PermissionSet.s_fullTrust.Assert();
     SetErrorCode(System.__HResults.COR_E_SECURITY);
     if (grantedSetObj != null) 
         m_granted = grantedSetObj.ToXml().ToString();
     if (refusedSetObj != null) 
         m_refused = refusedSetObj.ToXml().ToString(); 
 }
        [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);
        }
示例#28
0
		public void AddDeclarativeSecurity (SecurityAction action, PermissionSet pset)
		{
#if !NET_2_1
			if (pset == null)
				throw new ArgumentNullException ("pset");
			if ((action == SecurityAction.RequestMinimum) ||
				(action == SecurityAction.RequestOptional) ||
				(action == SecurityAction.RequestRefuse))
				throw new ArgumentOutOfRangeException ("Request* values are not permitted", "action");

			RejectIfCreated ();

			if (permissions != null) {
				/* Check duplicate actions */
				foreach (RefEmitPermissionSet set in permissions)
					if (set.action == action)
						throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");

				RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
				permissions.CopyTo (new_array, 0);
				permissions = new_array;
			}
			else
				permissions = new RefEmitPermissionSet [1];

			permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
			attrs |= MethodAttributes.HasSecurity;
#endif
		}
示例#29
0
		public void FromXmlEmpty () 
		{
			PermissionSet ps = new PermissionSet (PermissionState.None);
			SecurityElement se = ps.ToXml ();
			Assert.IsNotNull (se, "Empty.ToXml()");
			Assert.AreEqual (0, ps.Count, "Empty.Count");

			PermissionSet ps2 = (PermissionSet) ps.Copy ();
			ps2.FromXml (se);
			Assert.IsTrue (!ps2.IsUnrestricted () , "FromXml-Copy.IsUnrestricted");

			se.AddAttribute ("Unrestricted", "true");
			ps2.FromXml (se);
			Assert.IsTrue (ps2.IsUnrestricted (), "FromXml-Unrestricted.IsUnrestricted");
		}
示例#30
0
		public void ToXmlUnrestricted () 
		{
			PermissionSet ps = new PermissionSet (PermissionState.Unrestricted);
			SecurityElement se = ps.ToXml ();
			Assert.IsTrue (ps.ToString().StartsWith ("<PermissionSet"), "Unrestricted.ToString().StartsWith");
			Assert.AreEqual ("System.Security.PermissionSet", (se.Attributes ["class"] as string), "Unrestricted.class");
			Assert.AreEqual ("1", (se.Attributes ["version"] as string), "Unrestricted.version");
			Assert.AreEqual ("true", (se.Attributes ["Unrestricted"] as string), "Unrestricted.Unrestricted");
		}
		public void FromXmlEmpty () 
		{
			PermissionSet ps = new PermissionSet (PermissionState.None);
			SecurityElement se = ps.ToXml ();
			AssertNotNull ("Empty.ToXml()", se);
			AssertEquals ("Empty.Count", 0, ps.Count);

			PermissionSet ps2 = (PermissionSet) ps.Copy ();
			ps2.FromXml (se);
			Assert ("FromXml-Copy.IsUnrestricted", !ps2.IsUnrestricted ()); 

			se.AddAttribute ("Unrestricted", "true");
			ps2.FromXml (se);
			Assert ("FromXml-Unrestricted.IsUnrestricted", ps2.IsUnrestricted ());
		}
示例#32
0
		// [ExpectedException (typeof (ArgumentException))]
		public void FromXmlWrongVersion () 
		{
			PermissionSet ps = new PermissionSet (PermissionState.None);
			SecurityElement se = ps.ToXml ();
			// can't modify - so we create our own
			SecurityElement se2 = new SecurityElement (se.Tag, se.Text);
			se2.AddAttribute ("class", se.Attribute ("class"));
			se2.AddAttribute ("version", "2");
			ps.FromXml (se2);
			// wow - here we accept a version 2 !!!
		}
		public void PermissionSetPermissionSet () 
		{
			FileDialogPermission fdp = new FileDialogPermission (FileDialogPermissionAccess.Open);
			PermissionSet ps1 = new PermissionSet (PermissionState.None);
			ps1.AddPermission (fdp);
			Assert ("ps1.IsEmpty", !ps1.IsEmpty ());

			PermissionSet ps = new PermissionSet (ps1);
			Assert ("PermissionSetPermissionSet.IsUnrestricted", !ps.IsUnrestricted ());
			Assert ("PermissionSetPermissionSet.IsEmpty", !ps.IsEmpty ());
			Assert ("PermissionSetPermissionSet.IsReadOnly", !ps.IsReadOnly);
			AssertEquals ("PermissionSetPermissionSet.ToXml().ToString()==ToString()", ps.ToXml ().ToString (), ps.ToString ());
		}
示例#34
0
		public void FromXmlOne () 
		{
			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);
			SecurityElement se = ps.ToXml ();
			Assert.IsNotNull (se, "One.ToXml()");
			Assert.AreEqual (1, ps.Count, "One.Count");

			PermissionSet ps2 = (PermissionSet) ps.Copy ();
			ps2.FromXml (se);
			Assert.IsTrue (!ps2.IsUnrestricted () , "FromXml-Copy.IsUnrestricted");
			Assert.AreEqual (1, ps2.Count, "Copy.Count");

			se.AddAttribute ("Unrestricted", "true");
			ps2.FromXml (se);
			Assert.IsTrue (ps2.IsUnrestricted (), "FromXml-Unrestricted.IsUnrestricted");
#if NET_2_0
			Assert.AreEqual (0, ps2.Count, "Unrestricted.Count");
#else
			// IPermission not shown in XML but still present in Count
			Assert.AreEqual (1, ps2.Count, "Unrestricted.Count");
#endif
		}
示例#35
0
        internal static void ListHandler( String[] args )
        {
            if (args[0].Equals( "__internal_usage__" ))
            {
                Console.WriteLine( "SecDBEdit -list <file>\n    List database entries for file" );
                return;
            }
            
            if (args.Length < 2)
            {
                Error( "-list", "Not enough arguments", -1 );
            }
            
            ArrayList list = null;
            
            try
            {
                list = LoadDatabase( args[1] );
            }
            catch (Exception e)
            {
                Error( "-list", "Failed during load - " + e.Message, -1 );
            }

            for (int i = 0; i < list.Count; ++i)
            {
                Console.WriteLine( "**** Entry #" + (i+1) + " *********************" );
                
                if (((DatabaseEntry)list[i]).xml != null)
                {
                    Console.WriteLine( "XML:" );
                    if (IsSecAttr( ((DatabaseEntry)list[i]).xml) )
                        Console.WriteLine( SecAttrToPermSet( ((DatabaseEntry)list[i]).xml ).ToString() );
                    else
                        Console.WriteLine( GetElementFromUbyte( ((DatabaseEntry)list[i]).xml ).ToString() );
                }
                else
                {
                    Console.WriteLine( "No XML entry" );
                }
                
                if (((DatabaseEntry)list[i]).binary != null)
                {
                    String format = null;
                    PermissionSet permSet = new PermissionSet(PermissionState.Unrestricted);
                    try
                    {
                        if ( ((DatabaseEntry)list[i]).binary[0] == '<' )
                        {
                            permSet.FromXml( GetElementFromUbyte( ((DatabaseEntry)list[i]).binary ) );
                            format = "(XML)";
                        }
                        else
                        {
                            BinaryFormatter formatter = new BinaryFormatter();
                            permSet = (PermissionSet)formatter.Deserialize( new MemoryStream( ((DatabaseEntry)list[i]).binary ) );
                            format = "(binary serialization)";
                        }
                    }
                    catch (Exception e)
                    {
                        Error( "-list", "Binary decode failed" + e.ToString(), -1 );
                    }
                    Console.WriteLine( "Binary " + format + ":" );
                    Console.WriteLine( permSet.ToXml().ToString() );
                }
                else
                {
                    Console.WriteLine( "No Binary entry - this equates to the empty set" );
                }
            }
        }
示例#36
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");
		}
	// Convert a permission set from one format to another.
	public static byte[] ConvertPermissionSet
				(String inFormat, byte[] inData, String outFormat)
			{
				// Validate the parameters.
				if(inFormat == null)
				{
					throw new ArgumentNullException("inFormat");
				}
				if(inData == null)
				{
					throw new ArgumentNullException("inData");
				}
				if(outFormat == null)
				{
					throw new ArgumentNullException("outFormat");
				}

				// Convert the input data into a permission set.
				PermissionSet permSet;
				SecurityElement e;
				switch(inFormat.ToLower(CultureInfo.InvariantCulture))
				{
					case "xml": case "xmlascii":
					{
						permSet = new PermissionSet(PermissionState.None);
						e = (new MiniXml(Encoding.UTF8.GetString(inData)))
								.Parse();
						permSet.FromXml(e);
					}
					break;

					case "xmlunicode":
					{
						permSet = new PermissionSet(PermissionState.None);
						e = (new MiniXml(Encoding.Unicode.GetString(inData)))
								.Parse();
						permSet.FromXml(e);
					}
					break;

				#if CONFIG_SERIALIZATION
					case "binary":
					{
						MemoryStream inStream = new MemoryStream(inData);
						permSet = (PermissionSet)
							((new BinaryFormatter()).Deserialize(inStream));
					}
					break;
				#endif

					default: return null;
				}

				// Convert the output data into a permission set.
				switch(outFormat.ToLower(CultureInfo.InvariantCulture))
				{
					case "xml": case "xmlascii":
					{
						e = permSet.ToXml();
						return Encoding.UTF8.GetBytes(e.ToString());
					}
					// Not reached.

					case "xmlunicode":
					{
						e = permSet.ToXml();
						return Encoding.Unicode.GetBytes(e.ToString());
					}
					// Not reached.

				#if CONFIG_SERIALIZATION
					case "binary":
					{
						MemoryStream outStream = new MemoryStream();
						(new BinaryFormatter()).Serialize(outStream, permSet);
						return outStream.ToArray();
					}
					// Not reached.
				#endif
				}
				return null;
			}