IsSubsetOf() public method

public IsSubsetOf ( PermissionSet target ) : bool
target PermissionSet
return bool
	// Determine if a specific permission has been granted.
	public static bool IsGranted(IPermission perm)
			{
				// Bail out if the requested permission is null.
				if(perm == null)
				{
					return true;
				}

				// Get the current permission state.
				ClrPermissions current = ClrSecurity.GetPermissionsFrom(1);
				if(current == null)
				{
					// Null is equivalent to "unrestricted".
					return true;
				}

				// Build a permission set with just this permission.
				PermissionSet set = new PermissionSet(PermissionState.None);
				set.AddPermission(perm);

				// If "PermitOnly" is set, then only check that set.
				if(current.permitOnly != null)
				{
					return set.IsSubsetOf(current.permitOnly);
				}

				// The permission must be granted, but not denied.
				if(!set.IsSubsetOf(current.granted) ||
				   set.IsSubsetOf(current.denied))
				{
					return false;
				}
				return true;
			}
Beispiel #2
0
 private static bool CanWriteToFolder(string folder)
 {
     var permission = new FileIOPermission(FileIOPermissionAccess.Write, folder);
     var permissionSet = new PermissionSet(PermissionState.None);
     permissionSet.AddPermission(permission);
     return permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);
 }
 /// <summary>
 /// Checks to see if DNS information is available to the caller
 /// 
 /// </summary>
 /// 
 /// <returns/>
 public bool GetIsDnsAvailable()
 {
   PermissionSet permissionSet = new PermissionSet(PermissionState.None);
   DnsPermission dnsPermission = new DnsPermission(PermissionState.Unrestricted);
   permissionSet.AddPermission((IPermission) dnsPermission);
   return permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);
 }
 /// <summary>
 /// Checks to see if Registry access is available to the caller
 /// 
 /// </summary>
 /// 
 /// <returns/>
 public bool GetIsRegistryAvailable()
 {
   PermissionSet permissionSet = new PermissionSet(PermissionState.None);
   RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted);
   permissionSet.AddPermission((IPermission) registryPermission);
   return permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);
 }
        public static bool NeedsAdministratorRights()
        {
            var permissionSet = new PermissionSet(PermissionState.None);
            var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, HostsFileManager.Filename);
            permissionSet.AddPermission(writePermission);

            return permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);
        }
        private bool HasSerializationFormatterPermission()
        {
#if(DOTNET35)
            return SecurityManager.IsGranted(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter));
#else
            var permission = new PermissionSet(PermissionState.None);
            permission.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
            return permission.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);
#endif
        }
		public static bool IsGranted(this IPermission permission)
		{
#if DOTNET35 || MONO26
			return SecurityManager.IsGranted(permission);
#else
			var permissionSet = new PermissionSet(PermissionState.None);
			permissionSet.AddPermission(permission);

			return permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);
#endif
		}
Beispiel #8
0
		internal static bool CheckAppDomainPermissions(PermissionSet permissions)
		{
			if (!AppDomain.CurrentDomain.IsHomogenous)
			{
				return false;
			}
			else
			{
				return permissions.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);
			}
		}
        private void CheckPermission()
        {
            var folder = ConfigurationManager.AppSettings["AttachmentsDirectory"];
            var permission = new FileIOPermission(FileIOPermissionAccess.Write, Server.MapPath(folder));
            var permissionSet = new PermissionSet(PermissionState.None);
            permissionSet.AddPermission(permission);

            if (!permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
            {
                WarningLabel.Text = String.Format(CultureInfo.CurrentUICulture, "The directory \"{0}\" is write protected", folder);
                //AttachmentPanel.Enabled = false;
            }
        }
Beispiel #10
0
        public static bool IsDirectoryWritable(string directory)
        {
            if (string.IsNullOrWhiteSpace(directory))
            {
                return false;
            }

            FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Write, HostingEnvironment.MapPath(directory));
            PermissionSet permissionSet = new PermissionSet(PermissionState.None);
            permissionSet.AddPermission(permission);

            return permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);
        }
Beispiel #11
0
        internal PermissionSetTriple UpdateAssert(PermissionSet in_a)
        {
            PermissionSetTriple retTriple = null;

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

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

                if (AssertSet == null)
                {
                    AssertSet = retPs;
                }
                else
                {
                    AssertSet.InplaceUnion(retPs);
                }
            }
            return(retTriple);
        }
