Union() public method

public Union ( PermissionSet other ) : PermissionSet
other PermissionSet
return PermissionSet
Example #1
0
        internal unsafe static void ReflectedLinkDemandInvoke(MethodBase mb)
        {
            RuntimeDeclSecurityActions runtimeDeclSecurityActions;
            RuntimeDeclSecurityActions runtimeDeclSecurityActions2;

            if (!SecurityManager.GetLinkDemandSecurity(mb, &runtimeDeclSecurityActions, &runtimeDeclSecurityActions2))
            {
                return;
            }
            PermissionSet permissionSet = null;

            if (runtimeDeclSecurityActions.cas.size > 0)
            {
                permissionSet = SecurityManager.Decode(runtimeDeclSecurityActions.cas.blob, runtimeDeclSecurityActions.cas.size);
            }
            if (runtimeDeclSecurityActions.noncas.size > 0)
            {
                PermissionSet permissionSet2 = SecurityManager.Decode(runtimeDeclSecurityActions.noncas.blob, runtimeDeclSecurityActions.noncas.size);
                permissionSet = ((permissionSet != null) ? permissionSet.Union(permissionSet2) : permissionSet2);
            }
            if (runtimeDeclSecurityActions2.cas.size > 0)
            {
                PermissionSet permissionSet3 = SecurityManager.Decode(runtimeDeclSecurityActions2.cas.blob, runtimeDeclSecurityActions2.cas.size);
                permissionSet = ((permissionSet != null) ? permissionSet.Union(permissionSet3) : permissionSet3);
            }
            if (runtimeDeclSecurityActions2.noncas.size > 0)
            {
                PermissionSet permissionSet4 = SecurityManager.Decode(runtimeDeclSecurityActions2.noncas.blob, runtimeDeclSecurityActions2.noncas.size);
                permissionSet = ((permissionSet != null) ? permissionSet.Union(permissionSet4) : permissionSet4);
            }
            if (permissionSet != null)
            {
                permissionSet.Demand();
            }
        }
Example #2
0
        private static PermissionSet ResolvePolicy(Evidence evidence, PermissionSet reqdPset, PermissionSet optPset, PermissionSet denyPset, out PermissionSet denied, bool checkExecutionPermission)
        {
            if (executionSecurityPermission == null)
            {
                executionSecurityPermission = new SecurityPermission(SecurityPermissionFlag.Execution);
            }
            PermissionSet other     = null;
            Exception     exception = null;
            PermissionSet set2      = optPset;

            if (reqdPset == null)
            {
                other = set2;
            }
            else
            {
                other = (set2 == null) ? null : reqdPset.Union(set2);
            }
            if ((other != null) && !other.IsUnrestricted())
            {
                other.AddPermission(executionSecurityPermission);
            }
            if (evidence == null)
            {
                evidence = new Evidence();
            }
            PermissionSet target = polmgr.Resolve(evidence);

            if (other != null)
            {
                target.InplaceIntersect(other);
            }
            if (checkExecutionPermission && (!target.Contains(executionSecurityPermission) || ((denyPset != null) && denyPset.Contains(executionSecurityPermission))))
            {
                throw new PolicyException(Environment.GetResourceString("Policy_NoExecutionPermission"), -2146233320, exception);
            }
            if ((reqdPset != null) && !reqdPset.IsSubsetOf(target))
            {
                throw new PolicyException(Environment.GetResourceString("Policy_NoRequiredPermission"), -2146233321, exception);
            }
            if (denyPset != null)
            {
                denied = denyPset.Copy();
                target.MergeDeniedSet(denied);
                if (denied.IsEmpty())
                {
                    denied = null;
                }
            }
            else
            {
                denied = null;
            }
            target.IgnoreTypeLoadFailures = true;
            return(target);
        }
        private static PermissionSet ResolvePolicy(Evidence evidence, PermissionSet reqdPset, PermissionSet optPset, PermissionSet denyPset, out PermissionSet denied, bool checkExecutionPermission)
        {
            if (SecurityManager.executionSecurityPermission == null)
            {
                SecurityManager.executionSecurityPermission = new SecurityPermission(SecurityPermissionFlag.Execution);
            }
            Exception     exception = null;
            PermissionSet permissionSet;

            if (reqdPset == null)
            {
                permissionSet = optPset;
            }
            else
            {
                permissionSet = ((optPset == null) ? null : reqdPset.Union(optPset));
            }
            if (permissionSet != null && !permissionSet.IsUnrestricted())
            {
                permissionSet.AddPermission(SecurityManager.executionSecurityPermission);
            }
            if (evidence == null)
            {
                evidence = new Evidence();
            }
            PermissionSet permissionSet2 = SecurityManager.polmgr.Resolve(evidence);

            if (permissionSet != null)
            {
                permissionSet2.InplaceIntersect(permissionSet);
            }
            if (checkExecutionPermission && (!permissionSet2.Contains(SecurityManager.executionSecurityPermission) || (denyPset != null && denyPset.Contains(SecurityManager.executionSecurityPermission))))
            {
                throw new PolicyException(Environment.GetResourceString("Policy_NoExecutionPermission"), -2146233320, exception);
            }
            if (reqdPset != null && !reqdPset.IsSubsetOf(permissionSet2))
            {
                throw new PolicyException(Environment.GetResourceString("Policy_NoRequiredPermission"), -2146233321, exception);
            }
            if (denyPset != null)
            {
                denied = denyPset.Copy();
                permissionSet2.MergeDeniedSet(denied);
                if (denied.IsEmpty())
                {
                    denied = null;
                }
            }
            else
            {
                denied = null;
            }
            permissionSet2.IgnoreTypeLoadFailures = true;
            return(permissionSet2);
        }
