Example #1
0
        private static PermissionSet /*!*/ CreatePermissionSetByName()
        {
            string        name            = "Internet";
            bool          foundName       = false;
            PermissionSet setIntersection = new PermissionSet(PermissionState.Unrestricted);

            // iterate over each policy level
            IEnumerator e = SecurityManager.PolicyHierarchy();

            while (e.MoveNext())
            {
                PolicyLevel   level    = (PolicyLevel)e.Current;
                PermissionSet levelSet = level.GetNamedPermissionSet(name);
                if (levelSet != null)
                {
                    foundName       = true;
                    setIntersection = setIntersection.Intersect(levelSet);
                }
            }

            if (setIntersection == null || !foundName)
            {
                setIntersection = new PermissionSet(PermissionState.None);
            }
            else
            {
                setIntersection = new NamedPermissionSet(name, setIntersection);
            }

            return(setIntersection);
        }
        public static PermissionSet Intersect(this PermissionSet permissionSet, IPermission permission)
        {
            PermissionSet singlePermissionSet = new PermissionSet(PermissionState.None);

            singlePermissionSet.AddPermission(permission);
            return(permissionSet.Intersect(singlePermissionSet));
        }
Example #3
0
    // source: http://blogs.msdn.com/shawnfa/archive/2004/10/22/246549.aspx
    static PermissionSet GetNamedPermissionSet(string name)
    {
        bool          foundName = false;
        PermissionSet pset      = new PermissionSet(PermissionState.Unrestricted);

        IEnumerator e = SecurityManager.PolicyHierarchy();

        while (e.MoveNext())
        {
            PolicyLevel pl = e.Current as PolicyLevel;

            PermissionSet levelpset = pl.GetNamedPermissionSet(name);
            if ((levelpset != null) && (pset != null))
            {
                foundName = true;
                pset      = pset.Intersect(levelpset);
            }
        }

        if (pset == null || !foundName)
        {
            return(new PermissionSet(PermissionState.None));
        }

        return(new NamedPermissionSet(name, pset));
    }
Example #4
0
 public static void PermissionSetCallMethods()
 {
     PermissionSet ps = new PermissionSet(new PermissionState());
     ps.Assert();
     bool containspermissions = ps.ContainsNonCodeAccessPermissions();
     PermissionSet ps2 = ps.Copy();
     ps.CopyTo(new int[1], 0);
     ps.Demand();
     ps.Equals(ps2);
     System.Collections.IEnumerator ie = ps.GetEnumerator();
     int hash = ps.GetHashCode();
     PermissionSet ps3 = ps.Intersect(ps2);
     bool isempty = ps.IsEmpty();
     bool issubsetof = ps.IsSubsetOf(ps2);
     bool isunrestricted = ps.IsUnrestricted();
     string s = ps.ToString();
     PermissionSet ps4 = ps.Union(ps2);
     SecurityElement se = new SecurityElement("");
     ps.FromXml(se);
     se = ps.ToXml();
 }
Example #5
0
	// source: http://blogs.msdn.com/shawnfa/archive/2004/10/22/246549.aspx	
	static PermissionSet GetNamedPermissionSet (string name)
	{
		bool foundName = false;
		PermissionSet pset = new PermissionSet (PermissionState.Unrestricted);

		IEnumerator e = SecurityManager.PolicyHierarchy ();
		while (e.MoveNext ()) {
			PolicyLevel pl = e.Current as PolicyLevel;

			PermissionSet levelpset = pl.GetNamedPermissionSet (name);
			if ((levelpset != null) && (pset != null)) {
				foundName = true;
				pset = pset.Intersect (levelpset);
			}
		}

		if (pset == null || !foundName)
			return new PermissionSet (PermissionState.None);

		return new NamedPermissionSet (name, pset);
	}
Example #6
0
        private static PermissionSet /*!*/ CreatePermissionSet()
        {
#if CLR2
            string        name            = "Internet";
            bool          foundName       = false;
            PermissionSet setIntersection = new PermissionSet(PermissionState.Unrestricted);

            // iterate over each policy level
            IEnumerator e = SecurityManager.PolicyHierarchy();
            while (e.MoveNext())
            {
                PolicyLevel   level    = (PolicyLevel)e.Current;
                PermissionSet levelSet = level.GetNamedPermissionSet(name);
                if (levelSet != null)
                {
                    foundName       = true;
                    setIntersection = setIntersection.Intersect(levelSet);
                }
            }

            if (setIntersection == null || !foundName)
            {
                setIntersection = new PermissionSet(PermissionState.None);
            }
            else
            {
                setIntersection = new NamedPermissionSet(name, setIntersection);
            }

            return(setIntersection);
#else
            // this functionality is not available on Mono (AddHostEvidence is undefined), use dynamic to resolve it at runtime
            dynamic e = new Evidence();
            e.AddHostEvidence(new Zone(SecurityZone.Internet));
            return(SecurityManager.GetStandardSandbox((Evidence)e));
#endif
        }