Beispiel #12
0
        // Determine if a specific permission has been granted.
        public static bool IsGranted(IPermission perm)
        {
            // Bail out if the requested permission is null.
            if (perm == null)
            {
                return(true);
            }

            // Get the current permission state.
            ClrPermissions current = ClrSecurity.GetPermissionsFrom(1);

            if (current == null)
            {
                // Null is equivalent to "unrestricted".
                return(true);
            }

            // Build a permission set with just this permission.
            PermissionSet set = new PermissionSet(PermissionState.None);

            set.AddPermission(perm);

            // If "PermitOnly" is set, then only check that set.
            if (current.permitOnly != null)
            {
                return(set.IsSubsetOf(current.permitOnly));
            }

            // The permission must be granted, but not denied.
            if (!set.IsSubsetOf(current.granted) ||
                set.IsSubsetOf(current.denied))
            {
                return(false);
            }
            return(true);
        }
Beispiel #13
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);
        }
Beispiel #14
0
        internal static bool TryResolveGrantSet(Evidence evidence, out PermissionSet grantSet)
        {
            HostSecurityManager hostSecurityManager = AppDomain.CurrentDomain.HostSecurityManager;

            if (evidence.GetHostEvidence <GacInstalled>() != null)
            {
                grantSet = new PermissionSet(PermissionState.Unrestricted);
                return(true);
            }
            if ((hostSecurityManager.Flags & HostSecurityManagerOptions.HostResolvePolicy) == HostSecurityManagerOptions.HostResolvePolicy)
            {
                PermissionSet permissionSet = hostSecurityManager.ResolvePolicy(evidence);
                if (permissionSet == null)
                {
                    throw new PolicyException(Environment.GetResourceString("Policy_NullHostGrantSet", new object[]
                    {
                        hostSecurityManager.GetType().FullName
                    }));
                }
                if (AppDomain.CurrentDomain.IsHomogenous)
                {
                    if (permissionSet.IsEmpty())
                    {
                        throw new PolicyException(Environment.GetResourceString("Policy_NoExecutionPermission"));
                    }
                    PermissionSet permissionSet2 = AppDomain.CurrentDomain.ApplicationTrust.DefaultGrantSet.PermissionSet;
                    if (!permissionSet.IsUnrestricted() && (!permissionSet.IsSubsetOf(permissionSet2) || !permissionSet2.IsSubsetOf(permissionSet)))
                    {
                        throw new PolicyException(Environment.GetResourceString("Policy_GrantSetDoesNotMatchDomain", new object[]
                        {
                            hostSecurityManager.GetType().FullName
                        }));
                    }
                }
                grantSet = permissionSet;
                return(true);
            }
            else
            {
                if (AppDomain.CurrentDomain.IsHomogenous)
                {
                    grantSet = AppDomain.CurrentDomain.GetHomogenousGrantSet(evidence);
                    return(true);
                }
                grantSet = null;
                return(false);
            }
        }
Beispiel #15
0
        internal PermissionSetTriple UpdateAssert(PermissionSet in_a)
        {
            PermissionSetTriple permissionSetTriple = (PermissionSetTriple)null;

            if (in_a != null)
            {
                if (in_a.IsSubsetOf(this.AssertSet))
                {
                    return((PermissionSetTriple)null);
                }
                PermissionSet permissionSet;
                if (this.GrantSet != null)
                {
                    permissionSet = in_a.Intersect(this.GrantSet);
                }
                else
                {
                    this.GrantSet = new PermissionSet(true);
                    permissionSet = in_a.Copy();
                }
                bool bFailedToCompress = false;
                if (this.RefusedSet != null)
                {
                    permissionSet = PermissionSet.RemoveRefusedPermissionSet(permissionSet, this.RefusedSet, out bFailedToCompress);
                }
                if (!bFailedToCompress)
                {
                    bFailedToCompress = PermissionSet.IsIntersectingAssertedPermissions(permissionSet, this.AssertSet);
                }
                if (bFailedToCompress)
                {
                    permissionSetTriple = new PermissionSetTriple(this);
                    this.Reset();
                    this.GrantSet = permissionSetTriple.GrantSet.Copy();
                }
                if (this.AssertSet == null)
                {
                    this.AssertSet = permissionSet;
                }
                else
                {
                    this.AssertSet.InplaceUnion(permissionSet);
                }
            }
            return(permissionSetTriple);
        }