Example #4
0
        // When using reflection LinkDemand are promoted to full Demand (i.e. stack walk)
        internal unsafe static void ReflectedLinkDemandInvoke(MethodBase mb)
        {
            RuntimeDeclSecurityActions klass;
            RuntimeDeclSecurityActions method;

            if (!GetLinkDemandSecurity(mb, &klass, &method))
            {
                return;
            }

            PermissionSet ps = null;

            if (klass.cas.size > 0)
            {
                ps = Decode(klass.cas.blob, klass.cas.size);
            }
            if (klass.noncas.size > 0)
            {
                PermissionSet p = Decode(klass.noncas.blob, klass.noncas.size);
                ps = (ps == null) ? p : ps.Union(p);
            }

            if (method.cas.size > 0)
            {
                PermissionSet p = Decode(method.cas.blob, method.cas.size);
                ps = (ps == null) ? p : ps.Union(p);
            }
            if (method.noncas.size > 0)
            {
                PermissionSet p = Decode(method.noncas.blob, method.noncas.size);
                ps = (ps == null) ? p : ps.Union(p);
            }

            // in this case we union-ed the permission sets because we want to do
            // a single stack walk (not up to 4).
            if (ps != null)
            {
                ps.Demand();
            }
        }
	// Assert permissions for the caller.
	internal void Assert(int skipFrames)
			{
				// Add the permission to the granted permissions set.  If there
				// are no permissions at all, then assume we are unrestricted.
				ClrPermissions current;
				current = ClrSecurity.GetPermissionsFrom(skipFrames);
				if(current != null)
				{
					PermissionSet set = new PermissionSet(PermissionState.None);
					set.AddPermission(this.Copy());
					set = set.Union(current.granted);
					ClrSecurity.SetPermissions
						(current.SetGranted(set), skipFrames);
				}
			}
Example #6
0
        // Assert permissions for the caller.
        internal void Assert(int skipFrames)
        {
            // Add the permission to the granted permissions set.  If there
            // are no permissions at all, then assume we are unrestricted.
            ClrPermissions current;

            current = ClrSecurity.GetPermissionsFrom(skipFrames);
            if (current != null)
            {
                PermissionSet set = new PermissionSet(PermissionState.None);
                set.AddPermission(this.Copy());
                set = set.Union(current.granted);
                ClrSecurity.SetPermissions
                    (current.SetGranted(set), skipFrames);
            }
        }
	// Deny permissions to the caller.
	internal void Deny(int skipFrames)
			{
				// Add the permission to the denied permissions set.
				ClrPermissions current;
				current = ClrSecurity.GetPermissionsFrom(skipFrames);
				PermissionSet set = new PermissionSet(PermissionState.None);
				set.AddPermission(this.Copy());
				if(current == null)
				{
					// Initialize the permissions context to "allow
					// everything except this permission object".
					current = new ClrPermissions
						(new PermissionSet(PermissionState.Unrestricted),
						 set, null);
				}
				else
				{
					current = current.SetDenied(set.Union(current.denied));
				}
				ClrSecurity.SetPermissions(current, skipFrames);
			}