Example #7
0
        public static void PermissionSetCallMethods()
        {
            PermissionSet ps = new PermissionSet(new PermissionState());

            ps.Assert();
            bool          containspermissions = ps.ContainsNonCodeAccessPermissions();
            PermissionSet ps2 = ps.Copy();

            ps.CopyTo(new int[1], 0);
            ps.Demand();
            ps.Equals(ps2);
            System.Collections.IEnumerator ie = ps.GetEnumerator();
            int             hash           = ps.GetHashCode();
            PermissionSet   ps3            = ps.Intersect(ps2);
            bool            isempty        = ps.IsEmpty();
            bool            issubsetof     = ps.IsSubsetOf(ps2);
            bool            isunrestricted = ps.IsUnrestricted();
            string          s   = ps.ToString();
            PermissionSet   ps4 = ps.Union(ps2);
            SecurityElement se  = new SecurityElement("");

            ps.FromXml(se);
            se = ps.ToXml();
        }
Example #8
0
        /// <summary>
        /// Create an AppDomain that contains policy restricting code to execute
        /// with only the permissions granted by a named permission set
        /// </summary>
        /// <param name="permissionSetName">name of the permission set to restrict to</param>
        /// <param name="appDomainName">'friendly' name of the appdomain to be created</param>
        /// <exception cref="ArgumentNullException">
        /// if <paramref name="permissionSetName"/> is null
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// if <paramref name="permissionSetName"/> is empty
        /// </exception>
        /// <returns>AppDomain with a restricted security policy</returns>
        /// <remarks>Substantial portions of this function from: http://blogs.msdn.com/shawnfa/archive/2004/10/25/247379.aspx
        /// Valid permissionSetName values are:
        /// * FullTrust
        /// * SkipVerification
        /// * Execution
        /// * Nothing
        /// * LocalIntranet
        /// * Internet
        /// * Everything
        /// </remarks>