Beispiel #16
0
        public static PermissionSet ResolvePolicy(Evidence evidence, PermissionSet reqdPset, PermissionSet optPset, PermissionSet denyPset, out PermissionSet denied)
        {
            PermissionSet resolved = ResolvePolicy(evidence);

            // do we have the minimal permission requested by the assembly ?
            if ((reqdPset != null) && !reqdPset.IsSubsetOf(resolved))
            {
                throw new PolicyException(Locale.GetText(
                                              "Policy doesn't grant the minimal permissions required to execute the assembly."));
            }

            // do we check for execution rights ?
            if (CheckExecutionRights)
            {
                bool execute = false;
                // an empty permissionset doesn't include Execution
                if (resolved != null)
                {
                    // unless we have "Full Trust"...
                    if (resolved.IsUnrestricted())
                    {
                        execute = true;
                    }
                    else
                    {
                        // ... we need to find a SecurityPermission
                        IPermission security = resolved.GetPermission(typeof(SecurityPermission));
                        execute = _execution.IsSubsetOf(security);
                    }
                }

                if (!execute)
                {
                    throw new PolicyException(Locale.GetText(
                                                  "Policy doesn't grant the right to execute the assembly."));
                }
            }

            denied = denyPset;
            return(resolved);
        }
        internal PermissionSetTriple UpdateAssert(PermissionSet in_a)
        {
            PermissionSetTriple triple = null;

            if (in_a != null)
            {
                PermissionSet set;
                bool          flag;
                if (in_a.IsSubsetOf(this.AssertSet))
                {
                    return(null);
                }
                if (this.GrantSet != null)
                {
                    set = in_a.Intersect(this.GrantSet);
                }
                else
                {
                    this.GrantSet = new PermissionSet(true);
                    set           = in_a.Copy();
                }
                set = PermissionSet.RemoveRefusedPermissionSet(set, this.RefusedSet, out flag);
                if (!flag)
                {
                    flag = PermissionSet.IsIntersectingAssertedPermissions(set, this.AssertSet);
                }
                if (flag)
                {
                    triple = new PermissionSetTriple(this);
                    this.Reset();
                    this.GrantSet = triple.GrantSet.Copy();
                }
                if (this.AssertSet == null)
                {
                    this.AssertSet = set;
                    return(triple);
                }
                this.AssertSet.InplaceUnion(set);
            }
            return(triple);
        }
Beispiel #18
0
        public static bool isDirWritable(String name,bool isDir=true)
        {
            try
            {
                string directoryName = null;
                if (isDir)
                {
                    directoryName = name;
                }
                else
                {
                    directoryName = Path.GetDirectoryName(name);
                }

                if (!String.IsNullOrEmpty(directoryName))
                {
                    PermissionSet permissionSet = new PermissionSet(PermissionState.None);

                    FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, directoryName);

                    permissionSet.AddPermission(writePermission);

                    if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return false;
        }
        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);
        }
        private static bool ValidateFilePermissions (string filePath)
        {
            string directoryName = Directory.GetParent (filePath).FullName;

            PermissionSet permissionSet = new PermissionSet (PermissionState.None);

            FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, directoryName);

            permissionSet.AddPermission(writePermission);

            if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
Beispiel #21
0
        /// <summary>
        /// Check whether the current user has write permission to the specified path.
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static bool HasWritePermissionOnDir(string path)
        {
            var writeAllow = false;
            var writeDeny = false;
            try
            {
                var accessControlList = Directory.GetAccessControl(path);
                if (accessControlList == null)
                    return false;
                var accessRules = accessControlList.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
                if (accessRules == null)
                    return false;

                foreach (System.Security.AccessControl.FileSystemAccessRule rule in accessRules)
                {
                    if ((System.Security.AccessControl.FileSystemRights.Write & rule.FileSystemRights)
                            != System.Security.AccessControl.FileSystemRights.Write)
                    {
                        continue;
                    }
                    if (rule.AccessControlType == System.Security.AccessControl.AccessControlType.Allow)
                    {
                        writeAllow = true;
                    }
                    else if (rule.AccessControlType == System.Security.AccessControl.AccessControlType.Deny)
                    {
                        writeDeny = true;
                    }
                }
            }
            catch (System.PlatformNotSupportedException)
            {
//#if __MonoCS__
//                writeAllow = (0 == Syscall.access(path, AccessModes.W_OK));
//#endif
                #if __COCOA__
                // TODO check directory permissions
                writeAllow = true;
                #endif
            }
            catch(System.UnauthorizedAccessException) {
                var permission = new FileIOPermission(FileIOPermissionAccess.Write, path);
                var permissionSet = new PermissionSet(PermissionState.None);
                permissionSet.AddPermission(permission);
                if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
                {
                    return true;
                }
                else
                    return false;
            }

            return writeAllow && !writeDeny;
        }
