.NET Framework 클래스 라이브러리
PolicyLevel 클래스

업데이트: 2007년 11월

공용 언어 런타임의 보안 정책 수준을 나타냅니다. 이 클래스는 상속될 수 없습니다.

네임스페이스:  System.Security.Policy
어셈블리:  mscorlib(mscorlib.dll)

구문

Visual Basic(선언)
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public NotInheritable Class PolicyLevel
Visual Basic (사용법)
Dim instance As PolicyLevel
C#
[SerializableAttribute]
[ComVisibleAttribute(true)]
public sealed class PolicyLevel
Visual C++
[SerializableAttribute]
[ComVisibleAttribute(true)]
public ref class PolicyLevel sealed
J#
/** @attribute SerializableAttribute */ 
/** @attribute ComVisibleAttribute(true) */
public final class PolicyLevel
JScript
public final class PolicyLevel
설명

최상위 수준의 보안 정책은 엔터프라이즈 수준입니다. 하위 수준에 정책 제한 사항을 세부적으로 지정할 수 있지만 상위 수준에서 허용하는 것 이상의 사용 권한을 부여하지는 못합니다. 다음은 구현되는 정책 수준입니다.

1. 엔터프라이즈: 엔터프라이즈 내에 있는 모든 관리 코드에 대한 보안 정책입니다.

2. 컴퓨터: 컴퓨터에서 실행되는 모든 관리 코드에 대한 보안 정책입니다.

3. 사용자: 사용자가 실행하는 모든 관리 코드에 대한 보안 정책입니다.

4. 응용 프로그램 도메인: 응용 프로그램에 있는 모든 관리 코드에 대한 보안 정책입니다.

정책 수준은 단일 루트 트리로 조직된 코드 그룹 집합으로 구성됩니다. 자세한 내용은 CodeGroup을 참조하십시오. 코드 그룹 집합은 코드 그룹에 속한 코드에 부여될 권한을 지정하는 코드 그룹과 완전히 신뢰할 수 있는 어셈블리의 목록에서 참조하는 명명된 권한 집합입니다.

SecurityManager..::.PolicyHierarchy를 사용하여 정책 수준을 열거합니다.

예제

다음 예제에서는 PolicyLevel 클래스의 멤버를 사용하는 방법을 보여 줍니다.

Visual Basic
' 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.
Imports System
Imports System.Collections
Imports System.Security
Imports System.Security.Policy
Imports System.Security.Permissions
Imports System.Reflection
Imports System.Globalization
Imports Microsoft.VisualBasic

'using CRCLib;

<Assembly: AssemblyKeyFile("snKey.snk")> 