Example #8
0
        // Deny permissions to the caller.
        internal void Deny(int skipFrames)
        {
            // Add the permission to the denied permissions set.
            ClrPermissions current;

            current = ClrSecurity.GetPermissionsFrom(skipFrames);
            PermissionSet set = new PermissionSet(PermissionState.None);

            set.AddPermission(this.Copy());
            if (current == null)
            {
                // Initialize the permissions context to "allow
                // everything except this permission object".
                current = new ClrPermissions
                              (new PermissionSet(PermissionState.Unrestricted),
                              set, null);
            }
            else
            {
                current = current.SetDenied(set.Union(current.denied));
            }
            ClrSecurity.SetPermissions(current, skipFrames);
        }
		private static PermissionSet Combine(PermissionSet p1, PermissionSet p2)
		{
			if (p1 == null)
			{
				return p2;
			}
			if (p2 == null)
			{
				return p1;
			}
			return p1.Union(p2);
		}
        [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;
        }
		public void Union_OnePermission ()
		{
			SecurityPermission sp = new SecurityPermission (SecurityPermissionFlag.Assertion);
			PermissionSet ps1 = new PermissionSet (PermissionState.None);
			ps1.AddPermission (sp);
			PermissionSet ps2 = new PermissionSet (PermissionState.None);
			Compare ("PS1 U null", ps1.Union (null), false, 1);
			Compare ("PS1 U None", ps1.Union (ps2), false, 1);
			Compare ("None U PS1", ps2.Union (ps1), false, 1);

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

			PermissionSet ups1 = new PermissionSet (PermissionState.Unrestricted);
			Compare ("PS1 U Unrestricted", ps1.Union (ups1), true, 0);
			Compare ("Unrestricted U PS1", ups1.Union (ps1), true, 0);
		}
        static private PermissionSet ResolvePolicy(Evidence evidence,
                                                   PermissionSet reqdPset,
                                                   PermissionSet optPset,
                                                   PermissionSet denyPset,
                                                   out PermissionSet denied,
                                                   bool checkExecutionPermission)
        {
            PermissionSet requested;
            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() && CheckExecution())
            {
                requested.AddPermission(executionSecurityPermission);
            }

            if (InitPolicy())
            {
                // If we aren't passed any evidence, just make an empty object
                // If we are passed evidence, copy it before passing it
                // to the policy manager.
                // Note: this is not a deep copy, the pieces of evidence within the
                // Evidence object can still be altered and affect the originals.

                if (evidence == null)
                {
                    evidence = new Evidence();
                }
                else
                {
                    evidence = evidence.ShallowCopy();
                }

                evidence.AddHost(new PermissionRequestEvidence(reqdPset, optPset, denyPset));

                // We need to make sure that no stray exceptions come out of Resolve so
                // we wrap it in a try block.

                try
                {
                    allowed = polmgr.Resolve(evidence, requested);
                }
                catch (Exception e)
                {
#if _DEBUG
                    if (debug)
                    {
                        DEBUG_OUT("Exception during resolve");
                        DEBUG_OUT(e.GetType().FullName);
                        DEBUG_OUT(e.Message);
                        DEBUG_OUT(e.StackTrace);
                    }
#endif

                    // If we get a policy exception, we are done are we are going to fail to
                    // load no matter what.

                    if (e is PolicyException)
                    {
                        throw e;
                    }

                    // If we get any other kid of exception, we set the allowed set to the
                    // empty set and continue processing as normal.  This allows assemblies
                    // that make no request to be loaded but blocks any assembly that
                    // makes a request from being loaded.  This seems like a valid design to
                    // me -- gregfee 6/19/2000

                    savedException = e;
                    allowed        = new PermissionSet();
                }
            }
            else
            {
                denied = null;
                return(null);
            }