Beispiel #22
0
        /// <summary>
        /// Check if user can write to selected DB location
        /// </summary>
        public bool havePermissions()
        {
            var permission = new FileIOPermission(FileIOPermissionAccess.Write,
                                                  DATABASE_LOCATION);
            var permissionSet = new PermissionSet(PermissionState.None);
            permissionSet.AddPermission(permission);

            return permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);
        }
Beispiel #23
0
        /// <summary>
        /// Gets the MIME content type for a given path extension.
        /// </summary>
        /// <param name="extension">The input path extension.</param>
        /// <param name="def">The default content type to return if any error occurs.</param>
        /// <returns>The path extension's MIME content type.</returns>
        public static string GetContentTypeForExtension(string extension, string def)
        {
            if (string.IsNullOrEmpty(extension))
            {
                return def;
            }
            string contentType = "";

            var permissionSet = new PermissionSet(PermissionState.None);
            permissionSet.AddPermission(new RegistryPermission(PermissionState.Unrestricted));
            if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
            {
                if (MimeTypes.ContainsKey(extension))
                    contentType = MimeTypes[extension];
                else
                    contentType = def;
            }

            permissionSet = new PermissionSet(PermissionState.None);
            permissionSet.AddPermission(new DnsPermission(PermissionState.Unrestricted));
            if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
            {
                //do something.... not at full trust
                try
                {
                    RegistryKey reg = Registry.ClassesRoot;
                    reg = reg.OpenSubKey(extension, false);
                    if (reg != null) contentType = (string)reg.GetValue("", def);
                }
                catch (Exception)
                {
                    contentType = def;
                }
            }
            return contentType;
        }
        internal static bool CheckAppDomainPermissions(PermissionSet permissions)
        {

            return AppDomain.CurrentDomain.IsHomogenous &&
                   permissions.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);
        }
        // Given a set of evidence and some permission requests, resolve policy
        // and compare the result against the given grant & deny sets. Return
        // whether the two are equivalent.
        static private bool CheckGrantSets(Evidence evidence,
                                           PermissionSet minimal,
                                           PermissionSet optional,
                                           PermissionSet refused,
                                           PermissionSet granted,
                                           PermissionSet denied)
        {
            PermissionSet newGranted = null;
            PermissionSet newDenied  = null;
            int           isUnrestricted;

            try {
                newGranted = ResolvePolicy(evidence,
                                           minimal,
                                           optional,
                                           refused,
                                           out newDenied,
                                           out isUnrestricted,
                                           true);
            } catch {
                return(false);
            }

            if (granted == null)
            {
                if ((newGranted != null) && !newGranted.IsEmpty())
                {
                    return(false);
                }
            }
            else
            {
                if (newGranted == null)
                {
                    return(granted.IsEmpty());
                }

                try
                {
                    if (!granted.IsSubsetOf(newGranted) ||
                        !newGranted.IsSubsetOf(granted))
                    {
                        return(false);
                    }
                }
                catch (Exception)
                {
                    // We catch any exception and just return false.
                    // This has to be done because not all permissions
                    // may support the IsSubsetOf operation.
                    return(false);
                }
            }

            if (denied == null)
            {
                if ((newDenied != null) && !newDenied.IsEmpty())
                {
                    return(false);
                }
            }
            else
            {
                if (newDenied == null)
                {
                    return(denied.IsEmpty());
                }

                try
                {
                    if (!denied.IsSubsetOf(newDenied) ||
                        !newDenied.IsSubsetOf(denied))
                    {
                        return(false);
                    }
                }
                catch (Exception)
                {
                    // We catch any exception and just return false.
                    // This has to be done because not all permissions
                    // may support the IsSubsetOf operation.
                    return(false);
                }
            }

            return(true);
        }
