Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.
1 out of 5 rated this helpful - Rate this topic

PolicyLevel Class

Represents the security policy levels for the common language runtime. This class cannot be inherited.

Namespace: System.Security.Policy
Assembly: mscorlib (in mscorlib.dll)

[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public sealed class PolicyLevel
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
public final class PolicyLevel
SerializableAttribute 
ComVisibleAttribute(true) 
public final class PolicyLevel

The highest level of security policy is enterprise-wide. Successive lower levels of hierarchy represent further policy restrictions, but can never grant more permissions than allowed by higher levels. The following policy levels are implemented:

1. Enterprise: security policy for all managed code in an enterprise.

2. Machine: security policy for all managed code run on the computer.

3. User: security policy for all managed code run by the user.

4. Application domain: security policy for all managed code in an application.

A policy level consists of a set of code groups organized into a single rooted tree (see CodeGroup), a set of named permission sets that are referenced by the code groups to specify permissions to be granted to code belonging to the code group, and a list of fully-trusted assemblies.

Use SecurityManager.PolicyHierarchy to enumerate the policy levels.

The following example shows the use of members of the PolicyLevel class.

// This sample demonstrates how to set code access permissions programmatically.  It creates a
// new parent and child code group pair, and allows the user to optionally delete the child group 
// and/or the parent code group.  It also shows the result of a ResolvePolicy call, and displays 
// the permissions for the three security levels; Enterprise, Machine, and User.
using System;
using System.Collections;
using System.Security;
using System.Security.Policy;
using System.Security.Permissions;
using System.Reflection;
using System.Globalization;
//using CRCLib;

[assembly: AssemblyKeyFile("snKey.snk")]
class PolicyLevelSample
{
	
    static void Main()
    {
        Console.WriteLine("*************************************************************************************");
        Console.WriteLine("Create an AppDomain policy level.");
        Console.WriteLine("Use the AppDomain to demonstrate PolicyLevel methods and properties.");
        Console.WriteLine("*************************************************************************************");
        CreateAPolicyLevel();
        Evidence intranetZoneEvidence = new Evidence(new object[] { new Zone(SecurityZone.Intranet) }, null);
        Console.WriteLine("*************************************************************************************");
        Console.WriteLine("Show the result of ResolvePolicy on this computer for LocalIntranet zone evidence.");
        Console.WriteLine("*************************************************************************************");
        CheckEvidence(intranetZoneEvidence);
        Console.WriteLine("*************************************************************************************");
        Console.WriteLine("Enumerate the permission sets for Machine policy level.");
        Console.WriteLine("*************************************************************************************");
        ListMachinePermissionSets();
        Console.Out.WriteLine("Press the Enter key to exit.");
        string consoleInput = Console.ReadLine();

    }
		
    public static void CreateAPolicyLevel()
    {
        try
        {
            // Create an AppDomain policy level.
            PolicyLevel pLevel = PolicyLevel.CreateAppDomainLevel();
            // The root code group of the policy level combines all
            // permissions of its children.
            UnionCodeGroup rootCodeGroup;
            PermissionSet ps = new PermissionSet(PermissionState.None);
            ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

            rootCodeGroup = new UnionCodeGroup(
                new AllMembershipCondition(),
                new PolicyStatement(ps, PolicyStatementAttribute.Nothing));
			
            // This code group grants FullTrust to assemblies with the strong
            // name key from this assembly.
            UnionCodeGroup myCodeGroup = new UnionCodeGroup(
                new StrongNameMembershipCondition(
                new StrongNamePublicKeyBlob(GetKey()),
                null,
                null),
                new PolicyStatement(new PermissionSet(PermissionState.Unrestricted),
                PolicyStatementAttribute.Nothing)
                );
            myCodeGroup.Name = "My CodeGroup";

            // Alternative way to grant full trust to an assembly.
            StrongNameMembershipCondition myMemCondition = new StrongNameMembershipCondition(
                new StrongNamePublicKeyBlob(GetKey()), null, null);
            pLevel.AddFullTrustAssembly(myMemCondition);
            pLevel.RemoveFullTrustAssembly(myMemCondition);
            // List StrongNameMembershipConditions for FullTrust assemblies.
            Console.WriteLine("StrongNameMembershipConditions for FullTrust assemblies:");
            IList strongNameMembership = pLevel.FullTrustAssemblies;
            IEnumerator list = strongNameMembership.GetEnumerator();
            while (list.MoveNext())
            {
                Console.WriteLine("\t" + ((StrongNameMembershipCondition)list.Current).Name);
            }
			
            // Add the code groups to the policy level.
            rootCodeGroup.AddChild(myCodeGroup);
            pLevel.RootCodeGroup = rootCodeGroup;
            Console.WriteLine("Permissions granted to all code running in this AppDomain level: ");
            Console.WriteLine(rootCodeGroup.ToXml());
            Console.WriteLine("Child code groups in RootCodeGroup:");
            IList codeGroups = pLevel.RootCodeGroup.Children;
            IEnumerator codeGroup = codeGroups.GetEnumerator();
            while (codeGroup.MoveNext())
            {
                Console.WriteLine("\t" + ((CodeGroup)codeGroup.Current).Name);
            }
            Console.WriteLine("Demonstrate adding and removing named permission sets.");
            Console.WriteLine("Original named permission sets:");
            ListPermissionSets(pLevel);
            NamedPermissionSet myInternet = pLevel.GetNamedPermissionSet("Internet");
            myInternet.Name = "MyInternet";
            pLevel.AddNamedPermissionSet(myInternet);
            Console.WriteLine("\nNew named permission sets:");
            ListPermissionSets(pLevel);
            myInternet.RemovePermission(typeof(System.Security.Permissions.FileDialogPermission));
            pLevel.ChangeNamedPermissionSet("MyInternet",myInternet);
            pLevel.RemoveNamedPermissionSet("MyInternet");
            Console.WriteLine("\nCurrent permission sets:");
            ListPermissionSets(pLevel);
            pLevel.AddNamedPermissionSet(myInternet);
            Console.WriteLine("\nUpdated named permission sets:");
            ListPermissionSets(pLevel);
            pLevel.Reset();
            Console.WriteLine("\nReset named permission sets:");
            ListPermissionSets(pLevel);
            Console.WriteLine("\nType property = " + pLevel.Type.ToString());
            Console.WriteLine("The result of GetHashCode is " + pLevel.GetHashCode().ToString());
            Console.WriteLine("StoreLocation property for the AppDomain level is empty, since AppDomain policy " + 
                "cannot be saved to a file.");
            Console.WriteLine("StoreLocation property = " + pLevel.StoreLocation);
            PolicyLevel pLevelCopy = PolicyLevel.CreateAppDomainLevel();
            // Create a copy of the PolicyLevel using ToXml/FromXml.
            pLevelCopy.FromXml(pLevel.ToXml());

            if (ComparePolicyLevels(pLevel, pLevelCopy))
            {
                Console.WriteLine("The ToXml/FromXml roundtrip was successful.");
            }
            else
            {
                Console.WriteLine("ToXml/FromXml roundtrip failed.");
            }
            Console.WriteLine("Show the result of resolving policy for evidence unique to the AppDomain policy level.");
            Evidence myEvidence = new Evidence(new object[] { myCodeGroup }, null);
            CheckEvidence(pLevel,myEvidence);
            return;
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return;
        }
    }
    // Compare two PolicyLevels using ToXml and FromXml.
    private static bool ComparePolicyLevels(PolicyLevel pLevel1, PolicyLevel pLevel2)
    {
        bool retVal = false;
        PolicyLevel firstCopy = PolicyLevel.CreateAppDomainLevel();
        PolicyLevel secondCopy = PolicyLevel.CreateAppDomainLevel();
        // Create copies of the two PolicyLevels passed in.
        // Convert the two PolicyLevels to their canonical form using ToXml and FromXml.
        firstCopy.FromXml(pLevel1.ToXml());
        secondCopy.FromXml(pLevel2.ToXml());
        if(firstCopy.ToXml().ToString().CompareTo(secondCopy.ToXml().ToString())== 0)
            retVal = true;
        return retVal;
    }
	
    // Demonstrate the use of ResolvePolicy for the supplied evidence and a specified policy level.
    private static void CheckEvidence(PolicyLevel pLevel, Evidence evidence)
    {
        // Display the code groups to which the evidence belongs.
        Console.WriteLine("\tResolvePolicy for the given evidence: ");
        IEnumerator codeGroup = evidence.GetEnumerator();
        while (codeGroup.MoveNext())
        {
            Console.WriteLine("\t\t" + ((CodeGroup)codeGroup.Current).Name);
        }
        Console.WriteLine("The current evidence belongs to the following root CodeGroup:");
        // pLevel is the current PolicyLevel, evidence is the Evidence to be resolved.
        CodeGroup cg1 = pLevel.ResolveMatchingCodeGroups(evidence);
        Console.WriteLine(pLevel.Label + " Level");
        Console.WriteLine("\tRoot CodeGroup = " + cg1.Name);

        // Show how Resolve is used to determine the set of permissions that 
        // the security system grants to code, based on the evidence.

        // Show the granted permissions. 
        Console.WriteLine("\nCurrent permissions granted:");
        PolicyStatement pState = pLevel.Resolve(evidence);
        Console.WriteLine(pState.ToXml().ToString());

        return;
    }

    private static void ListPermissionSets(PolicyLevel pLevel)
    {
        IList namedPermissions = pLevel.NamedPermissionSets;
        IEnumerator namedPermission = namedPermissions.GetEnumerator();
        while (namedPermission.MoveNext())
        {
            Console.WriteLine("\t" + ((NamedPermissionSet)namedPermission.Current).Name);
        }
    }

    private static byte[] GetKey()
    {
        return Assembly.GetCallingAssembly().GetName().GetPublicKey();
    }
    // Demonstrate the use of ResolvePolicy for passed in evidence.
    private static void CheckEvidence(Evidence evidence)
    {
        // Display the code groups to which the evidence belongs.
        Console.WriteLine("ResolvePolicy for the given evidence.");
        Console.WriteLine("\tCurrent evidence belongs to the following code groups:");
        IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy();
        // Resolve the evidence at all the policy levels.
        while (policyEnumerator.MoveNext())
        {

            PolicyLevel currentLevel = (PolicyLevel)policyEnumerator.Current;	
            CodeGroup cg1 = currentLevel.ResolveMatchingCodeGroups(evidence);
            Console.WriteLine("\n\t" + currentLevel.Label + " Level");
            Console.WriteLine("\t\tCodeGroup = " + cg1.Name);
            IEnumerator cgE1 = cg1.Children.GetEnumerator();
            while (cgE1.MoveNext())
            {
                Console.WriteLine("\t\t\tGroup = " + ((CodeGroup)cgE1.Current).Name);
            }
            Console.WriteLine("\tStoreLocation = " + currentLevel.StoreLocation);

        }

        return;
    }

    private static void ListMachinePermissionSets()
    {
        Console.WriteLine("\nPermission sets in Machine policy level:");
        IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy();
        while (policyEnumerator.MoveNext())
        {

            PolicyLevel currentLevel = (PolicyLevel)policyEnumerator.Current;	
            if (currentLevel.Label == "Machine")
            {
			
                IList namedPermissions = currentLevel.NamedPermissionSets;
                IEnumerator namedPermission = namedPermissions.GetEnumerator();
                while (namedPermission.MoveNext())
                {
                    Console.WriteLine("\t" + ((NamedPermissionSet)namedPermission.Current).Name);
                }

            }
        }

    }
	
}


// This sample demonstrates how to set code access permissions
// programmatically. It creates a new parent and child code group pair, 
// and allows the user to optionally delete the child group and/or the 
// parent code group.  It also shows the result of a ResolvePolicy call, 
// and displays the permissions for the three security levels; Enterprise, 
// Machine,and User.

import System.*;
import System.Collections.*;
import System.Security.*;
import System.Security.Policy.*;
import System.Security.Permissions.*;
import System.Reflection.*;
import System.Globalization.*;
import System.Security.SecurityManager;

/** @assembly AssemblyKeyFile("snKey.snk")
 */

class PolicyLevelSample
{
    public static void main(String[] args)
    {
        Console.WriteLine("*************************************************"
            + "************************************");
        Console.WriteLine("Create an AppDomain policy level.");
        Console.WriteLine("Use the AppDomain to demonstrate PolicyLevel "
            + "methods and properties.");
        Console.WriteLine("*************************************************"
            + "************************************");
        CreateAPolicyLevel();
        Evidence intranetZoneEvidence = new Evidence(new System.Object[] { 
                new Zone(SecurityZone.Intranet) }, null);
        Console.WriteLine("*************************************************"
            + "************************************");
        Console.WriteLine("Show the result of ResolvePolicy on this computer "
            + "for LocalIntranet zone evidence.");
        Console.WriteLine("*************************************************"
            + "************************************");
        CheckEvidence(intranetZoneEvidence);
        Console.WriteLine("*************************************************"
            + "************************************");
        Console.WriteLine("Enumerate the permission sets for Machine "
            + "policy level.");
        Console.WriteLine("*************************************************"
            + "************************************");
        ListMachinePermissionSets();
        Console.get_Out().WriteLine("Press the Enter key to exit.");
        String consoleInput = Console.ReadLine();
    } //main

    public static void CreateAPolicyLevel()
    {
        try {
            // Create an AppDomain policy level.
            PolicyLevel pLevel = PolicyLevel.CreateAppDomainLevel();

            // The root code group of the policy level combines all
            // permissions of its children.
            UnionCodeGroup rootCodeGroup;
            PermissionSet ps = new PermissionSet(PermissionState.None);

            ps.AddPermission(new SecurityPermission
                (SecurityPermissionFlag.Execution));
            rootCodeGroup = new UnionCodeGroup(new AllMembershipCondition(),
                new PolicyStatement(ps, PolicyStatementAttribute.Nothing));

            // This code group grants FullTrust to assemblies with the strong
            // name key from this assembly.
            UnionCodeGroup myCodeGroup = new UnionCodeGroup(
                new StrongNameMembershipCondition(
                new StrongNamePublicKeyBlob(GetKey()), null, null),
                new PolicyStatement(new PermissionSet
                (PermissionState.Unrestricted), 
                PolicyStatementAttribute.Nothing));

            myCodeGroup.set_Name("My CodeGroup");

            // Alternative way to grant full trust to an assembly.
            // RemoveFullTrustAssembly
            StrongNameMembershipCondition myMemCondition =
                new StrongNameMembershipCondition(new StrongNamePublicKeyBlob
                (GetKey()), null, null);

            pLevel.AddFullTrustAssembly(myMemCondition);
            pLevel.RemoveFullTrustAssembly(myMemCondition);

            // List StrongNameMembershipConditions for FullTrust assemblies.
            Console.WriteLine("StrongNameMembershipConditions for FullTrust"
                + " assemblies:");

            IList strongNameMembership = pLevel.get_FullTrustAssemblies();
            IEnumerator list = strongNameMembership.GetEnumerator();

            while (list.MoveNext()) {
                Console.WriteLine(("\t" + ((StrongNameMembershipCondition)
                    (list.get_Current())).get_Name()));
            }

            // Add the code groups to the policy level.
            rootCodeGroup.AddChild(myCodeGroup);
            pLevel.set_RootCodeGroup(rootCodeGroup);
            Console.WriteLine("Permissions granted to all code running in "
                + "this AppDomain level: ");
            Console.WriteLine(rootCodeGroup.ToXml());
            Console.WriteLine("Child code groups in RootCodeGroup:");

            IList codeGroups = pLevel.get_RootCodeGroup().get_Children();
            IEnumerator codeGroup = codeGroups.GetEnumerator();

            while (codeGroup.MoveNext()) {
                Console.WriteLine(("\t" + ((CodeGroup)
                    (codeGroup.get_Current())).get_Name()));
            }

            Console.WriteLine("Demonstrate adding and removing named"
                + " permission sets.");
            Console.WriteLine("Original named permission sets:");
            ListPermissionSets(pLevel);
            NamedPermissionSet myInternet =
                pLevel.GetNamedPermissionSet("Internet");

            myInternet.set_Name("MyInternet");

            pLevel.AddNamedPermissionSet(myInternet);

            Console.WriteLine("\nNew named permission sets:");
            ListPermissionSets(pLevel);
            myInternet.RemovePermission(System.Security.Permissions
                .FileDialogPermission.class.ToType());

            pLevel.ChangeNamedPermissionSet("MyInternet", myInternet);

            pLevel.RemoveNamedPermissionSet("MyInternet");

            Console.WriteLine("\nCurrent permission sets:");
            ListPermissionSets(pLevel);
            pLevel.AddNamedPermissionSet(myInternet);
            Console.WriteLine("\nUpdated named permission sets:");
            ListPermissionSets(pLevel);

            pLevel.Reset();

            Console.WriteLine("\nReset named permission sets:");
            ListPermissionSets(pLevel);

            Console.WriteLine(("\nType property = " 
                + pLevel.get_Type().ToString()));

            Console.WriteLine(("The result of GetHashCode is " 
                + String.valueOf(pLevel.GetHashCode())));

            Console.WriteLine(("StoreLocation property for the AppDomain"+
                " level is empty, since AppDomain policy " 
                + "cannot be saved to a file."));
            Console.WriteLine(("StoreLocation property = " 
                + pLevel.get_StoreLocation()));

            PolicyLevel pLevelCopy = PolicyLevel.CreateAppDomainLevel();

            // Create a copy of the PolicyLevel using ToXml/FromXml.
            pLevelCopy.FromXml(pLevel.ToXml());
            if (ComparePolicyLevels(pLevel, pLevelCopy)) {
                Console.WriteLine("The ToXml/FromXml roundtrip "
                    + "was successful.");
            }
            else {
                Console.WriteLine("ToXml/FromXml roundtrip failed.");
            }

            Console.WriteLine("Show the result of resolving policy for"
                + " evidence unique to the AppDomain policy level.");

            Evidence myEvidence = new Evidence(
                new System.Object[] { myCodeGroup }, null);

            CheckEvidence(pLevel, myEvidence);
            return;
        }
        catch (System.Exception e) {
            Console.WriteLine(e.get_Message());
            return;
        }
    } //CreateAPolicyLevel

    // Compare two PolicyLevels using ToXml and FromXml.
    private static boolean ComparePolicyLevels(PolicyLevel pLevel1,
            PolicyLevel pLevel2)
    {
        boolean retVal = false;
        PolicyLevel firstCopy = PolicyLevel.CreateAppDomainLevel();
        PolicyLevel secondCopy = PolicyLevel.CreateAppDomainLevel();

        // Create copies of the two PolicyLevels passed in.
        // Convert the two PolicyLevels to their canonical form using ToXml
        // and FromXml.
        firstCopy.FromXml(pLevel1.ToXml());
        secondCopy.FromXml(pLevel2.ToXml());
        if (firstCopy.ToXml().ToString().CompareTo
                (secondCopy.ToXml().ToString()) == 0) {
            retVal = true;
        }
        return retVal;
    } //ComparePolicyLevels

    // Demonstrate the use of ResolvePolicy for the supplied evidence and 
    //a specified policy level.
    private static void CheckEvidence(PolicyLevel pLevel, Evidence evidence)
    {
        // Display the code groups to which the evidence belongs.
        Console.WriteLine("\tResolvePolicy for the given evidence: ");
        IEnumerator codeGroup = evidence.GetEnumerator();
        while (codeGroup.MoveNext()) {
            Console.WriteLine(("\t\t" + ((CodeGroup)
                (codeGroup.get_Current())).get_Name()));
        }

        Console.WriteLine("The current evidence belongs to the "
            + "following root CodeGroup:");

        // pLevel is the current PolicyLevel, evidence is the Evidence
        // to be resolved.
        CodeGroup cg1 = pLevel.ResolveMatchingCodeGroups(evidence);

        Console.WriteLine((pLevel.get_Label() + " Level"));
        Console.WriteLine(("\tRoot CodeGroup = " + cg1.get_Name()));

        // Show how Resolve is used to determine the set of permissions that 
        // the security system grants to code, based on the evidence.
        // Show the granted permissions. 
        Console.WriteLine("\nCurrent permissions granted:");
        PolicyStatement pState = pLevel.Resolve(evidence);
        Console.WriteLine(pState.ToXml().ToString());
        return;
    } //CheckEvidence

    private static void ListPermissionSets(PolicyLevel pLevel)
    {
        IList namedPermissions = pLevel.get_NamedPermissionSets();
        IEnumerator namedPermission = namedPermissions.GetEnumerator();
        
        while (namedPermission.MoveNext()) {
            Console.WriteLine(("\t" + ((NamedPermissionSet)
                (namedPermission.get_Current())).get_Name()));
        }
    }

    private static ubyte[] GetKey()
    {
        return Assembly.GetCallingAssembly().GetName().GetPublicKey();
    }

    // StoreLocation PolicyLevel.Label
    // Demonstrate the use of ResolvePolicy for passed in evidence.
    private static void CheckEvidence(Evidence evidence)
    {
        // Display the code groups to which the evidence belongs.
        Console.WriteLine("ResolvePolicy for the given evidence.");
        Console.WriteLine("\tCurrent evidence belongs to the "
            + "following code groups:");

        IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy();
        // Resolve the evidence at all the policy levels.
        while (policyEnumerator.MoveNext()) {
            PolicyLevel currentLevel = ((PolicyLevel)
                (policyEnumerator.get_Current()));
            CodeGroup cg1 = currentLevel.ResolveMatchingCodeGroups(evidence);

            Console.WriteLine(("\n\t" + currentLevel.get_Label() + " Level"));
            Console.WriteLine(("\t\tCodeGroup = " + cg1.get_Name()));
            IEnumerator cgE1 = cg1.get_Children().GetEnumerator();
            while (cgE1.MoveNext()) {
                Console.WriteLine(("\t\t\tGroup = " + ((CodeGroup)
                    (cgE1.get_Current())).get_Name()));
            }
            Console.WriteLine(("\tStoreLocation = " 
                + currentLevel.get_StoreLocation()));
        }
        return;
    } //CheckEvidence

    private static void ListMachinePermissionSets()
    {
        Console.WriteLine("\nPermission sets in Machine policy level:");
        IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy();
        while (policyEnumerator.MoveNext()) {
            PolicyLevel currentLevel = ((PolicyLevel)
                (policyEnumerator.get_Current()));
            if (currentLevel.get_Label().equalsIgnoreCase("Machine")) {
                IList namedPermissions = 
                    currentLevel.get_NamedPermissionSets();
                IEnumerator namedPermission = 
                    namedPermissions.GetEnumerator();

                while (namedPermission.MoveNext()) {
                    Console.WriteLine(("\t" + ((NamedPermissionSet)
                        (namedPermission.get_Current())).get_Name()));
                }
            }
        }
    } //ListMachinePermissionSets
} //PolicyLevelSample

System.Object
  System.Security.Policy.PolicyLevel
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

Show:
© 2014 Microsoft. All rights reserved.