Class PolicyLevelSample


    Shared Sub Main()
        Console.WriteLine("*************************************************************************************")
        Console.WriteLine("Create an AppDomain policy level.")
        Console.WriteLine("Use the AppDomain to demonstrate PolicyLevel methods and properties.")
        Console.WriteLine("*************************************************************************************")
        CreateAPolicyLevel()
        Dim intranetZoneEvidence As New Evidence(New Object() {New Zone(SecurityZone.Intranet)}, Nothing)
        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.")
        Dim consoleInput As String = Console.ReadLine()
    End Sub 'Main


    Public Shared Sub CreateAPolicyLevel()
        Try
            ' Create an AppDomain policy level.
            Dim pLevel As PolicyLevel = PolicyLevel.CreateAppDomainLevel()
            ' The root code group of the policy level combines all
            ' permissions of its children.
            Dim rootCodeGroup As UnionCodeGroup
            Dim ps As 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.
            Dim myCodeGroup As New UnionCodeGroup(New StrongNameMembershipCondition(New StrongNamePublicKeyBlob(GetKey()), Nothing, Nothing), New PolicyStatement(New PermissionSet(PermissionState.Unrestricted), PolicyStatementAttribute.Nothing))
            myCodeGroup.Name = "My CodeGroup"

            ' Alternative way to grant full trust to an assembly.
            Dim myMemCondition As New StrongNameMembershipCondition(New StrongNamePublicKeyBlob(GetKey()), Nothing, Nothing)
            pLevel.AddFullTrustAssembly(myMemCondition)
            pLevel.RemoveFullTrustAssembly(myMemCondition)
            ' List StrongNameMembershipConditions for FullTrust assemblies.
            Console.WriteLine("StrongNameMembershipConditions for FullTrust assemblies:")
            Dim strongNameMembership As IList = pLevel.FullTrustAssemblies
            Dim list As IEnumerator = strongNameMembership.GetEnumerator()
            While list.MoveNext()
                Console.WriteLine((ControlChars.Tab + CType(list.Current, StrongNameMembershipCondition).Name))
            End While
            ' 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:")
            Dim codeGroups As IList = pLevel.RootCodeGroup.Children
            Dim codeGroup As IEnumerator = codeGroups.GetEnumerator()
            While codeGroup.MoveNext()
                Console.WriteLine((ControlChars.Tab + CType(codeGroup.Current, CodeGroup).Name))
            End While
            Console.WriteLine("Demonstrate adding and removing named permission sets.")
            Console.WriteLine("Original named permission sets:")
            ListPermissionSets(pLevel)
            Dim myInternet As NamedPermissionSet = pLevel.GetNamedPermissionSet("Internet")
            myInternet.Name = "MyInternet"
            pLevel.AddNamedPermissionSet(myInternet)
            Console.WriteLine(ControlChars.Lf + "New named permission sets:")
            ListPermissionSets(pLevel)
            myInternet.RemovePermission(GetType(System.Security.Permissions.FileDialogPermission))
            pLevel.ChangeNamedPermissionSet("MyInternet", myInternet)
            pLevel.RemoveNamedPermissionSet("MyInternet")
            Console.WriteLine(ControlChars.Lf + "Current permission sets:")
            ListPermissionSets(pLevel)
            pLevel.AddNamedPermissionSet(myInternet)
            Console.WriteLine(ControlChars.Lf + "Updated named permission sets:")
            ListPermissionSets(pLevel)
            pLevel.Reset()
            Console.WriteLine(ControlChars.Lf + "Reset named permission sets:")
            ListPermissionSets(pLevel)
            Console.WriteLine(ControlChars.Lf + "Type 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)
            Dim pLevelCopy As PolicyLevel = PolicyLevel.CreateAppDomainLevel()
            ' Create a copy of the PolicyLevel using ToXml/FromXml.
            pLevelCopy.FromXml(pLevel.ToXml())

            If ComparePolicyLevels(pLevel, pLevelCopy) Then
                Console.WriteLine("The ToXml/FromXml roundtrip was successful.")
            Else
                Console.WriteLine("ToXml/FromXml roundtrip failed.")
            End If
            Console.WriteLine("Show the result of resolving policy for evidence unique to the AppDomain policy level.")
            Dim myEvidence As New Evidence(New Object() {myCodeGroup}, Nothing)
            CheckEvidence(pLevel, myEvidence)
            Return
        Catch e As Exception
            Console.WriteLine(e.Message)
            Return
        End Try
    End Sub 'CreateAPolicyLevel

    ' Compare two PolicyLevels using ToXml and FromXml.
    Private Shared Function ComparePolicyLevels(ByVal pLevel1 As PolicyLevel, ByVal pLevel2 As PolicyLevel) As Boolean
        Dim retVal As Boolean = False
        Dim firstCopy As PolicyLevel = PolicyLevel.CreateAppDomainLevel()
        Dim secondCopy As PolicyLevel = 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 Then
            retVal = True
        End If
        Return retVal
    End Function 'ComparePolicyLevels


    ' Demonstrate the use of ResolvePolicy for the supplied evidence and a specified policy level.
    Private Overloads Shared Sub CheckEvidence(ByVal pLevel As PolicyLevel, ByVal evidence As Evidence)
        ' Display the code groups to which the evidence belongs.
        Console.WriteLine(ControlChars.Tab + "ResolvePolicy for the given evidence: ")
        Dim codeGroup As IEnumerator = evidence.GetEnumerator()
        While codeGroup.MoveNext()
            Console.WriteLine((ControlChars.Tab + ControlChars.Tab + CType(codeGroup.Current, CodeGroup).Name))
        End While
        Console.WriteLine("The current evidence belongs to the following root CodeGroup:")
        ' pLevel is the current PolicyLevel, evidence is the Evidence to be resolved.
        Dim cg1 As CodeGroup = pLevel.ResolveMatchingCodeGroups(evidence)
        Console.WriteLine((pLevel.Label + " Level"))
        Console.WriteLine((ControlChars.Tab + "Root 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(ControlChars.Lf + "Current permissions granted:")
        Dim pState As PolicyStatement = pLevel.Resolve(evidence)
        Console.WriteLine(pState.ToXml().ToString())

        Return
    End Sub 'CheckEvidence

    Private Shared Sub ListPermissionSets(ByVal pLevel As PolicyLevel)
        Dim namedPermissions As IList = pLevel.NamedPermissionSets
        Dim namedPermission As IEnumerator = namedPermissions.GetEnumerator()
        While namedPermission.MoveNext()
            Console.WriteLine((ControlChars.Tab + CType(namedPermission.Current, NamedPermissionSet).Name))
        End While
    End Sub 'ListPermissionSets

    Private Shared Function GetKey() As Byte()
        Return [Assembly].GetCallingAssembly().GetName().GetPublicKey()
    End Function 'GetKey

    ' Demonstrate the use of ResolvePolicy for passed in evidence.
    Private Overloads Shared Sub CheckEvidence(ByVal evidence As Evidence)
        ' Display the code groups to which the evidence belongs.
        Console.WriteLine("ResolvePolicy for the given evidence.")
        Console.WriteLine(ControlChars.Tab + "Current evidence belongs to the following code groups:")
        Dim policyEnumerator As IEnumerator = SecurityManager.PolicyHierarchy()
        ' Resolve the evidence at all the policy levels.
        While policyEnumerator.MoveNext()
            Dim currentLevel As PolicyLevel = CType(policyEnumerator.Current, PolicyLevel)
            Dim cg1 As CodeGroup = currentLevel.ResolveMatchingCodeGroups(evidence)
            Console.WriteLine((ControlChars.Lf + ControlChars.Tab + currentLevel.Label + " Level"))
            Console.WriteLine((ControlChars.Tab + ControlChars.Tab + "CodeGroup = " + cg1.Name))
            Dim cgE1 As IEnumerator = cg1.Children.GetEnumerator()
            While cgE1.MoveNext()
                Console.WriteLine((ControlChars.Tab + ControlChars.Tab + ControlChars.Tab + "Group = " + CType(cgE1.Current, CodeGroup).Name))
            End While
            Console.WriteLine((ControlChars.Tab + "StoreLocation = " + currentLevel.StoreLocation))
        End While

        Return
    End Sub 'CheckEvidence

    Private Shared Sub ListMachinePermissionSets()
        Console.WriteLine(ControlChars.Lf + "Permission sets in Machine policy level:")
        Dim policyEnumerator As IEnumerator = SecurityManager.PolicyHierarchy()
        While policyEnumerator.MoveNext()

            Dim currentLevel As PolicyLevel = CType(policyEnumerator.Current, PolicyLevel)
            If currentLevel.Label = "Machine" Then

                Dim namedPermissions As IList = currentLevel.NamedPermissionSets
                Dim namedPermission As IEnumerator = namedPermissions.GetEnumerator()
                While namedPermission.MoveNext()
                    Console.WriteLine((ControlChars.Tab + CType(namedPermission.Current, NamedPermissionSet).Name))
                End While
            End If
        End While
    End Sub 'ListMachinePermissionSets
End Class 'PolicyLevelSample 
C#
// 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);
                }

            }
        }

    }
    
}
Visual C++
// 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 namespace System;
using namespace System::Collections;
using namespace System::Security;
using namespace System::Security::Policy;
using namespace System::Security::Permissions;
using namespace System::Reflection;
using namespace System::Globalization;