#pragma warning disable 0618
        public static AppDomain CreateRestrictedDomain(string permissionSetName, string appDomainName)
        {
            if (permissionSetName == null)
            {
                throw new ArgumentNullException("permissionSetName");
            }
            if (permissionSetName.Length == 0)
            {
                throw new ArgumentOutOfRangeException("permissionSetName", permissionSetName,
                                                      "Cannot have an empty permission set name");
            }

            // Default to all code getting nothing
            PolicyStatement emptyPolicy = new PolicyStatement(new PermissionSet(PermissionState.None));
            UnionCodeGroup  policyRoot  = new UnionCodeGroup(new AllMembershipCondition(), emptyPolicy);

            bool          foundName       = false;
            PermissionSet setIntersection = new PermissionSet(PermissionState.Unrestricted);

            // iterate over each policy level
            IEnumerator levelEnumerator = SecurityManager.PolicyHierarchy();

            while (levelEnumerator.MoveNext())
            {
                PolicyLevel level = levelEnumerator.Current as PolicyLevel;

                // if this level has defined a named permission set with the
                // given name, then intersect it with what we've retrieved
                // from all the previous levels
                if (level != null)
                {
                    PermissionSet levelSet = level.GetNamedPermissionSet(permissionSetName);
                    if (levelSet != null)
                    {
                        foundName = true;
                        if (setIntersection != null)
                        {
                            setIntersection = setIntersection.Intersect(levelSet);
                        }
                    }
                }
            }

            // Intersect() can return null for an empty set, so convert that
            // to an empty set object. Also return an empty set if we didn't find
            // the named permission set we were looking for
            if (setIntersection == null || !foundName)
            {
                setIntersection = new PermissionSet(PermissionState.None);
            }
            else
            {
                setIntersection = new NamedPermissionSet(permissionSetName, setIntersection);
            }

            // if no named permission sets were found, return an empty set,
            // otherwise return the set that was found
            PolicyStatement permissions = new PolicyStatement(setIntersection);

            policyRoot.AddChild(new UnionCodeGroup(new AllMembershipCondition(), permissions));

            // create an AppDomain policy level for the policy tree
            PolicyLevel appDomainLevel = PolicyLevel.CreateAppDomainLevel();

            appDomainLevel.RootCodeGroup = policyRoot;

            // create an AppDomain where this policy will be in effect
            string    domainName       = appDomainName;
            AppDomain restrictedDomain = AppDomain.CreateDomain(domainName);

            restrictedDomain.SetAppDomainPolicy(appDomainLevel);

            return(restrictedDomain);
        }
        /// From MRMModule.cs by Adam Frisby
        /// <summary>
        ///     Create an AppDomain that contains policy restricting code to execute
        ///     with only the permissions granted by a named permission set
        /// </summary>
        /// <param name="permissionSetName">name of the permission set to restrict to</param>
        /// <param name="appDomainName">'friendly' name of the appdomain to be created</param>
        /// <param name="ads"></param>
        /// <exception cref="ArgumentNullException">
        ///     if <paramref name="permissionSetName" /> is null
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        ///     if <paramref name="permissionSetName" /> is empty
        /// </exception>
        /// <returns>AppDomain with a restricted security policy</returns>
        /// <remarks>
        ///     Substantial portions of this function from: http://blogs.msdn.com/shawnfa/archive/2004/10/25/247379.aspx
        ///     Valid permissionSetName values are:
        ///     * FullTrust
        ///     * SkipVerification
        ///     * Execution
        ///     * Nothing
        ///     * LocalIntranet
        ///     * Internet
        ///     * Everything
        /// </remarks>
        public AppDomain CreateRestrictedDomain(string permissionSetName, string appDomainName, AppDomainSetup ads)
        {
            if (permissionSetName == null)
            {
                throw new ArgumentNullException("permissionSetName");
            }
            if (permissionSetName.Length == 0)
            {
                throw new ArgumentOutOfRangeException("permissionSetName", permissionSetName,
                                                      "Cannot have an empty permission set name");
            }

            // Default to all code getting everything
            PermissionSet setIntersection  = new PermissionSet(PermissionState.Unrestricted);
            AppDomain     restrictedDomain = null;

#if LINUX
        #pragma warning disable 612, 618
            PolicyStatement emptyPolicy = new PolicyStatement(new PermissionSet(PermissionState.None));
            UnionCodeGroup  policyRoot  = new UnionCodeGroup(new AllMembershipCondition(), emptyPolicy);

            bool foundName = false;
            // iterate over each policy level
            IEnumerator levelEnumerator = SecurityManager.PolicyHierarchy();
            while (levelEnumerator.MoveNext())
            {
                PolicyLevel level = levelEnumerator.Current as PolicyLevel;

                // if this level has defined a named permission set with the
                // given name, then intersect it with what we've retrieved
                // from all the previous levels
                if (level != null)
                {
                    PermissionSet levelSet = level.GetNamedPermissionSet(permissionSetName);
                    if (levelSet != null)
                    {
                        foundName = true;
                        if (setIntersection != null)
                        {
                            setIntersection = setIntersection.Intersect(levelSet);
                        }
                    }
                }
            }

            // Intersect() can return null for an empty set, so convert that
            // to an empty set object. Also return an empty set if we didn't find
            // the named permission set we were looking for
            if (setIntersection == null || !foundName)
            {
                setIntersection = new PermissionSet(PermissionState.None);
            }
            else
            {
                setIntersection = new NamedPermissionSet(permissionSetName, setIntersection);
            }

            // if no named permission sets were found, return an empty set,
            // otherwise return the set that was found
            setIntersection.AddPermission(new SocketPermission(PermissionState.Unrestricted));
            setIntersection.AddPermission(new WebPermission(PermissionState.Unrestricted));
            setIntersection.AddPermission(new SecurityPermission(PermissionState.Unrestricted));

            PolicyStatement permissions = new PolicyStatement(setIntersection);
            policyRoot.AddChild(new UnionCodeGroup(new AllMembershipCondition(), permissions));

            // create an AppDomain policy level for the policy tree
            PolicyLevel appDomainLevel = PolicyLevel.CreateAppDomainLevel();
            appDomainLevel.RootCodeGroup = policyRoot;

            // create an AppDomain where this policy will be in effect
            restrictedDomain = AppDomain.CreateDomain(appDomainName, null, ads);
            restrictedDomain.SetAppDomainPolicy(appDomainLevel);
        #pragma warning restore 612, 618
#else
            SecurityZone zone = SecurityZone.MyComputer;
            try
            {
                zone = (SecurityZone)Enum.Parse(typeof(SecurityZone), permissionSetName);
            }
            catch
            {
                zone = SecurityZone.MyComputer;
            }

            Evidence ev = new Evidence();
            ev.AddHostEvidence(new Zone(zone));
            setIntersection = SecurityManager.GetStandardSandbox(ev);
            setIntersection.AddPermission(new System.Net.SocketPermission(PermissionState.Unrestricted));
            setIntersection.AddPermission(new System.Net.WebPermission(PermissionState.Unrestricted));
            setIntersection.AddPermission(
                new System.Security.Permissions.SecurityPermission(PermissionState.Unrestricted));

            // create an AppDomain where this policy will be in effect
            restrictedDomain = AppDomain.CreateDomain(appDomainName, ev, ads, setIntersection, null);
#endif

            return(restrictedDomain);
        }