#if _DEBUG
            if (debug)
            {
                DEBUG_OUT("ResolvePolicy:");
                IEnumerator enumerator = evidence.GetEnumerator();
                DEBUG_OUT("Evidence:");
                while (enumerator.MoveNext())
                {
                    Object obj = enumerator.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 Publisher)
                    {
                        DEBUG_OUT(((Publisher)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());
                    }
                }
                DEBUG_OUT("Required permissions:");
                DEBUG_OUT(reqdPset != null ? reqdPset.ToString() : "<null>");
                DEBUG_OUT("Optional permissions:");
                DEBUG_OUT(optPset != null ? optPset.ToString() : "<null>");
                DEBUG_OUT("Denied permissions:");
                DEBUG_OUT(denyPset != null ? denyPset.ToString() : "<null>");
                DEBUG_OUT("Requested permissions:");
                DEBUG_OUT(requested != null ? requested.ToString() : "<null>");
                DEBUG_OUT("Granted permissions:");
                DEBUG_OUT(allowed != null ? allowed.ToString() : "<null>");
            }
#endif

            // Check that we were granted the right to execute.
            if (!allowed.IsUnrestricted() && checkExecutionPermission && CheckExecution())
            {
                SecurityPermission secPerm = (SecurityPermission)allowed.GetPermission(securityPermissionType);

                if (secPerm == null || !executionSecurityPermission.IsSubsetOf(secPerm))
                {
#if _DEBUG
                    DEBUG_OUT("No execute permission");
#endif
                    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))
            {
#if _DEBUG
                DEBUG_OUT("Didn't get required permissions");
#endif
                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)
            {
                denied = denyPset.Copy();
                allowed.MergeDeniedSet(denied);
                if (denied.IsEmpty())
                {
                    denied = null;
                }
            }
            else
            {
                denied = null;
            }


#if _DEBUG
            if (debug)
            {
                DEBUG_OUT("Final denied permissions:");
                DEBUG_OUT(denied != null ? denied.ToString() : "<null>");
            }
#endif

            return(allowed);
        }
 private static PermissionSet ResolvePolicy(Evidence evidence, PermissionSet reqdPset, PermissionSet optPset, PermissionSet denyPset, out PermissionSet denied, bool checkExecutionPermission)
 {
     if (executionSecurityPermission == null)
     {
         executionSecurityPermission = new SecurityPermission(SecurityPermissionFlag.Execution);
     }
     PermissionSet other = null;
     Exception exception = null;
     PermissionSet set2 = optPset;
     if (reqdPset == null)
     {
         other = set2;
     }
     else
     {
         other = (set2 == null) ? null : reqdPset.Union(set2);
     }
     if ((other != null) && !other.IsUnrestricted())
     {
         other.AddPermission(executionSecurityPermission);
     }
     if (evidence == null)
     {
         evidence = new Evidence();
     }
     PermissionSet target = polmgr.Resolve(evidence);
     if (other != null)
     {
         target.InplaceIntersect(other);
     }
     if (checkExecutionPermission && (!target.Contains(executionSecurityPermission) || ((denyPset != null) && denyPset.Contains(executionSecurityPermission))))
     {
         throw new PolicyException(Environment.GetResourceString("Policy_NoExecutionPermission"), -2146233320, exception);
     }
     if ((reqdPset != null) && !reqdPset.IsSubsetOf(target))
     {
         throw new PolicyException(Environment.GetResourceString("Policy_NoRequiredPermission"), -2146233321, exception);
     }
     if (denyPset != null)
     {
         denied = denyPset.Copy();
         target.MergeDeniedSet(denied);
         if (denied.IsEmpty())
         {
             denied = null;
         }
     }
     else
     {
         denied = null;
     }
     target.IgnoreTypeLoadFailures = true;
     return target;
 }