Beispiel #26
0
 public static bool CheckWriteAccess(string path)
 {
     PermissionSet permissionSet = new PermissionSet(PermissionState.None);
     FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, path);
     permissionSet.AddPermission(writePermission);
     return permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);
 }
		public void IsSubset_OneNonIUnrestrictedPermission ()
		{
			ZoneIdentityPermission zip = new ZoneIdentityPermission (SecurityZone.MyComputer);
			PermissionSet ps1 = new PermissionSet (PermissionState.None);
			ps1.AddPermission (zip);
			PermissionSet ps2 = new PermissionSet (PermissionState.None);
			Assert.IsTrue (!ps1.IsSubsetOf (null), "PS1.IsSubset(null)");
			Assert.IsTrue (!ps1.IsSubsetOf (ps2), "PS1.IsSubset(None)");
			Assert.IsTrue (ps2.IsSubsetOf (ps1), "None.IsSubset(PS1)");

			PermissionSet ps3 = ps1.Copy ();
			Assert.IsTrue (ps1.IsSubsetOf (ps3), "PS1.IsSubset(PS3)");
			Assert.IsTrue (ps3.IsSubsetOf (ps1), "PS3.IsSubset(PS1)");

			PermissionSet ups1 = new PermissionSet (PermissionState.Unrestricted);
			ups1.AddPermission (zip);
			Assert.IsTrue (ps1.IsSubsetOf (ups1), "PS1.IsSubset(Unrestricted)");
			Assert.IsTrue (!ups1.IsSubsetOf (ps1), "Unrestricted.IsSubset(PS1)");

			PermissionSet ups2 = new PermissionSet (PermissionState.Unrestricted);
#if NET_2_0
			// as ZoneIdentityPermission isn't added UPS1Z == UPS2
			Assert.IsTrue (ups1.IsSubsetOf (ups2), "UPS1Z.IsSubset(UPS2)");
#else
			Assert.IsTrue (!ups1.IsSubsetOf (ups2), "UPS1Z.IsSubset(UPS2)");
#endif
			Assert.IsTrue (ups2.IsSubsetOf (ups1), "UPS2.IsSubset(UPS1Z)");
			ups2.AddPermission (zip);
			Assert.IsTrue (ups1.IsSubsetOf (ups2), "UPS1Z.IsSubset(UPS2Z)");
			Assert.IsTrue (ups2.IsSubsetOf (ups1), "UPS2Z.IsSubset(UPS1Z)");
		}