Example #10
0
        // -rsp assemblyname
        // -resolveperm assemblyname
        static bool ResolvePermissions(string assemblyname)
        {
            Evidence ev = GetAssemblyEvidences(assemblyname);

            if (ev == null)
            {
                return(false);
            }

            PermissionSet ps = null;

            Console.WriteLine();
            if (policyLevelDefault)
            {
                // different "default" here
                IEnumerator e = SecurityManager.PolicyHierarchy();
                while (e.MoveNext())
                {
                    PolicyLevel pl = (PolicyLevel)e.Current;
                    Console.WriteLine("Resolving {0} level", pl.Label);
                    if (ps == null)
                    {
                        ps = pl.Resolve(ev).PermissionSet;
                    }
                    else
                    {
                        ps = ps.Intersect(pl.Resolve(ev).PermissionSet);
                    }
                }
            }
            else
            {
                // use the user specified levels
                foreach (PolicyLevel pl in Levels)
                {
                    Console.WriteLine("Resolving {0} level", pl.Label);
                    if (ps == null)
                    {
                        ps = pl.Resolve(ev).PermissionSet;
                    }
                    else
                    {
                        ps = ps.Intersect(pl.Resolve(ev).PermissionSet);
                    }
                }
            }
            if (ps == null)
            {
                return(false);
            }

            IEnumerator ee = ev.GetHostEnumerator();

            while (ee.MoveNext())
            {
                IIdentityPermissionFactory ipf = (ee.Current as IIdentityPermissionFactory);
                if (ipf != null)
                {
                    IPermission p = ipf.CreateIdentityPermission(ev);
                    ps.AddPermission(p);
                }
            }

            Console.WriteLine("{0}Grant:{0}{1}", Environment.NewLine, ps.ToXml().ToString());
            return(true);
        }