Example #14
0
        /// <include file='doc\SecurityManager.uex' path='docs/doc[@for="SecurityManager.ResolvePolicy"]/*' />
        static public PermissionSet ResolvePolicy(Evidence evidence,
                           PermissionSet reqdPset,
                           PermissionSet optPset,
                           PermissionSet denyPset,
                           out PermissionSet denied)
        {
            PermissionSet requested;
            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() && CheckExecution())
            {
                requested.AddPermission( executionSecurityPermission );
            }
            
            if (InitPolicy())
            {
                // If we aren't passed any evidence, just make an empty object
                // If we are passed evidence, copy it before passing it
                // to the policy manager.
                // Note: this is not a deep copy, the pieces of evidence within the
                // Evidence object can still be altered and affect the originals.
            
                if (evidence == null)
                    evidence = new Evidence();
                else
                    evidence = evidence.ShallowCopy();
                    
                evidence.AddHost(new PermissionRequestEvidence(reqdPset, optPset, denyPset));
                
                // We need to make sure that no stray exceptions come out of Resolve so
                // we wrap it in a try block.

                try
                {
                    allowed = polmgr.Resolve(evidence,requested);
                }
                catch (Exception e)
                {
#if _DEBUG
                    if (debug)
                    {
                        DEBUG_OUT( "Exception during resolve" );
                        DEBUG_OUT( e.GetType().FullName );
                        DEBUG_OUT( e.Message );
                        DEBUG_OUT( e.StackTrace );
                    }
#endif

                    // If we get a policy exception, we are done are we are going to fail to
                    // load no matter what.

                    if (e is PolicyException)
                        throw e;

                    // If we get any other kid of exception, we set the allowed set to the
                    // empty set and continue processing as normal.  This allows assemblies
                    // that make no request to be loaded but blocks any assembly that
                    // makes a request from being loaded.                                          

                    savedException = e;
                    allowed = new PermissionSet();
                }
            }
            else
            {
                denied = null;
                return null;
            }
                

#if _DEBUG    
            if (debug)
            {
                DEBUG_OUT("ResolvePolicy:");
                IEnumerator enumerator = evidence.GetEnumerator();
                DEBUG_OUT("Evidence:");
                while (enumerator.MoveNext())
                {
                    Object obj = enumerator.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() );
                    }
                }
                DEBUG_OUT("Required permissions:");
                DEBUG_OUT(reqdPset != null ? reqdPset.ToString() : "<null>");
                DEBUG_OUT("Optional permissions:");
                DEBUG_OUT(optPset != null ? optPset.ToString() : "<null>");
                DEBUG_OUT("Denied permissions:");
                DEBUG_OUT(denyPset != null ? denyPset.ToString() : "<null>");
                DEBUG_OUT("Requested permissions:");
                DEBUG_OUT(requested != null ? requested.ToString() : "<null>");
                DEBUG_OUT("Granted permissions:");
                DEBUG_OUT(allowed != null ? allowed.ToString() : "<null>");
            }
#endif
        
            // Check that we were granted the right to execute.
            if (!allowed.IsUnrestricted() && CheckExecution())
            {
                SecurityPermission secPerm = (SecurityPermission)allowed.GetPermission( securityPermissionType );

                if (secPerm == null || !executionSecurityPermission.IsSubsetOf( secPerm ))
                {
#if _DEBUG
                    DEBUG_OUT( "No execute permission" );
#endif                            
                    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))
            {
#if _DEBUG
                DEBUG_OUT( "Didn't get required permissions" );
#endif           
                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)
            {
                denied = denyPset.Copy();
                allowed.MergeDeniedSet(denied);
                if (denied.IsEmpty())
                    denied = null;
            }
            else
                denied = null;
    
    
#if _DEBUG
            if (debug)
            {
                DEBUG_OUT("Final denied permissions:");
                DEBUG_OUT(denied != null ? denied.ToString() : "<null>");
            }
#endif
    
            return allowed;
        }