//using CRCLib;

[assembly:AssemblyKeyFile("snKey.snk")];
array<Byte>^ GetKey();
void ListPermissionSets( PolicyLevel^ pLevel );
bool ComparePolicyLevels( PolicyLevel^ pLevel1, PolicyLevel^ pLevel2 );
void CreateAPolicyLevel();
void CheckEvidence( PolicyLevel^ pLevel, Evidence^ evidence );
void CheckEvidence( Evidence^ evidence );
void ListMachinePermissionSets();

int main()
{
   Console::WriteLine( "*************************************************************************************" );
   Console::WriteLine( "Create an AppDomain policy level." );
   Console::WriteLine( "Use the AppDomain to demonstrate PolicyLevel methods and properties." );
   Console::WriteLine( "*************************************************************************************" );
   CreateAPolicyLevel();
   array<Object^>^temp0 = {gcnew Zone( SecurityZone::Intranet )};
   Evidence^ intranetZoneEvidence = gcnew Evidence( temp0,nullptr );
   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." );
   Console::ReadLine();
}

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 = gcnew PermissionSet( PermissionState::None );
      ps->AddPermission( gcnew SecurityPermission( SecurityPermissionFlag::Execution ) );
      rootCodeGroup = gcnew UnionCodeGroup( gcnew AllMembershipCondition,gcnew PolicyStatement( ps,PolicyStatementAttribute::Nothing ) );

      // This code group grants FullTrust to assemblies with the strong
      // name key from this assembly.
      UnionCodeGroup^ myCodeGroup = gcnew UnionCodeGroup( gcnew StrongNameMembershipCondition( gcnew StrongNamePublicKeyBlob( GetKey() ),nullptr,nullptr ),gcnew PolicyStatement( gcnew PermissionSet( PermissionState::Unrestricted ),PolicyStatementAttribute::Nothing ) );
      myCodeGroup->Name = "My CodeGroup";

      // Alternative way to grant full trust to an assembly.
      StrongNameMembershipCondition^ myMemCondition = gcnew StrongNameMembershipCondition( gcnew StrongNamePublicKeyBlob( GetKey() ),nullptr,nullptr );
      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{0}", (dynamic_cast<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{0}", (dynamic_cast<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( System::Security::Permissions::FileDialogPermission::typeid );

      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 = {0}", pLevel->Type );

      Console::WriteLine( "The result of GetHashCode is {0}", 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 = {0}", 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." );
      array<Object^>^temp1 = {myCodeGroup};
      Evidence^ myEvidence = gcnew Evidence( temp1,nullptr );
      CheckEvidence( pLevel, myEvidence );
      return;
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( e->Message );
      return;
   }
}