Beispiel #28
0
        /// <summary>
        /// Gets the path extension for a given MIME content type.
        /// </summary>
        /// <param name="contentType">The input MIME content type.</param>
        /// <param name="def">The default path extension to return if any error occurs.</param>
        /// <returns>The MIME content type's path extension.</returns>
        public static string GetExtensionForContentType(string contentType, string def)
        {
            if (string.IsNullOrEmpty(contentType))
            {
                return def;
            }
            string ext = "";

            var permissionSet = new PermissionSet(PermissionState.None);
            permissionSet.AddPermission(new RegistryPermission(PermissionState.Unrestricted));
            if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
            {
                if (MimeTypes.ContainsValue(contentType))
                {
                    foreach (KeyValuePair<string, string> pair in MimeTypes)
                        if (pair.Value == contentType)
                            return pair.Value;
                }
                return def;
            }

            if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
            {
                try
                {
                    RegistryKey reg = Registry.ClassesRoot;
                    reg = reg.OpenSubKey(@"MIME\Database\Content Type\" + contentType, false);
                    if (reg != null) ext = (string)reg.GetValue("Extension", def);
                }
                catch (Exception)
                {
                    ext = def;
                }
            }
            return ext;
        }
Beispiel #29
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 IsSubset_Empty ()
		{
			PermissionSet ps1 = new PermissionSet (PermissionState.None);
			PermissionSet ps2 = new PermissionSet (PermissionState.None);
			Assert.IsTrue (ps1.IsSubsetOf (null), "None.IsSubsetOf(null)");
			Assert.IsTrue (ps1.IsSubsetOf (ps2), "None1.IsSubsetOf(None2)");
			Assert.IsTrue (ps2.IsSubsetOf (ps1), "None2.IsSubsetOf(None1)");

			PermissionSet ups1 = new PermissionSet (PermissionState.Unrestricted);
			Assert.IsTrue (ps1.IsSubsetOf (ups1), "None1.IsSubsetOf(Unrestricted)");
			Assert.IsTrue (!ups1.IsSubsetOf (ps1), "Unrestricted.IsSubsetOf(None1)");
			Assert.IsTrue (!ups1.IsSubsetOf (null), "Unrestricted.IsSubsetOf(Null)");

			PermissionSet ups2 = new PermissionSet (PermissionState.Unrestricted);
			Assert.IsTrue (ups1.IsSubsetOf (ups2), "ups1IsSubsetOf(ups2)");
			Assert.IsTrue (ups2.IsSubsetOf (ups1), "ups2.IsSubsetOf(ups1)");
		}
Beispiel #31
0
        /// <summary>
        /// Creates an _instance of logger. If rootDirectory doesn't exist tries to create it.
        /// If everything is successfull sets IsInited to true.
        /// </summary>
        /// <param name="rootDirectory">The directory, where logs should be created.</param>
        /// <param name="level">Level of loggin. Pass LogLevel.Off for turning off logging.</param>
        /// <exception cref="AtTaskException">
        ///     Code: FILE_ACCESS_ERROR: when the rootDirectory doesn't exist and couldn't be created or
        ///         when there is no permosision to write files in that directory
        /// </exception>
        private Logger(string rootDirectory, LogLevel level)
        {
            try
            {
                if (string.IsNullOrEmpty(rootDirectory))
                {
                    rootDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Logs");

                    //throw new ArgumentException("rootDirectory is null or empty");
                    return;
                }

                if (!Directory.Exists(rootDirectory))
                {
                    try
                    {
                        Directory.CreateDirectory(rootDirectory);
                    }
                    catch (IOException)
                    {
                        //throw new AtTaskException(AtTaskExceptionCode.FILE_ACCESS_ERROR, ex);
                        return;
                    }
                }

                FileIOPermission directoryPermission = new FileIOPermission(FileIOPermissionAccess.Append, rootDirectory);

                PermissionSet permissionSet = new PermissionSet(PermissionState.None);
                permissionSet.AddPermission(directoryPermission);
                if (!permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
                {
                    //throw new AtTaskException(AtTaskExceptionCode.FILE_ACCESS_ERROR);
                    return;
                }

                this.rootDirectory = rootDirectory;
                Level = level;

                IsInitied = true;
            }
            catch
            {
                //DO NOTHING
            }
        }
Beispiel #32
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;
        }
        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);
        }
        [System.Security.SecurityCritical]  // auto-generated
        internal PermissionSetTriple UpdateAssert(PermissionSet in_a)
        {
            PermissionSetTriple retTriple = null;
            if (in_a != null)
            {
                Contract.Assert((!in_a.IsUnrestricted() || RefusedSet == null), "Cannot be unrestricted or refused must be null");
                // if we're already asserting in_a, nothing to do
                if (in_a.IsSubsetOf(AssertSet))
                    return null;

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

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

            }
            return retTriple;
        }
		public void IsSubset_OnePermission ()
		{
			SecurityPermission sp = new SecurityPermission (SecurityPermissionFlag.Assertion);
			PermissionSet ps1 = new PermissionSet (PermissionState.None);
			ps1.AddPermission (sp);
			PermissionSet ps2 = new PermissionSet (PermissionState.None);
			Assert.IsTrue (!ps1.IsSubsetOf (null), "PS1.IsSubset(null)");
			Assert.IsTrue (!ps1.IsSubsetOf (ps2), "PS1.IsSubset(None)");
			Assert.IsTrue (ps2.IsSubsetOf (ps1), "None.IsSubset(PS1)");

			PermissionSet ps3 = ps1.Copy ();
			Assert.IsTrue (ps1.IsSubsetOf (ps3), "PS1.IsSubset(PS3)");
			Assert.IsTrue (ps3.IsSubsetOf (ps1), "PS3.IsSubset(PS1)");

			PermissionSet ups1 = new PermissionSet (PermissionState.Unrestricted);
			Assert.IsTrue (ps1.IsSubsetOf (ups1), "PS1.IsSubset(Unrestricted)");
			Assert.IsTrue (!ups1.IsSubsetOf (ps1), "Unrestricted.IsSubset(PS1)");
		}
        internal static bool TryResolveGrantSet(Evidence evidence, out PermissionSet grantSet)
        {
            Contract.Assert(evidence != null);

            HostSecurityManager securityManager = AppDomain.CurrentDomain.HostSecurityManager;

            // GAC assemblies always are fully trusted
            if (evidence.GetHostEvidence <GacInstalled>() != null)
            {
                grantSet = new PermissionSet(PermissionState.Unrestricted);
                return(true);
            }
            // If the host wants to participate in policy resolution, then our next option is to ask it for
            // a grant set
            else if ((securityManager.Flags & HostSecurityManagerOptions.HostResolvePolicy) == HostSecurityManagerOptions.HostResolvePolicy)
            {
                PermissionSet hostGrantSet = securityManager.ResolvePolicy(evidence);

                if (hostGrantSet == null)
                {
                    throw new PolicyException(Environment.GetResourceString("Policy_NullHostGrantSet", securityManager.GetType().FullName));
                }

                // If we're in a homogenous domain, we don't want to allow the host to create multiple
                // levels of permissions within the domain.  So, if we see the host return something other
                // than full trust or the homogenous grant set, we reject the grant set.
                if (AppDomain.CurrentDomain.IsHomogenous)
                {
                    // Some hosts, such as ASP.NET, return Nothing as a way of saying that the assembly should
                    // not be allowed to run in the AppDomain.  Reject that with a specific
                    // no-execution-allowed-here exception message, rather than the return value validation
                    // exception message we'd hit below.
                    if (hostGrantSet.IsEmpty())
                    {
                        throw new PolicyException(Environment.GetResourceString("Policy_NoExecutionPermission"));
                    }

                    PermissionSet homogenousGrantSet = AppDomain.CurrentDomain.ApplicationTrust.DefaultGrantSet.PermissionSet;
                    bool          isValidGrantSet    = hostGrantSet.IsUnrestricted() ||
                                                       (hostGrantSet.IsSubsetOf(homogenousGrantSet) && homogenousGrantSet.IsSubsetOf(hostGrantSet));

                    if (!isValidGrantSet)
                    {
                        throw new PolicyException(Environment.GetResourceString("Policy_GrantSetDoesNotMatchDomain", securityManager.GetType().FullName));
                    }
                }

                grantSet = hostGrantSet;
                return(true);
            }
            // If we're in a homogenous domain, we can get the grant set directly from the application trust
            else if (AppDomain.CurrentDomain.IsHomogenous)
            {
                grantSet = AppDomain.CurrentDomain.GetHomogenousGrantSet(evidence);
                return(true);
            }
            // Otherwise we have no way to figure out what the grant set is
            else
            {
                grantSet = null;
                return(false);
            }
        }
		public void IsSubset_NonCasPermission_Unrestricted ()
		{
			PermissionSet ps1 = new PermissionSet (PermissionState.None);
			ps1.AddPermission (new PrincipalPermission (PermissionState.Unrestricted));
			PermissionSet ps2 = new PermissionSet (PermissionState.None);
			Assert.IsTrue (!ps1.IsSubsetOf (null), "PS1.IsSubset(null)");
			Assert.IsTrue (!ps1.IsSubsetOf (ps2), "PS1.IsSubset(None)");
			Assert.IsTrue (ps2.IsSubsetOf (ps1), "None.IsSubset(PS1)");

			PermissionSet ps3 = ps1.Copy ();
			Assert.IsTrue (ps1.IsSubsetOf (ps3), "PS1.IsSubset(PS3)");
			Assert.IsTrue (ps3.IsSubsetOf (ps1), "PS3.IsSubset(PS1)");

			PermissionSet ups1 = new PermissionSet (PermissionState.Unrestricted);
#if NET_2_0
			Assert.IsTrue (ps1.IsSubsetOf (ups1), "PS1.IsSubset(Unrestricted)");
#else
			Assert.IsTrue (!ps1.IsSubsetOf (ups1), "PS1.IsSubset(Unrestricted)");
#endif
			Assert.IsTrue (!ups1.IsSubsetOf (ps1), "Unrestricted.IsSubset(PS1)");
		}