Example #15
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);
        }
		public void Union_Empty ()
		{
			PermissionSet ps1 = new PermissionSet (PermissionState.None);
			PermissionSet ps2 = new PermissionSet (PermissionState.None);
			Compare ("None U null", ps1.Union (null), false, 0);
			Compare ("None1 U None2", ps1.Union (ps2), false, 0);
			Compare ("None2 U None1", ps2.Union (ps1), false, 0);

			PermissionSet ups1 = new PermissionSet (PermissionState.Unrestricted);
			Compare ("None1 U Unrestricted", ps1.Union (ups1), true, 0);
			Compare ("Unrestricted U None1", ups1.Union (ps1), true, 0);
			Compare ("Unrestricted U Null", ups1.Union (null), true, 0);

			PermissionSet ups2 = new PermissionSet (PermissionState.Unrestricted);
			Compare ("ups1 U ups2", ups1.Union (ups2), true, 0);
			Compare ("ups2 U ups1", ups2.Union (ups1), true, 0);
		}
        private void BuildAssembly(AppDomain appDomain, string dir, string filename)
        {
            // Prepare the assembly-level permissions.
            PermissionSet requiredPermissions = new PermissionSet(null);
            PermissionSet optionalPermissions = new PermissionSet(null);
            PermissionSet refusedPermissions = new PermissionSet(null);

            foreach (SecurityDeclaration securityDeclaration in assemblyDefinition.SecurityDeclarations)
            {
                switch (securityDeclaration.Action)
                {
                    case Mono.Cecil.SecurityAction.RequestMinimum:
                        requiredPermissions = requiredPermissions.Union(securityDeclaration.PermissionSet);
                        break;
                    case Mono.Cecil.SecurityAction.RequestOptional:
                        optionalPermissions = optionalPermissions.Union(securityDeclaration.PermissionSet);
                        break;
                    case Mono.Cecil.SecurityAction.RequestRefuse:
                        refusedPermissions = refusedPermissions.Union(securityDeclaration.PermissionSet);
                        break;
                }
            }

            // Build the dynamic assembly.
            AssemblyBuilder assemblyBuilder = appDomain.DefineDynamicAssembly(
                new AssemblyName(assemblyDefinition.Name.FullName),
                AssemblyBuilderAccess.RunAndSave, dir,
                requiredPermissions, optionalPermissions, refusedPermissions);
            dynamicAssembly = new DynamicAssembly(assemblyBuilder, filename);

            // TODO: Set entry point and assembly kind.

            foreach (ModuleDefinition moduleDefinition in assemblyDefinition.Modules)
                BuildModule(moduleDefinition);

            metadataPass.Add(delegate
            {
                InitializeCustomAttributes(assemblyBuilder.SetCustomAttribute, assemblyDefinition.CustomAttributes);
            });
        }
		public void Union_OneNonIUnrestrictedPermission ()
		{
			ZoneIdentityPermission zip = new ZoneIdentityPermission (SecurityZone.MyComputer);
			PermissionSet ps1 = new PermissionSet (PermissionState.None);
			ps1.AddPermission (zip);
			PermissionSet ps2 = new PermissionSet (PermissionState.None);
			Compare ("PS1 U null", ps1.Union (null), false, 1);
			Compare ("PS1 U None", ps1.Union (ps2), false, 1);
			Compare ("None U PS1", ps2.Union (ps1), false, 1);

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

			PermissionSet ups1 = new PermissionSet (PermissionState.Unrestricted);
			ups1.AddPermission (zip);
#if NET_2_0
			// Identity permissions aren't added to unrestricted permission sets in 2.0
			Compare ("PS1 U Unrestricted", ps1.Union (ups1), true, 0);
			Compare ("Unrestricted U PS1", ups1.Union (ps1), true, 0);
			PermissionSet ups2 = new PermissionSet (PermissionState.Unrestricted);
			Compare ("UPS1 U UPS2", ups1.Union (ups1), true, 0);
			Compare ("UPS2 U UPS1", ups2.Union (ups1), true, 0);
			ups2.AddPermission (zip);
			Compare ("UPS1 U UPS2+ZIP", ups1.Union (ups2), true, 0);
			Compare ("UPS2+ZIP U UPS1", ups2.Union (ups1), true, 0);
#else
			Compare ("PS1 U Unrestricted", ps1.Union (ups1), true, 1);
			Compare ("Unrestricted U PS1", ups1.Union (ps1), true, 1);
			PermissionSet ups2 = new PermissionSet (PermissionState.Unrestricted);
			Compare ("UPS1 U UPS2", ups1.Union (ups1), true, 1);
			Compare ("UPS2 U UPS1", ups2.Union (ups1), true, 1);
			ups2.AddPermission (zip);
			Compare ("UPS1 U UPS2+ZIP", ups1.Union (ups2), true, 1);
			Compare ("UPS2+ZIP U UPS1", ups2.Union (ups1), true, 1);
#endif
		}