// Compare two PolicyLevels using ToXml and FromXml.
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.
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{0}", (dynamic_cast<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( "{0} Level", pLevel->Label );
   Console::WriteLine( "\tRoot CodeGroup = {0}", 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() );
   return;
}

void ListPermissionSets( PolicyLevel^ pLevel )
{
   IList^ namedPermissions = pLevel->NamedPermissionSets;
   IEnumerator^ namedPermission = namedPermissions->GetEnumerator();
   while ( namedPermission->MoveNext() )
   {
      Console::WriteLine( "\t{0}", (dynamic_cast<NamedPermissionSet^>(namedPermission->Current))->Name );
   }
}

array<Byte>^ GetKey()
{
   return Assembly::GetCallingAssembly()->GetName()->GetPublicKey();
}

// Demonstrate the use of ResolvePolicy for passed in evidence.
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 = dynamic_cast<PolicyLevel^>(policyEnumerator->Current);
      CodeGroup^ cg1 = currentLevel->ResolveMatchingCodeGroups( evidence );
      Console::WriteLine( "\n\t{0} Level", currentLevel->Label );
      Console::WriteLine( "\t\tCodeGroup = {0}", cg1->Name );
      IEnumerator^ cgE1 = cg1->Children->GetEnumerator();
      while ( cgE1->MoveNext() )
      {
         Console::WriteLine( "\t\t\tGroup = {0}", (dynamic_cast<CodeGroup^>(cgE1->Current))->Name );
      }

      Console::WriteLine( "\tStoreLocation = {0}", currentLevel->StoreLocation );
   }

   return;
}

void ListMachinePermissionSets()
{
   Console::WriteLine( "\nPermission sets in Machine policy level:" );
   IEnumerator^ policyEnumerator = SecurityManager::PolicyHierarchy();
   while ( policyEnumerator->MoveNext() )
   {
      PolicyLevel^ currentLevel = dynamic_cast<PolicyLevel^>(policyEnumerator->Current);
      if ( currentLevel->Label->Equals( "Machine" ) )
      {
         IList^ namedPermissions = currentLevel->NamedPermissionSets;
         IEnumerator^ namedPermission = namedPermissions->GetEnumerator();
         while ( namedPermission->MoveNext() )
         {
            Console::WriteLine( "\t{0}", (dynamic_cast<NamedPermissionSet^>(namedPermission->Current))->Name );
         }
      }
   }
}
J#
// 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
스레드로부터의 안전성

이 형식의 모든 공용 static(Visual Basic의 경우 Shared) 멤버는 스레드로부터 안전합니다. 인터페이스 멤버는 스레드로부터 안전하지 않습니다.
플랫폼

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

.NET Framework 및 .NET Compact Framework에서 모든 플랫폼의 전체 버전을 지원하지는 않습니다. 지원되는 버전의 목록을 보려면 .NET Framework 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

3.5, 3.0, 2.0, 1.1, 1.0에서 지원
참고 항목

참조

태그 :


Page view tracker