Example #11
0
 public static void PermissionSetDemo()
 {
     Console.WriteLine("Executing PermissionSetDemo");
     try
     {
         //<Snippet2>
         // Open a new PermissionSet.
         PermissionSet ps1 = new PermissionSet(PermissionState.None);
         Console.WriteLine("Adding permission to open a file from a file dialog box.");
         //<Snippet3>
         // Add a permission to the permission set.
         ps1.AddPermission(
             new FileDialogPermission(FileDialogPermissionAccess.Open));
         //</Snippet3>
         Console.WriteLine("Demanding permission to open a file.");
         ps1.Demand();
         Console.WriteLine("Demand succeeded.");
         //</Snippet2>
         Console.WriteLine("Adding permission to save a file from a file dialog box.");
         ps1.AddPermission(
             new FileDialogPermission(FileDialogPermissionAccess.Save));
         Console.WriteLine("Demanding permission to open and save a file.");
         ps1.Demand();
         Console.WriteLine("Demand succeeded.");
         Console.WriteLine("Adding permission to read environment variable USERNAME.");
         ps1.AddPermission(
             new EnvironmentPermission(EnvironmentPermissionAccess.Read, "USERNAME"));
         ps1.Demand();
         Console.WriteLine("Demand succeeded.");
         Console.WriteLine("Adding permission to read environment variable COMPUTERNAME.");
         ps1.AddPermission(
             new EnvironmentPermission(EnvironmentPermissionAccess.Read, "COMPUTERNAME"));
         //<Snippet4>
         // Demand all the permissions in the set.
         Console.WriteLine("Demand all permissions.");
         ps1.Demand();
         //</Snippet4>
         Console.WriteLine("Demand succeeded.");
         //<Snippet5>
         // Display the number of permissions in the set.
         Console.WriteLine("Number of permissions = " + ps1.Count);
         //</Snippet5>
         //<Snippet6>
         // Display the value of the IsSynchronized property.
         Console.WriteLine("IsSynchronized property = " + ps1.IsSynchronized);
         //</Snippet6>
         //<Snippet7>
         // Display the value of the IsReadOnly property.
         Console.WriteLine("IsReadOnly property = " + ps1.IsReadOnly);
         //</Snippet7>
         //<Snippet8>
         // Display the value of the SyncRoot property.
         Console.WriteLine("SyncRoot property = " + ps1.SyncRoot);
         //</Snippet8>
         //<Snippet9>
         // Display the result of a call to the ContainsNonCodeAccessPermissions method.
         // Gets a value indicating whether the PermissionSet contains permissions
         // that are not derived from CodeAccessPermission.
         // Returns true if the PermissionSet contains permissions that are not
         // derived from CodeAccessPermission; otherwise, false.
         Console.WriteLine("ContainsNonCodeAccessPermissions method returned " +
                           ps1.ContainsNonCodeAccessPermissions());
         //</Snippet9>
         //<Snippet10>
         Console.WriteLine("Value of the permission set ToString = \n" + ps1.ToString());
         //</Snippet10>
         PermissionSet ps2 = new PermissionSet(PermissionState.None);
         //<Snippet11>
         // Create a second permission set and compare it to the first permission set.
         ps2.AddPermission(
             new EnvironmentPermission(EnvironmentPermissionAccess.Read, "USERNAME"));
         ps2.AddPermission(
             new EnvironmentPermission(EnvironmentPermissionAccess.Write, "COMPUTERNAME"));
         IEnumerator list = ps1.GetEnumerator();
         Console.WriteLine("Permissions in first permission set:");
         while (list.MoveNext())
         {
             Console.WriteLine(list.Current.ToString());
         }
         Console.WriteLine("Second permission IsSubsetOf first permission = " + ps2.IsSubsetOf(ps1));
         //</Snippet11>
         //<Snippet12>
         // Display the intersection of two permission sets.
         PermissionSet ps3 = ps2.Intersect(ps1);
         Console.WriteLine("The intersection of the first permission set and "
                           + "the second permission set = " + ps3.ToString());
         //</Snippet12>
         // Create a new permission set.
         PermissionSet ps4 = new PermissionSet(PermissionState.None);
         ps4.AddPermission(
             new FileIOPermission(FileIOPermissionAccess.Read,
                                  "C:\\Temp\\Testfile.txt"));
         ps4.AddPermission(
             new FileIOPermission(FileIOPermissionAccess.Read |
                                  FileIOPermissionAccess.Write | FileIOPermissionAccess.Append,
                                  "C:\\Temp\\Testfile.txt"));
         //<Snippet13>
         // Display the union of two permission sets.
         PermissionSet ps5 = ps3.Union(ps4);
         Console.WriteLine("The union of permission set 3 and permission set 4 = "
                           + ps5.ToString());
         //</Snippet13>
         //<Snippet15>
         // Remove FileIOPermission from the permission set.
         ps5.RemovePermission(typeof(FileIOPermission));
         Console.WriteLine("The last permission set after removing FileIOPermission = "
                           + ps5.ToString());
         //</Snippet15>
         //<Snippet16>
         // Change the permission set using SetPermission.
         ps5.SetPermission(new EnvironmentPermission(EnvironmentPermissionAccess.AllAccess, "USERNAME"));
         Console.WriteLine("Permission set after SetPermission = " + ps5.ToString());
         //</Snippet16>
         //<Snippet17>
         // Display result of ToXml and FromXml operations.
         PermissionSet ps6 = new PermissionSet(PermissionState.None);
         ps6.FromXml(ps5.ToXml());
         Console.WriteLine("Result of ToFromXml = " + ps6.ToString() + "\n");
         //</Snippet17>
         //<Snippet18>
         // Display results of PermissionSet.GetEnumerator.
         IEnumerator psEnumerator = ps1.GetEnumerator();
         while (psEnumerator.MoveNext())
         {
             Console.WriteLine(psEnumerator.Current);
         }
         //</Snippet18>
         //<Snippet19>
         // Check for an unrestricted permission set.
         PermissionSet ps7 = new PermissionSet(PermissionState.Unrestricted);
         Console.WriteLine("Permission set is unrestricted = " + ps7.IsUnrestricted());
         //</Snippet19>
         //<Snippet20>
         // Create and display a copy of a permission set.
         ps7 = ps5.Copy();
         Console.WriteLine("Result of copy = " + ps7.ToString());
         //</Snippet20>
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message.ToString());
     }
 }