Example #19
0
        internal static PermissionSet SecAttrToPermSet(byte[] input)
        {
            // Convert byte array to string.
            char[] charInput = new char[input.Length - 1];
            for (int i = 0; i < (input.Length - 1); i++)
                charInput[i] = (char)input[i];
            String strInput = new String(charInput);

            // Start with an empty permission set.
            PermissionSet pset = new PermissionSet(PermissionState.None);

            // Remove initial tag.
            strInput = strInput.Substring(attrTag.Length);

            // Divide input up into descriptors for each security attribute
            // (each descriptor is separated with a ';').
            String[] attrs = strInput.Split(new char[] {';'});

            // Process each security attribute individually.
            for (int i = 0; i < attrs.Length; i++) {

                // The last descriptor is always blank (we always append a
                // trailing ';').
                if (attrs[i].Length == 0)
                    break;

                // Break the '@' separated descriptor into its constituent
                // fields.
                String[] fields = attrs[i].Split(new char[] {'@'});

                // The first field is the fully qualified name of the security
                // attribute class.
                Type attrType = Type.GetType(fields[0]);
                if (attrType == null)
                    throw new ArgumentException();

                // Build an argument list for the attribute class constructor
                // (it takes a single SecurityAction enumerated type, which we
                // always set to zero because we don't care what the security
                // action is (it's not encoded in the permission set)).
                Object[] attrArgs = new Object[] { Enum.ToObject(typeof(SecurityAction), 0) };

                // Create an instance of the security attribute class.
                Object attr = Activator.CreateInstance(attrType,attrArgs);
                if (attr == null)
                    throw new ArgumentException();

                // Set any properties or fields on the instance that represent
                // state data.
                for (int j = 1; j < fields.Length; j++) {

                    // First character in the descriptor indicates either a
                    // field ('F') or a property ('P').
                    bool isField = fields[j][0] == 'F';

                    // The field type is encoded in the next two characters.
                    String type = fields[j].Substring(1, 2);

                    // Remove the characters we've already parsed from the field
                    // descriptor.
                    String field = fields[j].Substring(3);

                    // Enumerated types have an extended type description that
                    // includes the fully qualified name of the enumerated value
                    // type. Extract this name and remove it from the field
                    // descriptor.
                    int pos;
                    String enumType = "";
                    if (type == "EN") {
                        pos = field.IndexOf('!');
                        enumType = field.Substring(0, pos);
                        field = field.Substring(pos + 1);
                    }

                    // The field/property name is everything up to the '='. The
                    // textual form of the value is everything after the '=' up
                    // to the end of the descriptor.
                    pos = field.IndexOf('=');
                    String name = field.Substring(0, pos);
                    String value = field.Substring(pos + 1);

                    // Build a one-value argument list for the field/property
                    // set. Need to parse the value string based on the field
                    // type.
                    Object[] args = new Object[1];
                    if (type == "BL")
                        args[0] =(Object)(value == "T");
                    else if (type == "I1")
                        args[0] = (sbyte) Int32.Parse(value, CultureInfo.InvariantCulture);
                    else if (type == "I2")
                        args[0] = (short)Int32.Parse(value, CultureInfo.InvariantCulture);
                    else if (type == "I4")
                        args[0] = (int)Int32.Parse(value, CultureInfo.InvariantCulture);
                    else if (type == "I8")
                        args[0] = (long)Int64.Parse(value, CultureInfo.InvariantCulture);
                    else if (type == "U1")
                        args[0] = (byte)Int32.Parse(value, CultureInfo.InvariantCulture);

                    else if (type == "U2")
                        args[0] = (ushort)Int32.Parse(value, CultureInfo.InvariantCulture);
                    else if (type == "U4")
                        args[0] = (uint)Int32.Parse(value, CultureInfo.InvariantCulture);
                    else if (type == "U8")
                        args[0] = (ulongint)Int64.Parse(value, CultureInfo.InvariantCulture);
                    else if (type == "R4")
                        args[0] = (float)Double.Parse(value, CultureInfo.InvariantCulture);
                    else if (type == "R8")
                        args[0] = (double)Double.Parse(value, CultureInfo.InvariantCulture);
                    else if (type == "CH")
                        args[0] = value[0];
                    else if (type == "SZ") {
                        // Strings are encoded as hex dumps to avoid conflicts
                        // with the separator characters in the descriptors.
                        StringBuilder sb = new StringBuilder();
                        for (int k = 0; k < (value.Length / 2); k++) {
                            String lookup = "0123456789ABCDEF";
                            int ch = (lookup.IndexOf(value[k * 2]) * 16) + lookup.IndexOf(value[(k * 2) + 1]);
                            sb.Append((char)ch);
                        }
                        args[0] = sb.ToString();
                    } else if (type == "EN")
                        args[0] = Enum.ToObject(Type.GetType(enumType),Int32.Parse(value, CultureInfo.InvariantCulture));

                    // Call the property setter or set the field with the value
                    // we've just calculated.
                    attrType.InvokeMember(name,
                                          isField ? BindingFlags.SetField : BindingFlags.SetProperty,
                                          Type.DefaultBinder,
                                          attr,
                                          args); 
                }

                // Ask the security attribute class to generate a class instance
                // for corresponding permission class (taking into account the
                // state data we supplied). There's one special case: if the
                // security custom attribute class is PermissionSetAttribute, a
                // whole permission set is generated instead (which we merge
                // into the current set).
                if (attrType != typeof(PermissionSetAttribute)) {
                    IPermission perm = ((SecurityAttribute)attr).CreatePermission();
                    if (perm == null)
                        throw new ArgumentException();

                    // We really can't cope with non-code access permissions
                    // embedded in mscorlib (we need to place them in separate
                    // sets from CAS perms, and we can't tell the difference
                    // soon enough).
                    if (!(perm is CodeAccessPermission))
                        throw new ArgumentException("Non-CAS perm used in mscorlib, see security team");

                    // Add the permission to the permission set we're accumulating.
                    pset.AddPermission(perm);
                } else {
                    PermissionSet mergePset = ((PermissionSetAttribute)attr).CreatePermissionSet();
                    if (mergePset == null)
                        throw new ArgumentException();

                    // As above, check perm set for non-CAS perms.
                    if (mergePset.ContainsNonCodeAccessPermissions())
                        throw new ArgumentException("Non-CAS perm used in mscorlib, see security team");

                    // Merge the new set into the permission we're building.
                    pset = pset.Union(mergePset);
                }
            }

            // Return the completed permission set.
            return pset;
        }
 internal static PermissionSet AddPermissionForUri(PermissionSet originalPermSet, Uri srcUri) 
 {
     PermissionSet newPermSet = originalPermSet; 
     if (srcUri != null) 
     {
         Evidence evidence = new Evidence(); 
         evidence.AddHost(new Url(BindUriHelper.UriToString(srcUri))); // important: the parameter must be a UrL object not a UrI object
         IMembershipCondition membership = new UrlMembershipCondition(BindUriHelper.UriToString(srcUri));
         CodeGroup group = (srcUri.IsFile) ?
             (CodeGroup)new FileCodeGroup(membership, FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery) 
             :(CodeGroup)new NetCodeGroup(membership);
         PolicyStatement policy = group.Resolve(evidence); 
         if (!policy.PermissionSet.IsEmpty()) 
         {
             newPermSet = originalPermSet.Union(policy.PermissionSet); 
         }
     }
     return newPermSet;
 } 