Beispiel #38
0
        private static bool ValidateArgs(string[] args, out StorgaeExporterConfiguration configuration)
        {
            configuration = null;
            if (args.Count() < 2)
            {
                ConsoleUtils.ConsoleWriteLineWithColor(ConsoleColor.Red, "Not enough arguments were provided.\n");
                return false;
            }
            if (!Directory.Exists(args[0]))
            {
                ConsoleUtils.ConsoleWriteLineWithColor(ConsoleColor.Red, "Directory {0} does not exists.\n",args[0]);                
                return false; 
            }
            if (!StorageExporter.ValidateStorageExsist(args[0]))
            {
                ConsoleUtils.ConsoleWriteLineWithColor(ConsoleColor.Red, "Directory {0} is not a valid RavenDB storage directory.\n", args[0]);
                return false; 
            }
            var outputDirectory = Path.GetDirectoryName(args[1]);
            if (!Directory.Exists(outputDirectory))
            {
                ConsoleUtils.ConsoleWriteLineWithColor(ConsoleColor.Red, "Output directory {0} does not exists.\n", outputDirectory);
                return false;
            }
            var permissionSet = new PermissionSet(PermissionState.None);
            var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, args[1]);
            permissionSet.AddPermission(writePermission);

            if (!permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
            {
                ConsoleUtils.ConsoleWriteLineWithColor(ConsoleColor.Red, "You don't have premissions to write to {0}.\n", args[1]);
            }
            if (args.Length % 2 != 0)
            {
                ConsoleUtils.ConsoleWriteLineWithColor(ConsoleColor.Red, "Wrong amount of arguments were passed.\n");
                return false;
            }           
            var currArgPos = 2;
            configuration = new StorgaeExporterConfiguration() {DatabaseDataDir = args[0], OutputDumpPath = args[1]};
            while (currArgPos < args.Length)
            {
                switch (args[currArgPos])
                {
                    case "-T":
                        configuration.TableName = args[currArgPos + 1];
                        currArgPos += 2;
                        break;
                    case "-BatchSize":
                        int batchSize;
                        if (int.TryParse(args[currArgPos + 1], out batchSize) && batchSize > 0)
                        {
                            configuration.BatchSize = batchSize;
                            currArgPos += 2;
                        }
                        else
                        {
                            ConsoleUtils.ConsoleWriteLineWithColor(ConsoleColor.Red, "BatchSize should be an integer number greater than 0 (BatchSize={0}).\n", args[currArgPos + 1]);
                            return false;
                        }
                        break;
                    default:
                        ConsoleUtils.ConsoleWriteLineWithColor(ConsoleColor.Red, "Unidentified argument {0}.\n");
                        break;
                }
            }
            return true;
        }
Beispiel #39
0
		public static PermissionSet ResolvePolicy (Evidence evidence, PermissionSet reqdPset, PermissionSet optPset, PermissionSet denyPset, out PermissionSet denied)
		{
			PermissionSet resolved = ResolvePolicy (evidence);
			// do we have the minimal permission requested by the assembly ?
			if ((reqdPset != null) && !reqdPset.IsSubsetOf (resolved)) {
				throw new PolicyException (Locale.GetText (
					"Policy doesn't grant the minimal permissions required to execute the assembly."));
			}

			// do we check for execution rights ?
			if (CheckExecutionRights) {
				bool execute = false;
				// an empty permissionset doesn't include Execution
				if (resolved != null) {
					// unless we have "Full Trust"...
					if (resolved.IsUnrestricted ()) {
						execute = true;
					} else {
						// ... we need to find a SecurityPermission
						IPermission security = resolved.GetPermission (typeof (SecurityPermission));
						execute = _execution.IsSubsetOf (security);
					}
				}

				if (!execute) {
					throw new PolicyException (Locale.GetText (
						"Policy doesn't grant the right to execute the assembly."));
				}
			}

			denied = denyPset;
			return resolved;
		}
        [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 Demand()
			{
				// Get the current permission state.
				ClrPermissions current = ClrSecurity.GetPermissionsFrom(1);
				if(current == null)
				{
					// Null is equivalent to "unrestricted".
					return;
				}

				// Build a permission set with just this permission.
				PermissionSet set = new PermissionSet(PermissionState.None);
				set.AddPermission(this);

				// If "PermitOnly" is set, then only check that set.
				if(current.permitOnly != null)
				{
					if(!set.IsSubsetOf(current.permitOnly))
					{
						throw new SecurityException
							(_("Exception_SecurityNotGranted"));
					}
					return;
				}

				// The permission must be granted, but not denied.
				if(!set.IsSubsetOf(current.granted) ||
				   set.IsSubsetOf(current.denied))
				{
					throw new SecurityException
						(_("Exception_SecurityNotGranted"));
				}
			}
        /// <summary>
        /// Checks to see if DNS information is available to the caller
        /// </summary>
        /// <returns></returns>
        public bool GetIsDnsAvailable()
        {
#if NET40 || NET451
            var permissionSet = new PermissionSet(PermissionState.None);    
            var writePermission = new DnsPermission(PermissionState.Unrestricted);
            permissionSet.AddPermission(writePermission);

            return permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);
#elif NET20
			return SecurityManager.IsGranted(new DnsPermission(PermissionState.Unrestricted));
#else
            return false;
#endif
        }