Example #21
0
        private static PermissionSet ResolvePolicy(Evidence evidence, PermissionSet reqdPset, PermissionSet optPset, PermissionSet denyPset, out PermissionSet denied, bool checkExecutionPermission)
        {
            if (SecurityManager.executionSecurityPermission == null)
            {
                SecurityManager.executionSecurityPermission = new SecurityPermission(SecurityPermissionFlag.Execution);
            }
            Exception     exception = (Exception)null;
            PermissionSet other1    = optPset;
            PermissionSet other2    = reqdPset != null ? (other1 == null ? (PermissionSet)null : reqdPset.Union(other1)) : other1;

            if (other2 != null && !other2.IsUnrestricted())
            {
                other2.AddPermission((IPermission)SecurityManager.executionSecurityPermission);
            }
            if (evidence == null)
            {
                evidence = new Evidence();
            }
            PermissionSet target = SecurityManager.polmgr.Resolve(evidence);

            if (other2 != null)
            {
                target.InplaceIntersect(other2);
            }
            if (checkExecutionPermission && (!target.Contains((IPermission)SecurityManager.executionSecurityPermission) || denyPset != null && denyPset.Contains((IPermission)SecurityManager.executionSecurityPermission)))
            {
                throw new PolicyException(Environment.GetResourceString("Policy_NoExecutionPermission"), -2146233320, exception);
            }
            if (reqdPset != null && !reqdPset.IsSubsetOf(target))
            {
                throw new PolicyException(Environment.GetResourceString("Policy_NoRequiredPermission"), -2146233321, exception);
            }
            if (denyPset != null)
            {
                denied = denyPset.Copy();
                target.MergeDeniedSet(denied);
                if (denied.IsEmpty())
                {
                    denied = (PermissionSet)null;
                }
            }
            else
            {
                denied = (PermissionSet)null;
            }
            target.IgnoreTypeLoadFailures = true;
            return(target);
        }