SecurityManager クラス
アセンブリ: mscorlib (mscorlib.dll 内)



SecurityManager を使用する例を次に示します。
' 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 Class SecurityManagerSample Shared Sub Main() ' Gets a value indicating whether code must have execution rights in order to execute. If Not SecurityManager.CheckExecutionRights Then Console.WriteLine("Execution rights are not required to run the assemblies.") End If ' Gets a value indicating whether code access security is enabled. If Not SecurityManager.SecurityEnabled Then Console.WriteLine("Security is not enabled.") End If ' Determines whether the right to control policy has been granted to the caller. If SecurityManager.IsGranted(New SecurityPermission(SecurityPermissionFlag.ControlPolicy)) Then ' Define custom named permission sets for Company and Department. ' These will be used for the new code groups. CreateCompanyPermission() CreateDepartmentPermission() ' Create a parent and child code group at the Machine policy level using the ' permission sets we created. CreateCodeGroups() ' Demonstrate the result of a call to ResolvePolicy(). ' This is not required for the main thrust of this sample, custom named permissions ' and code groups, but allows demonstration of the ResolvePolicy method. Console.WriteLine("Current Security Policy:") Console.WriteLine("------------------------") DisplaySecurityPolicy() Console.WriteLine("Resolve Policy demonstration.") ' Get the evidence for the Local Intranet zone. Dim intranetZoneEvidence As New Evidence(New Object() {New Zone(SecurityZone.Intranet)}, Nothing) Console.WriteLine("Show the result of ResolvePolicy for LocalIntranet zone evidence.") CheckEvidence(intranetZoneEvidence) ' Optionally remove the policy elements that were created. Console.WriteLine("Would you like to remove the Department code group?") Console.WriteLine("Please type 'yes' to delete the Department group, else press the Enter key.") Dim answer As String = Console.ReadLine() If answer = "yes" Then DeleteCustomChildCodeGroup("MyDepartment") SecurityManager.SavePolicy() End If Console.WriteLine("Would you like to remove all new code groups and permission sets?") Console.WriteLine("Please type yes to delete all new groups, else press the Enter key.") answer = Console.ReadLine() If answer = "yes" Then DeleteCustomCodeGroups() DeleteCustomPermissions() SecurityManager.SavePolicy() End If Else Console.Out.WriteLine("ControlPolicy permission is denied.") End If Return End Sub 'Main Private Shared Sub DisplaySecurityPolicy() Dim policyEnumerator As IEnumerator = SecurityManager.PolicyHierarchy() While policyEnumerator.MoveNext() Dim currentLevel As PolicyLevel = CType(policyEnumerator.Current, PolicyLevel) ' Display the policy at the current level. Console.WriteLine("Policy Level {0}:", currentLevel.Label) ' To display the policy detail, uncomment the following line: 'Console.WriteLine(currentLevel.ToXml().ToString()); 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 While End Sub 'DisplaySecurityPolicy Private Shared Sub DeleteCustomCodeGroups() ' Delete the custom code groups that were created. Dim policyEnumerator As IEnumerator = SecurityManager.PolicyHierarchy() While policyEnumerator.MoveNext() Dim machineLevel As PolicyLevel = CType(policyEnumerator.Current, PolicyLevel) Dim childCodeGroups As IList = machineLevel.RootCodeGroup.Children Dim childGroups As IEnumerator = childCodeGroups.GetEnumerator() While childGroups.MoveNext() Dim thisCodeGroup As CodeGroup = CType(childGroups.Current, CodeGroup) If thisCodeGroup.Name = "MyCompanyCodeGroup" Then machineLevel.RootCodeGroup.RemoveChild(thisCodeGroup) End If End While End While End Sub 'DeleteCustomCodeGroups Private Shared Sub DeleteCustomChildCodeGroup(ByVal codeGroupName As String) ' Delete the custom child group. ' Delete the child group by creating a copy of the parent code group, deleting its children, ' then adding the copy of the parent code group back to the root code group. Dim policyEnumerator As IEnumerator = SecurityManager.PolicyHierarchy() While policyEnumerator.MoveNext() Dim machineLevel As PolicyLevel = CType(policyEnumerator.Current, PolicyLevel) ' IList returns copies of the code groups, not the code groups themselves, ' so operations on the IList objects do not affect the actual code group. Dim childCodeGroups As IList = machineLevel.RootCodeGroup.Children Dim childGroups As IEnumerator = childCodeGroups.GetEnumerator() While childGroups.MoveNext() Dim thisCodeGroup As CodeGroup = CType(childGroups.Current, CodeGroup) If thisCodeGroup.Name = codeGroupName Then ' Create a new code group from this one, but without it's children. ' Delete the original code group and add the new one just created. Dim newCodeGroup As CodeGroup = thisCodeGroup Dim childCodeGroup As IList = newCodeGroup.Children Dim childGroup As IEnumerator = childCodeGroup.GetEnumerator() While childGroup.MoveNext() ' Remove all the children from the copy. newCodeGroup.RemoveChild(CType(childGroup.Current, CodeGroup)) End While ' Should have a copy of the parent code group with children removed. ' Delete the original parent code group and replace with its childless clone. machineLevel.RootCodeGroup.RemoveChild(thisCodeGroup) machineLevel.RootCodeGroup.AddChild(newCodeGroup) SecurityManager.SavePolicy() End If End While End While End Sub 'DeleteCustomChildCodeGroup ' Create a custom named permission set based on the LocalIntranet permission set. Private Shared Sub CreateCompanyPermission() Dim policyEnumerator As IEnumerator = SecurityManager.PolicyHierarchy() ' Move through the policy levels to the Machine policy level. While policyEnumerator.MoveNext() Dim currentLevel As PolicyLevel = CType(policyEnumerator.Current, PolicyLevel) If currentLevel.Label = "Machine" Then ' Enumerate the permission sets in the Machine policy level. Dim namedPermissions As IList = currentLevel.NamedPermissionSets Dim namedPermission As IEnumerator = namedPermissions.GetEnumerator() ' Locate the LocalIntranet permission set. While namedPermission.MoveNext() If CType(namedPermission.Current, NamedPermissionSet).Name = "LocalIntranet" Then ' The current permission set is a copy of the LocalIntranet permission set. ' It can be modified to provide the permissions for the new permission set. ' Rename the copy to the name chosen for the new permission set. CType(namedPermission.Current, NamedPermissionSet).Name = "MyCompany" Dim permissions As IEnumerator = CType(namedPermission.Current, NamedPermissionSet).GetEnumerator() ' Remove the current security permission from the permission set and replace it ' with a new security permission that does not have the right to assert permissions. While permissions.MoveNext() If permissions.Current.GetType().ToString() = "System.Security.Permissions.SecurityPermission" Then ' Remove the current security permission. CType(namedPermission.Current, NamedPermissionSet).RemovePermission(permissions.Current.GetType()) ' Add a new security permission that only allows execution. CType(namedPermission.Current, NamedPermissionSet).AddPermission(New SecurityPermission(SecurityPermissionFlag.Execution)) Exit While End If End While Try ' If you run this application twice, the following instruction throws ' an exception because the named permission set is already present. ' You can remove the custom named permission set using Caspole.exe or the ' .NET Framework Configuration tool currentLevel.AddNamedPermissionSet(CType(namedPermission.Current, NamedPermissionSet)) SecurityManager.SavePolicy() ' Catch the exception for a duplicate permission set. Catch e As System.ArgumentException Console.WriteLine(e.Message) Return End Try Console.WriteLine(CType(namedPermission.Current, NamedPermissionSet).ToString()) Exit While End If End While End If End While End Sub 'CreateCompanyPermission ' Create new code groups using the custom named permission sets previously created. Private Shared Sub CreateCodeGroups() ' Create instances of the named permission sets created earlier to establish the ' permissions for the new code groups. Dim companyCodeSet As New NamedPermissionSet("MyCompany", PermissionState.Unrestricted) Dim departmentCodeSet As New NamedPermissionSet("MyDepartment", PermissionState.Unrestricted) ' Create new code groups using the named permission sets. Dim policyMyCompany As New PolicyStatement(companyCodeSet, PolicyStatementAttribute.LevelFinal) Dim policyMyDepartment As New PolicyStatement(departmentCodeSet, PolicyStatementAttribute.Exclusive) ' Create new code groups using UnionCodeGroup. Dim myCompanyZone = New UnionCodeGroup(New ZoneMembershipCondition(SecurityZone.Intranet), policyMyCompany) myCompanyZone.Name = "MyCompanyCodeGroup" Dim b1 As Byte() = {0, 36, 0, 0, 4, 128, 0, 0, 148, 0, 0, 0, 6, 2, 0, 0, 0, 36, 0, 0, 82, 83, 65, 49, 0, 4, 0, 0, 1, 0, 1, 0, 237, 146, 145, 51, 34, 97, 123, 196, 90, 174, 41, 170, 173, 221, 41, 193, 175, 39, 7, 151, 178, 0, 230, 152, 218, 8, 206, 206, 170, 84, 111, 145, 26, 208, 158, 240, 246, 219, 228, 34, 31, 163, 11, 130, 16, 199, 111, 224, 4, 112, 46, 84, 0, 104, 229, 38, 39, 63, 53, 189, 0, 157, 32, 38, 34, 109, 0, 171, 114, 244, 34, 59, 9, 232, 150, 192, 247, 175, 104, 143, 171, 42, 219, 66, 66, 194, 191, 218, 121, 59, 92, 42, 37, 158, 13, 108, 210, 189, 9, 203, 204, 32, 48, 91, 212, 101, 193, 19, 227, 107, 25, 133, 70, 2, 220, 83, 206, 71, 102, 245, 104, 252, 87, 109, 190, 56, 34, 180} Dim blob As New StrongNamePublicKeyBlob(b1) Dim myDepartmentZone = New UnionCodeGroup(New StrongNameMembershipCondition(blob, Nothing, Nothing), policyMyDepartment) myDepartmentZone.Name = "MyDepartmentCodeGroup" ' Move through the policy levels looking for the Machine policy level. ' Create two new code groups at that level. Dim policyEnumerator As IEnumerator = SecurityManager.PolicyHierarchy() While policyEnumerator.MoveNext() ' At the Machine level delete already existing copies of the custom code groups, ' then create the new code groups. Dim currentLevel As PolicyLevel = CType(policyEnumerator.Current, PolicyLevel) If currentLevel.Label = "Machine" Then ' Remove old instances of the custom groups. DeleteCustomCodeGroups() ' Add the new code groups. '******************************************************* ' To add a child code group, add the child to the parent prior to adding ' the parent to the root. myCompanyZone.AddChild(myDepartmentZone) ' Add the parent to the root code group. currentLevel.RootCodeGroup.AddChild(myCompanyZone) SecurityManager.SavePolicy() End If End While ' Save the security policy. SecurityManager.SavePolicy() Console.WriteLine("Security policy modified.") Console.WriteLine("New code groups added at the Machine policy level.") End Sub 'CreateCodeGroups Private Shared Sub CreateDepartmentPermission() Dim policyEnumerator As IEnumerator = SecurityManager.PolicyHierarchy() ' Move through the policy levels to the Machine policy level. While policyEnumerator.MoveNext() Dim currentLevel As PolicyLevel = CType(policyEnumerator.Current, PolicyLevel) If currentLevel.Label = "Machine" Then ' Enumerate the permission sets in the Machine level. Dim namedPermissions As IList = currentLevel.NamedPermissionSets Dim namedPermission As IEnumerator = namedPermissions.GetEnumerator() ' Locate the Everything permission set. While namedPermission.MoveNext() If CType(namedPermission.Current, NamedPermissionSet).Name = "Everything" Then ' The current permission set is a copy of the Everything permission set. ' It can be modified to provide the permissions for the new permission set. ' Rename the copy to the name chosen for the new permission set. CType(namedPermission.Current, NamedPermissionSet).Name = "MyDepartment" Dim permissions As IEnumerator = CType(namedPermission.Current, NamedPermissionSet).GetEnumerator() ' Modify security permission by removing and replacing with a new permission. While permissions.MoveNext() If permissions.Current.GetType().ToString() = "System.Security.Permissions.SecurityPermission" Then CType(namedPermission.Current, NamedPermissionSet).RemovePermission(permissions.Current.GetType()) ' Add a new security permission with limited permissions. Dim limitedPermission As New SecurityPermission(SecurityPermissionFlag.Execution Or SecurityPermissionFlag.RemotingConfiguration Or SecurityPermissionFlag.ControlThread) CType(namedPermission.Current, NamedPermissionSet).AddPermission(limitedPermission) Exit While End If End While Try ' If you run this application twice, the following instruction throws ' an exception because the named permission set is already present. ' You can remove the custom named permission set using Caspole.exe or the ' .NET Framework Configuration tool currentLevel.AddNamedPermissionSet(CType(namedPermission.Current, NamedPermissionSet)) SecurityManager.SavePolicy() Catch e As System.ArgumentException Console.WriteLine(e.Message) End Try Console.WriteLine(CType(namedPermission.Current, NamedPermissionSet).ToString()) Exit While End If End While End If End While End Sub 'CreateDepartmentPermission Private Shared Sub DeleteCustomPermissions() Dim policyEnumerator As IEnumerator = SecurityManager.PolicyHierarchy() ' Move through the policy levels to the Machine policy level. While policyEnumerator.MoveNext() Dim currentLevel As PolicyLevel = CType(policyEnumerator.Current, PolicyLevel) If currentLevel.Label = "Machine" Then Try currentLevel.RemoveNamedPermissionSet("MyCompany") currentLevel.RemoveNamedPermissionSet("MyDepartment") Catch e As System.ArgumentException ' An exception is thrown if the named permission set cannot be found. Console.WriteLine(e.Message) End Try End If End While End Sub 'DeleteCustomPermissions ' Demonstrate the use of ResolvePolicy. Private 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("Current evidence belongs to the following code groups:") Dim policyEnumerator As IEnumerator = SecurityManager.PolicyHierarchy() While policyEnumerator.MoveNext() Dim currentLevel As PolicyLevel = CType(policyEnumerator.Current, PolicyLevel) Dim cg1 As CodeGroup = currentLevel.ResolveMatchingCodeGroups(evidence) Console.WriteLine((currentLevel.Label + " Level")) Console.WriteLine((ControlChars.Tab + "CodeGroup = " + cg1.Name)) Console.WriteLine(("StoreLocation = " + currentLevel.StoreLocation)) Dim cgE1 As IEnumerator = cg1.Children.GetEnumerator() While cgE1.MoveNext() Console.WriteLine((ControlChars.Tab + ControlChars.Tab + "Group = " + CType(cgE1.Current, CodeGroup).Name)) End While End While ' Show how ResolvePolicy is used to determine the set of permissions that would be granted ' by the security system to code, based on the evidence and the permission sets requested. ' The permission sets require Execute permission; allow optional Read access permission ' to C:\temp; and deny the code permission to control security policy. Console.WriteLine((ControlChars.Lf + "Create permission sets requiring Execute permission, requesting optional " + ControlChars.Lf + "Read permission for 'C:\temp', and dening permission to control policy.")) Dim requiredSet As New PermissionSet(PermissionState.None) requiredSet.AddPermission(New SecurityPermission(SecurityPermissionFlag.Execution)) Dim optionalSet As New PermissionSet(PermissionState.None) optionalSet.AddPermission(New FileIOPermission(FileIOPermissionAccess.Read, New String() {"c:\temp"})) Dim deniedSet As New PermissionSet(PermissionState.None) deniedSet.AddPermission(New SecurityPermission(SecurityPermissionFlag.ControlPolicy)) ' Show the granted permissions. Console.WriteLine(ControlChars.Lf + "Current permissions granted:") Dim permsDenied As PermissionSet = Nothing Dim perm As IPermission For Each perm In SecurityManager.ResolvePolicy(evidence, requiredSet, optionalSet, deniedSet, permsDenied) Console.WriteLine(perm.ToXml().ToString()) Next perm ' Show the denied permissions. Console.WriteLine("Current permissions denied:") 'Dim perm As IPermission For Each perm In permsDenied Console.WriteLine(perm.ToXml().ToString()) Next perm Return End Sub 'CheckEvidence End Class 'SecurityManagerSample
// 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; class SecurityManagerSample { static void Main() { // Gets a value indicating whether code must have execution rights in order to execute. if(!SecurityManager.CheckExecutionRights) Console.WriteLine("Execution rights are not required to run the assemblies."); // Gets a value indicating whether code access security is enabled. if(!SecurityManager.SecurityEnabled) Console.WriteLine("Security is not enabled."); // Determines whether the right to control policy has been granted to the caller. if(SecurityManager.IsGranted(new SecurityPermission(SecurityPermissionFlag.ControlPolicy))) { // Define custom named permission sets for Company and Department. // These will be used for the new code groups. CreateCompanyPermission(); CreateDepartmentPermission(); // Create a parent and child code group at the Machine policy level using the // permission sets we created. CreateCodeGroups(); // Demonstrate the result of a call to ResolvePolicy(). // This is not required for the main thrust of this sample, custom named permissions // and code groups, but allows demonstration of the ResolvePolicy method. Console.WriteLine("Current Security Policy:"); Console.WriteLine("------------------------"); DisplaySecurityPolicy(); Console.WriteLine("Resolve Policy demonstration."); // Get the evidence for the Local Intranet zone. Evidence intranetZoneEvidence = new Evidence(new object[] { new Zone(SecurityZone.Intranet) }, null); Console.WriteLine("Show the result of ResolvePolicy for LocalIntranet zone evidence."); CheckEvidence(intranetZoneEvidence); // Optionally remove the policy elements that were created. Console.WriteLine("Would you like to remove the Department code group?"); Console.WriteLine("Please type 'yes' to delete the Department group, else press the Enter key."); string answer = Console.ReadLine(); if(answer == "yes") { DeleteCustomChildCodeGroup("MyDepartment"); SecurityManager.SavePolicy(); } Console.WriteLine("Would you like to remove all new code groups and permission sets?"); Console.WriteLine("Please type yes to delete all new groups, else press the Enter key."); answer = Console.ReadLine(); if(answer == "yes") { DeleteCustomCodeGroups(); DeleteCustomPermissions(); SecurityManager.SavePolicy(); } } else { Console.Out.WriteLine("ControlPolicy permission is denied."); } return; } private static void DisplaySecurityPolicy() { IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy(); while(policyEnumerator.MoveNext()) { PolicyLevel currentLevel = (PolicyLevel)policyEnumerator.Current; // Display the policy at the current level. Console.WriteLine("Policy Level {0}:", currentLevel.Label); // To display the policy detail, uncomment the following line: //Console.WriteLine(currentLevel.ToXml().ToString()); IList namedPermissions = currentLevel.NamedPermissionSets; IEnumerator namedPermission = namedPermissions.GetEnumerator(); while(namedPermission.MoveNext()) { Console.WriteLine("\t" + ((NamedPermissionSet)namedPermission.Current).Name); } } } private static void DeleteCustomCodeGroups() { // Delete the custom code groups that were created. IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy(); while(policyEnumerator.MoveNext()) { PolicyLevel machineLevel = (PolicyLevel)policyEnumerator.Current; IList childCodeGroups = machineLevel.RootCodeGroup.Children; IEnumerator childGroups = childCodeGroups.GetEnumerator(); while(childGroups.MoveNext()) { CodeGroup thisCodeGroup = (CodeGroup)childGroups.Current; if( thisCodeGroup.Name == "MyCompanyCodeGroup") { machineLevel.RootCodeGroup.RemoveChild(thisCodeGroup); } } } } private static void DeleteCustomChildCodeGroup(string codeGroupName) { // Delete the custom child group. // Delete the child group by creating a copy of the parent code group, deleting its children, // then adding the copy of the parent code group back to the root code group. IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy(); while(policyEnumerator.MoveNext()) { PolicyLevel machineLevel = (PolicyLevel)policyEnumerator.Current; // IList returns copies of the code groups, not the code groups themselves, // so operations on the IList objects do not affect the actual code group. IList childCodeGroups = machineLevel.RootCodeGroup.Children; IEnumerator childGroups = childCodeGroups.GetEnumerator(); while(childGroups.MoveNext()) { CodeGroup thisCodeGroup = (CodeGroup)childGroups.Current; if(thisCodeGroup.Name == codeGroupName) { // Create a new code group from this one, but without it's children. // Delete the original code group and add the new one just created. CodeGroup newCodeGroup = thisCodeGroup; IList childCodeGroup = newCodeGroup.Children; IEnumerator childGroup = childCodeGroup.GetEnumerator(); while(childGroup.MoveNext()) { // Remove all the children from the copy. newCodeGroup.RemoveChild((CodeGroup)childGroup.Current); } // Should have a copy of the parent code group with children removed. // Delete the original parent code group and replace with its childless clone. machineLevel.RootCodeGroup.RemoveChild(thisCodeGroup); machineLevel.RootCodeGroup.AddChild(newCodeGroup); SecurityManager.SavePolicy(); } } } } // Create a custom named permission set based on the LocalIntranet permission set. private static void CreateCompanyPermission() { IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy(); // Move through the policy levels to the Machine policy level. while(policyEnumerator.MoveNext()) { PolicyLevel currentLevel = (PolicyLevel)policyEnumerator.Current; if(currentLevel.Label == "Machine") { // Enumerate the permission sets in the Machine policy level. IList namedPermissions = currentLevel.NamedPermissionSets; IEnumerator namedPermission = namedPermissions.GetEnumerator(); // Locate the LocalIntranet permission set. while(namedPermission.MoveNext()) { if(((NamedPermissionSet)namedPermission.Current).Name == "LocalIntranet") { // The current permission set is a copy of the LocalIntranet permission set. // It can be modified to provide the permissions for the new permission set. // Rename the copy to the name chosen for the new permission set. ((NamedPermissionSet)namedPermission.Current).Name = "MyCompany"; IEnumerator permissions = ((NamedPermissionSet)namedPermission.Current).GetEnumerator(); // Remove the current security permission from the permission set and replace it // with a new security permission that does not have the right to assert permissions. while(permissions.MoveNext()) { if(permissions.Current.GetType().ToString() == "System.Security.Permissions.SecurityPermission") { // Remove the current security permission. ((NamedPermissionSet)namedPermission.Current).RemovePermission(permissions.Current.GetType()); // Add a new security permission that only allows execution. ((NamedPermissionSet)namedPermission.Current).AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); break; } } try { // If you run this application twice, the following instruction throws // an exception because the named permission set is already present. // You can remove the custom named permission set using Caspole.exe or the // .NET Framework Configuration tool currentLevel.AddNamedPermissionSet(((NamedPermissionSet)namedPermission.Current)); SecurityManager.SavePolicy(); } // Catch the exception for a duplicate permission set. catch ( System.ArgumentException e) { Console.WriteLine(e.Message); return; } Console.WriteLine(((NamedPermissionSet)namedPermission.Current).ToString()); break; } } } } } // Create new code groups using the custom named permission sets previously created. private static void CreateCodeGroups() { // Create instances of the named permission sets created earlier to establish the // permissions for the new code groups. NamedPermissionSet companyCodeSet = new NamedPermissionSet("MyCompany" ,PermissionState.Unrestricted); NamedPermissionSet departmentCodeSet = new NamedPermissionSet("MyDepartment" ,PermissionState.Unrestricted); // Create new code groups using the named permission sets. PolicyStatement policyMyCompany = new PolicyStatement(companyCodeSet ,PolicyStatementAttribute.LevelFinal); PolicyStatement policyMyDepartment = new PolicyStatement(departmentCodeSet ,PolicyStatementAttribute.Exclusive); // Create new code groups using UnionCodeGroup. CodeGroup myCompanyZone = new UnionCodeGroup(new ZoneMembershipCondition(SecurityZone.Intranet), policyMyCompany); myCompanyZone.Name = "MyCompanyCodeGroup"; byte[] b1 = { 0, 36, 0, 0, 4, 128, 0, 0, 148, 0, 0, 0, 6, 2, 0, 0, 0, 36, 0, 0, 82, 83, 65, 49, 0, 4, 0, 0, 1, 0, 1, 0, 237, 146, 145, 51, 34, 97, 123, 196, 90, 174, 41, 170, 173, 221, 41, 193, 175, 39, 7, 151, 178, 0, 230, 152, 218, 8, 206, 206, 170,84, 111, 145, 26, 208, 158, 240, 246, 219, 228, 34, 31, 163, 11, 130, 16, 199, 111, 224, 4, 112, 46, 84, 0, 104, 229, 38, 39, 63, 53, 189, 0, 157, 32, 38, 34, 109, 0, 171, 114, 244, 34, 59, 9, 232, 150, 192, 247, 175, 104, 143, 171, 42, 219, 66, 66, 194, 191, 218, 121, 59, 92, 42, 37, 158, 13, 108, 210, 189, 9, 203, 204, 32, 48, 91, 212, 101, 193, 19, 227, 107, 25, 133, 70, 2, 220, 83, 206, 71, 102, 245, 104, 252, 87, 109, 190, 56, 34, 180}; StrongNamePublicKeyBlob blob = new StrongNamePublicKeyBlob(b1); CodeGroup myDepartmentZone = new UnionCodeGroup(new StrongNameMembershipCondition(blob,null , null ), policyMyDepartment); myDepartmentZone.Name = "MyDepartmentCodeGroup"; // Move through the policy levels looking for the Machine policy level. // Create two new code groups at that level. IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy(); while(policyEnumerator.MoveNext()) { // At the Machine level delete already existing copies of the custom code groups, // then create the new code groups. PolicyLevel currentLevel = (PolicyLevel)policyEnumerator.Current; if (currentLevel.Label == "Machine") { // Remove old instances of the custom groups. DeleteCustomCodeGroups(); // Add the new code groups. //******************************************************* // To add a child code group, add the child to the parent prior to adding // the parent to the root. myCompanyZone.AddChild(myDepartmentZone); // Add the parent to the root code group. currentLevel.RootCodeGroup.AddChild(myCompanyZone); SecurityManager.SavePolicy(); } } // Save the security policy. SecurityManager.SavePolicy(); Console.WriteLine("Security policy modified."); Console.WriteLine("New code groups added at the Machine policy level."); } private static void CreateDepartmentPermission() { IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy(); // Move through the policy levels to the Machine policy level. while(policyEnumerator.MoveNext()) { PolicyLevel currentLevel = (PolicyLevel)policyEnumerator.Current; if(currentLevel.Label == "Machine") { // Enumerate the permission sets in the Machine level. IList namedPermissions = currentLevel.NamedPermissionSets; IEnumerator namedPermission = namedPermissions.GetEnumerator(); // Locate the Everything permission set. while(namedPermission.MoveNext()) { if(((NamedPermissionSet)namedPermission.Current).Name == "Everything") { // The current permission set is a copy of the Everything permission set. // It can be modified to provide the permissions for the new permission set. // Rename the copy to the name chosen for the new permission set. ((NamedPermissionSet)namedPermission.Current).Name = "MyDepartment"; IEnumerator permissions = ((NamedPermissionSet)namedPermission.Current).GetEnumerator(); // Modify security permission by removing and replacing with a new permission. while(permissions.MoveNext()) { if(permissions.Current.GetType().ToString() == "System.Security.Permissions.SecurityPermission") { ((NamedPermissionSet)namedPermission.Current).RemovePermission(permissions.Current.GetType()); // Add a new security permission with limited permissions. SecurityPermission limitedPermission = new SecurityPermission(SecurityPermissionFlag.Execution | SecurityPermissionFlag.RemotingConfiguration | SecurityPermissionFlag.ControlThread); ((NamedPermissionSet)namedPermission.Current).AddPermission(limitedPermission); break; } } try { // If you run this application twice, the following instruction throws // an exception because the named permission set is already present. // You can remove the custom named permission set using Caspole.exe or the // .NET Framework Configuration tool currentLevel.AddNamedPermissionSet(((NamedPermissionSet)namedPermission.Current)); SecurityManager.SavePolicy(); } catch (System.ArgumentException e) { Console.WriteLine(e.Message); } Console.WriteLine(((NamedPermissionSet)namedPermission.Current).ToString()); break; } } } } } private static void DeleteCustomPermissions() { IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy(); // Move through the policy levels to the Machine policy level. while(policyEnumerator.MoveNext()) { PolicyLevel currentLevel = (PolicyLevel)policyEnumerator.Current; if(currentLevel.Label == "Machine") { try { currentLevel.RemoveNamedPermissionSet("MyCompany"); currentLevel.RemoveNamedPermissionSet("MyDepartment"); } catch(System.ArgumentException e) { // An exception is thrown if the named permission set cannot be found. Console.WriteLine(e.Message); } } } } // Demonstrate the use of ResolvePolicy. private static void CheckEvidence(Evidence evidence) { // Display the code groups to which the evidence belongs. Console.WriteLine("ResolvePolicy for the given evidence."); Console.WriteLine("Current evidence belongs to the following code groups:"); IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy(); while(policyEnumerator.MoveNext()) { PolicyLevel currentLevel = (PolicyLevel)policyEnumerator.Current; CodeGroup cg1 = currentLevel.ResolveMatchingCodeGroups(evidence); Console.WriteLine(currentLevel.Label + " Level" ); Console.WriteLine("\tCodeGroup = " + cg1.Name); Console.WriteLine("StoreLocation = " + currentLevel.StoreLocation); IEnumerator cgE1 = cg1.Children.GetEnumerator(); while(cgE1.MoveNext()) { Console.WriteLine("\t\tGroup = " + ((CodeGroup)cgE1.Current).Name); } } // Show how ResolvePolicy is used to determine the set of permissions that would be granted // by the security system to code, based on the evidence and the permission sets requested. // The permission sets require Execute permission; allow optional Read access permission // to C:\temp; and deny the code permission to control security policy. Console.WriteLine("\nCreate permission sets requiring Execute permission, requesting optional " + "\nRead permission for 'C:\\temp', and dening permission to control policy."); PermissionSet requiredSet = new PermissionSet(PermissionState.None); requiredSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); PermissionSet optionalSet = new PermissionSet(PermissionState.None); optionalSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, new string[] { @"c:\temp" })); PermissionSet deniedSet = new PermissionSet(PermissionState.None); deniedSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlPolicy)); // Show the granted permissions. Console.WriteLine("\nCurrent permissions granted:"); PermissionSet permsDenied = null; foreach(IPermission perm in SecurityManager.ResolvePolicy(evidence, requiredSet, optionalSet, deniedSet, out permsDenied)) Console.WriteLine(perm.ToXml().ToString()); // Show the denied permissions. Console.WriteLine("Current permissions denied:"); foreach(IPermission perm in permsDenied) Console.WriteLine(perm.ToXml().ToString()); return; } }
// 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; void DisplaySecurityPolicy(); void DeleteCustomCodeGroups(); void DeleteCustomChildCodeGroup( String^ codeGroupName ); void CreateCompanyPermission(); void CreateCodeGroups(); void CreateDepartmentPermission(); void DeleteCustomPermissions(); void CheckEvidence( Evidence^ evidence ); int main() { // Gets a value indicating whether code must have execution rights in order to execute. if ( !SecurityManager::CheckExecutionRights ) Console::WriteLine( "Execution rights are not required to run the assemblies." ); // Gets a value indicating whether code access security is enabled. if ( !SecurityManager::SecurityEnabled ) Console::WriteLine( "Security is not enabled." ); // Determines whether the right to control policy has been granted to the caller. if ( SecurityManager::IsGranted( gcnew SecurityPermission( SecurityPermissionFlag::ControlPolicy ) ) ) { // Define custom named permission sets for Company and Department. // These will be used for the new code groups. CreateCompanyPermission(); CreateDepartmentPermission(); // Create a parent and child code group at the Machine policy level using the // permission sets we created. CreateCodeGroups(); // Demonstrate the result of a call to ResolvePolicy(). // This is not required for the main thrust of this sample, custom named permissions // and code groups, but allows demonstration of the ResolvePolicy method. Console::WriteLine( "Current Security Policy:" ); Console::WriteLine( "------------------------" ); DisplaySecurityPolicy(); Console::WriteLine( "Resolve Policy demonstration." ); // Get the evidence for the Local Intranet zone. array<Object^>^temp0 = {gcnew Zone( SecurityZone::Intranet )}; Evidence^ intranetZoneEvidence = gcnew Evidence( temp0,nullptr ); Console::WriteLine( "Show the result of ResolvePolicy for LocalIntranet zone evidence." ); CheckEvidence( intranetZoneEvidence ); // Optionally remove the policy elements that were created. Console::WriteLine( "Would you like to remove the Department code group?" ); Console::WriteLine( "Please type 'yes' to delete the Department group, else press the Enter key." ); String^ answer = Console::ReadLine(); if ( answer->Equals( "yes" ) ) { DeleteCustomChildCodeGroup( "MyDepartment" ); SecurityManager::SavePolicy(); } Console::WriteLine( "Would you like to remove all new code groups and permission sets?" ); Console::WriteLine( "Please type yes to delete all new groups, else press the Enter key." ); answer = Console::ReadLine(); if ( answer->Equals( "yes" ) ) { DeleteCustomCodeGroups(); DeleteCustomPermissions(); SecurityManager::SavePolicy(); } } else { Console::Out->WriteLine( "ControlPolicy permission is denied." ); } } void DisplaySecurityPolicy() { IEnumerator^ policyEnumerator = SecurityManager::PolicyHierarchy(); while ( policyEnumerator->MoveNext() ) { PolicyLevel^ currentLevel = dynamic_cast<PolicyLevel^>(policyEnumerator->Current); // Display the policy at the current level. Console::WriteLine( "Policy Level {0}:", currentLevel->Label ); // To display the policy detail, uncomment the following line: //Console.WriteLine(currentLevel.ToXml().ToString()); IList^ namedPermissions = currentLevel->NamedPermissionSets; IEnumerator^ namedPermission = namedPermissions->GetEnumerator(); while ( namedPermission->MoveNext() ) { Console::WriteLine( "\t{0}", (dynamic_cast<NamedPermissionSet^>(namedPermission->Current))->Name ); } } } void DeleteCustomCodeGroups() { // Delete the custom code groups that were created. IEnumerator^ policyEnumerator = SecurityManager::PolicyHierarchy(); while ( policyEnumerator->MoveNext() ) { PolicyLevel^ machineLevel = dynamic_cast<PolicyLevel^>(policyEnumerator->Current); IList^ childCodeGroups = machineLevel->RootCodeGroup->Children; IEnumerator^ childGroups = childCodeGroups->GetEnumerator(); while ( childGroups->MoveNext() ) { CodeGroup^ thisCodeGroup = dynamic_cast<CodeGroup^>(childGroups->Current); if ( thisCodeGroup->Name->Equals( "MyCompanyCodeGroup" ) ) { machineLevel->RootCodeGroup->RemoveChild( thisCodeGroup ); } } } } void DeleteCustomChildCodeGroup( String^ codeGroupName ) { // Delete the custom child group. // Delete the child group by creating a copy of the parent code group, deleting its children, // then adding the copy of the parent code group back to the root code group. IEnumerator^ policyEnumerator = SecurityManager::PolicyHierarchy(); while ( policyEnumerator->MoveNext() ) { PolicyLevel^ machineLevel = dynamic_cast<PolicyLevel^>(policyEnumerator->Current); // IList returns copies of the code groups, not the code groups themselves, // so operations on the IList objects do not affect the actual code group. IList^ childCodeGroups = machineLevel->RootCodeGroup->Children; IEnumerator^ childGroups = childCodeGroups->GetEnumerator(); while ( childGroups->MoveNext() ) { CodeGroup^ thisCodeGroup = dynamic_cast<CodeGroup^>(childGroups->Current); if ( thisCodeGroup->Name == codeGroupName ) { // Create a new code group from this one, but without it's children. // Delete the original code group and add the new one just created. CodeGroup^ newCodeGroup = thisCodeGroup; IList^ childCodeGroup = newCodeGroup->Children; IEnumerator^ childGroup = childCodeGroup->GetEnumerator(); while ( childGroup->MoveNext() ) { // Remove all the children from the copy. newCodeGroup->RemoveChild( dynamic_cast<CodeGroup^>(childGroup->Current) ); } // Delete the original parent code group and replace with its childless clone. machineLevel->RootCodeGroup->RemoveChild( thisCodeGroup ); machineLevel->RootCodeGroup->AddChild( newCodeGroup ); SecurityManager::SavePolicy(); } } } } // Create a custom named permission set based on the LocalIntranet permission set. void CreateCompanyPermission() { IEnumerator^ policyEnumerator = SecurityManager::PolicyHierarchy(); // Move through the policy levels to the Machine policy level. while ( policyEnumerator->MoveNext() ) { PolicyLevel^ currentLevel = dynamic_cast<PolicyLevel^>(policyEnumerator->Current); if ( currentLevel->Label->Equals( "Machine" ) ) { // Enumerate the permission sets in the Machine policy level. IList^ namedPermissions = currentLevel->NamedPermissionSets; IEnumerator^ namedPermission = namedPermissions->GetEnumerator(); // Locate the LocalIntranet permission set. while ( namedPermission->MoveNext() ) { if ( (dynamic_cast<NamedPermissionSet^>(namedPermission->Current))->Name->Equals( "LocalIntranet" ) ) { // The current permission set is a copy of the LocalIntranet permission set. // It can be modified to provide the permissions for the new permission set. // Rename the copy to the name chosen for the new permission set. (dynamic_cast<NamedPermissionSet^>(namedPermission->Current))->Name = "MyCompany"; IEnumerator^ permissions = (dynamic_cast<NamedPermissionSet^>(namedPermission->Current))->GetEnumerator(); // Remove the current security permission from the permission set and replace it // with a new security permission that does not have the right to assert permissions. while ( permissions->MoveNext() ) { if ( permissions->Current->GetType()->ToString()->Equals( "System.Security.Permissions.SecurityPermission" ) ) { // Remove the current security permission. (dynamic_cast<NamedPermissionSet^>(namedPermission->Current))->RemovePermission( permissions->Current->GetType() ); // Add a new security permission that only allows execution. (dynamic_cast<NamedPermissionSet^>(namedPermission->Current))->AddPermission( gcnew SecurityPermission( SecurityPermissionFlag::Execution ) ); break; } } try { // If you run this application twice, the following instruction throws // an exception because the named permission set is already present. // You can remove the custom named permission set using Caspole.exe or the // .NET Framework Configuration tool currentLevel->AddNamedPermissionSet( safe_cast<NamedPermissionSet^>(namedPermission->Current) ); SecurityManager::SavePolicy(); } // Catch the exception for a duplicate permission set. catch ( System::ArgumentException^ e ) { Console::WriteLine( e->Message ); return; } Console::WriteLine( ); break; } } } } } // Create new code groups using the custom named permission sets previously created. void CreateCodeGroups() { // Create instances of the named permission sets created earlier to establish the // permissions for the new code groups. NamedPermissionSet^ companyCodeSet = gcnew NamedPermissionSet( "MyCompany",PermissionState::Unrestricted ); NamedPermissionSet^ departmentCodeSet = gcnew NamedPermissionSet( "MyDepartment",PermissionState::Unrestricted ); // Create new code groups using the named permission sets. PolicyStatement^ policyMyCompany = gcnew PolicyStatement( companyCodeSet,PolicyStatementAttribute::LevelFinal ); PolicyStatement^ policyMyDepartment = gcnew PolicyStatement( departmentCodeSet,PolicyStatementAttribute::Exclusive ); // Create new code groups using UnionCodeGroup. CodeGroup^ myCompanyZone = gcnew UnionCodeGroup( gcnew ZoneMembershipCondition( SecurityZone::Intranet ),policyMyCompany ); myCompanyZone->Name = "MyCompanyCodeGroup"; array<Byte>^b1 = {0,36,0,0,4,128,0,0,148,0,0,0,6,2,0,0,0,36,0,0,82,83,65 ,49,0,4,0,0,1,0,1,0,237,146,145,51,34,97,123,196,90,174,41,170,173,221,41,193,175 ,39,7,151,178,0,230,152,218,8,206,206,170,84,111,145,26,208,158,240,246,219,228,34,31,163,11,130,16,199,111,224,4,112,46,84,0,104,229,38,39,63,53,189,0,157,32,38 ,34,109,0,171,114,244,34,59,9,232,150,192,247,175,104,143,171,42,219,66,66,194,191,218,121,59,92,42,37,158,13,108,210,189,9,203,204,32,48,91,212,101,193,19,227,107,25,133,70,2,220,83,206,71,102,245,104,252,87,109,190,56,34,180}; StrongNamePublicKeyBlob^ blob = gcnew StrongNamePublicKeyBlob( b1 ); CodeGroup^ myDepartmentZone = gcnew UnionCodeGroup( gcnew StrongNameMembershipCondition( blob,nullptr,nullptr ),policyMyDepartment ); myDepartmentZone->Name = "MyDepartmentCodeGroup"; // Move through the policy levels looking for the Machine policy level. // Create two new code groups at that level. IEnumerator^ policyEnumerator = SecurityManager::PolicyHierarchy(); while ( policyEnumerator->MoveNext() ) { // At the Machine level delete already existing copies of the custom code groups, // then create the new code groups. PolicyLevel^ currentLevel = dynamic_cast<PolicyLevel^>(policyEnumerator->Current); if ( currentLevel->Label->Equals( "Machine" ) ) { // Remove old instances of the custom groups. DeleteCustomCodeGroups(); // Add the new code groups. //******************************************************* // To add a child code group, add the child to the parent prior to adding // the parent to the root. myCompanyZone->AddChild( myDepartmentZone ); // Add the parent to the root code group. currentLevel->RootCodeGroup->AddChild( myCompanyZone ); SecurityManager::SavePolicy(); } } SecurityManager::SavePolicy(); Console::WriteLine( "Security policy modified." ); Console::WriteLine( "New code groups added at the Machine policy level." ); } void CreateDepartmentPermission() { IEnumerator^ policyEnumerator = SecurityManager::PolicyHierarchy(); // Move through the policy levels to the Machine policy level. while ( policyEnumerator->MoveNext() ) { PolicyLevel^ currentLevel = dynamic_cast<PolicyLevel^>(policyEnumerator->Current); if ( currentLevel->Label->Equals( "Machine" ) ) { // Enumerate the permission sets in the Machine level. IList^ namedPermissions = currentLevel->NamedPermissionSets; IEnumerator^ namedPermission = namedPermissions->GetEnumerator(); // Locate the Everything permission set. while ( namedPermission->MoveNext() ) { if ( (dynamic_cast<NamedPermissionSet^>(namedPermission->Current))->Name->Equals( "Everything" ) ) { // The current permission set is a copy of the Everything permission set. // It can be modified to provide the permissions for the new permission set. // Rename the copy to the name chosen for the new permission set. (dynamic_cast<NamedPermissionSet^>(namedPermission->Current))->Name = "MyDepartment"; IEnumerator^ permissions = (dynamic_cast<NamedPermissionSet^>(namedPermission->Current))->GetEnumerator(); // Modify security permission by removing and replacing with a new permission. while ( permissions->MoveNext() ) { if ( permissions->Current->GetType()->ToString()->Equals( "System.Security.Permissions.SecurityPermission" ) ) { (dynamic_cast<NamedPermissionSet^>(namedPermission->Current))->RemovePermission( permissions->Current->GetType() ); // Add a new security permission with limited permissions. SecurityPermission^ limitedPermission = gcnew SecurityPermission( static_cast<SecurityPermissionFlag>(SecurityPermissionFlag::Execution | SecurityPermissionFlag::RemotingConfiguration | SecurityPermissionFlag::ControlThread) ); (dynamic_cast<NamedPermissionSet^>(namedPermission->Current))->AddPermission( limitedPermission ); break; } } try { // If you run this application twice, the following instruction throws // an exception because the named permission set is already present. // You can remove the custom named permission set using Caspole.exe or the // .NET Framework Configuration tool currentLevel->AddNamedPermissionSet( safe_cast<NamedPermissionSet^>(namedPermission->Current) ); SecurityManager::SavePolicy(); } catch ( System::ArgumentException^ e ) { Console::WriteLine( e->Message ); } Console::WriteLine( ); break; } } } } } void DeleteCustomPermissions() { IEnumerator^ policyEnumerator = SecurityManager::PolicyHierarchy(); // Move through the policy levels to the Machine policy level. while ( policyEnumerator->MoveNext() ) { PolicyLevel^ currentLevel = dynamic_cast<PolicyLevel^>(policyEnumerator->Current); if ( currentLevel->Label->Equals( "Machine" ) ) { try { currentLevel->RemoveNamedPermissionSet( "MyCompany" ); currentLevel->RemoveNamedPermissionSet( "MyDepartment" ); } catch ( System::ArgumentException^ e ) { // An exception is thrown if the named permission set cannot be found. Console::WriteLine( e->Message ); } } } } // Demonstrate the use of ResolvePolicy. void CheckEvidence( Evidence^ evidence ) { // Display the code groups to which the evidence belongs. Console::WriteLine( "ResolvePolicy for the given evidence." ); Console::WriteLine( "Current evidence belongs to the following code groups:" ); IEnumerator^ policyEnumerator = SecurityManager::PolicyHierarchy(); while ( policyEnumerator->MoveNext() ) { PolicyLevel^ currentLevel = dynamic_cast<PolicyLevel^>(policyEnumerator->Current); CodeGroup^ cg1 = currentLevel->ResolveMatchingCodeGroups( evidence ); Console::WriteLine( "{0} Level", currentLevel->Label ); Console::WriteLine( "\tCodeGroup = {0}", cg1->Name ); Console::WriteLine( "StoreLocation = {0}", currentLevel->StoreLocation ); IEnumerator^ cgE1 = cg1->Children->GetEnumerator(); while ( cgE1->MoveNext() ) { Console::WriteLine( "\t\tGroup = {0}", (dynamic_cast<CodeGroup^>(cgE1->Current))->Name ); } } // Show how ResolvePolicy is used to determine the set of permissions that would be granted // by the security system to code, based on the evidence and the permission sets requested. // The permission sets require Execute permission; allow optional Read access permission // to C:\temp; and deny the code permission to control security policy. Console::WriteLine( "\nCreate permission sets requiring Execute permission, requesting optional " "\nRead permission for 'C:\\temp', and dening permission to control policy." ); PermissionSet^ requiredSet = gcnew PermissionSet( PermissionState::None ); requiredSet->AddPermission( gcnew SecurityPermission( SecurityPermissionFlag::Execution ) ); PermissionSet^ optionalSet = gcnew PermissionSet( PermissionState::None ); array<String^>^temp1 = {"c:\\temp"}; optionalSet->AddPermission( gcnew FileIOPermission( FileIOPermissionAccess::Read,temp1 ) ); PermissionSet^ deniedSet = gcnew PermissionSet( PermissionState::None ); deniedSet->AddPermission( gcnew SecurityPermission( SecurityPermissionFlag::ControlPolicy ) ); // Show the granted permissions. Console::WriteLine( "\nCurrent permissions granted:" ); PermissionSet^ permsDenied = nullptr; for each(IPermission^ perm in SecurityManager::ResolvePolicy(evidence, requiredSet, optionalSet, deniedSet, permsDenied)) Console::WriteLine(perm->ToXml()->ToString()); // Show the denied permissions. Console::WriteLine( "Current permissions denied:" ); IEnumerator^ myEnum1 = permsDenied->GetEnumerator(); while ( myEnum1->MoveNext() ) { IPermission^ perm = safe_cast<IPermission^>(myEnum1->Current); Console::WriteLine( perm->ToXml() ); } return; }
// 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; class SecurityManagerSample { public static void main(String[] args) { // Gets a value indicating whether code must have execution rights // in order to execute. if (!(SecurityManager.get_CheckExecutionRights())) { Console.WriteLine( "Execution rights are not required to run the assemblies."); } // Gets a value indicating whether code access security is enabled. if (!(SecurityManager.get_SecurityEnabled())) { Console.WriteLine("Security is not enabled."); } // Determines whether the right to control policy has been granted // to the caller. if (SecurityManager.IsGranted(new SecurityPermission (SecurityPermissionFlag.ControlPolicy))) { // Define custom named permission sets for Company and Department. // These will be used for the new code groups. CreateCompanyPermission(); CreateDepartmentPermission(); // Create a parent and child code group at the Machine policy // level using the permission sets we created. CreateCodeGroups(); // Demonstrate the result of a call to ResolvePolicy(). // This is not required for the main thrust of this sample, custom // named permissions and code groups, but allows demonstration of // the ResolvePolicy method. Console.WriteLine("Current Security Policy:"); Console.WriteLine("------------------------"); DisplaySecurityPolicy(); Console.WriteLine("Resolve Policy demonstration."); // Get the evidence for the Local Intranet zone. Evidence intranetZoneEvidence = new Evidence(new Object[] { new Zone(SecurityZone.Intranet) }, null); Console.WriteLine("Show the result of ResolvePolicy for" + " LocalIntranet zone evidence."); CheckEvidence(intranetZoneEvidence); // Optionally remove the policy elements that were created. Console.WriteLine("Would you like to remove the Department " + "code group?"); Console.WriteLine("Please type 'yes' to delete the Department" + " group, else press the Enter key."); String answer = Console.ReadLine(); if (answer.equalsIgnoreCase("yes")) { DeleteCustomChildCodeGroup("MyDepartment"); SecurityManager.SavePolicy(); } Console.WriteLine("Would you like to remove all new code groups " + "and permission sets?"); Console.WriteLine("Please type yes to delete all new groups, else" + " press the Enter key."); answer = Console.ReadLine(); if (answer.equalsIgnoreCase("yes")) { DeleteCustomCodeGroups(); DeleteCustomPermissions(); SecurityManager.SavePolicy(); } } else { Console.get_Out().WriteLine("ControlPolicy permission is denied."); } return; } //main private static void DisplaySecurityPolicy() { IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy(); while (policyEnumerator.MoveNext()) { PolicyLevel currentLevel = ((PolicyLevel) (policyEnumerator.get_Current())); // Display the policy at the current level. Console.WriteLine("Policy Level {0}:", currentLevel.get_Label()); // To display the policy detail, uncomment the following line: //Console.WriteLine(currentLevel.ToXml().ToString()); IList namedPermissions = currentLevel.get_NamedPermissionSets(); IEnumerator namedPermission = namedPermissions.GetEnumerator(); while (namedPermission.MoveNext()) { Console.WriteLine(("\t" + ((NamedPermissionSet) (namedPermission.get_Current())).get_Name())); } } } //DisplaySecurityPolicy private static void DeleteCustomCodeGroups() { // Delete the custom code groups that were created. IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy(); while (policyEnumerator.MoveNext()) { PolicyLevel machineLevel = ((PolicyLevel)(policyEnumerator.get_Current())); IList childCodeGroups = machineLevel.get_RootCodeGroup().get_Children(); IEnumerator childGroups = childCodeGroups.GetEnumerator(); while (childGroups.MoveNext()) { CodeGroup thisCodeGroup = ((CodeGroup)(childGroups.get_Current())); if (thisCodeGroup.get_Name().equalsIgnoreCase ("MyCompanyCodeGroup")) { machineLevel.get_RootCodeGroup() .RemoveChild(thisCodeGroup); } } } } //DeleteCustomCodeGroups private static void DeleteCustomChildCodeGroup(System.String codeGroupName) { // Delete the custom child group. // Delete the child group by creating a copy of the parent code group, // deleting its children,then adding the copy of the parent code group // back to the root code group. IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy(); while (policyEnumerator.MoveNext()) { PolicyLevel machineLevel = ((PolicyLevel)(policyEnumerator.get_Current())); // IList returns copies of the code groups, not the code groups // themselves,so operations on the IList objects do not affect // the actual code group. IList childCodeGroups = machineLevel.get_RootCodeGroup().get_Children(); IEnumerator childGroups = childCodeGroups.GetEnumerator(); while (childGroups.MoveNext()) { CodeGroup thisCodeGroup = ((CodeGroup)(childGroups.get_Current())); if (thisCodeGroup.get_Name().equalsIgnoreCase(codeGroupName)) { // Create a new code group from this one, but without // it's children.Delete the original code group and // add the new one just created. CodeGroup newCodeGroup = thisCodeGroup; IList childCodeGroup = newCodeGroup.get_Children(); IEnumerator childGroup = childCodeGroup.GetEnumerator(); while (childGroup.MoveNext()) { // Remove all the children from the copy. newCodeGroup.RemoveChild(((CodeGroup) (childGroup.get_Current()))); } // Should have a copy of the parent code group with // children removed.Delete the original parent code // group and replace with its childless clone. machineLevel.get_RootCodeGroup(). RemoveChild(thisCodeGroup); machineLevel.get_RootCodeGroup(). AddChild(newCodeGroup); SecurityManager.SavePolicy(); } } } } //DeleteCustomChildCodeGroup // Create a custom named permission set based on the LocalIntranet // permission set. private static void CreateCompanyPermission() { IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy(); // Move through the policy levels to the Machine policy level. while (policyEnumerator.MoveNext()) { PolicyLevel currentLevel = ((PolicyLevel)(policyEnumerator.get_Current())); if (currentLevel.get_Label().equalsIgnoreCase("Machine")) { // Enumerate the permission sets in the Machine policy level. IList namedPermissions = currentLevel.get_NamedPermissionSets(); IEnumerator namedPermission = namedPermissions.GetEnumerator(); // Locate the LocalIntranet permission set. while (namedPermission.MoveNext()) { if (((NamedPermissionSet)(namedPermission.get_Current())) .get_Name().equalsIgnoreCase("LocalIntranet")) { // The current permission set is a copy of the // LocalIntranet permission set.It can be modified // to provide the permissions for the new permission // set.Rename the copy to the name chosen for the new // permission set. ((NamedPermissionSet)(namedPermission.get_Current())). set_Name("MyCompany"); IEnumerator permissions = ((NamedPermissionSet) (namedPermission.get_Current())).GetEnumerator(); // Remove the current security permission from the // permission set and replace it with a new security // permission that does not have the right to assert // permissions. while (permissions.MoveNext()) { if ( permissions.get_Current().GetType().ToString() .equalsIgnoreCase("System.Security." + "Permissions.SecurityPermission")) { // Remove the current security permission. ((NamedPermissionSet) (namedPermission.get_Current())) .RemovePermission(permissions.get_Current() .GetType()); // Add a new security permission that only // allows execution. ((NamedPermissionSet) (namedPermission.get_Current())) .AddPermission(new SecurityPermission (SecurityPermissionFlag.Execution)); break; } } try { // If you run this application twice, the following // instruction throws an exception because the // named permission set is already present.You can // remove the custom named permission set using // Caspole.exe or the // .NET Framework Configuration tool currentLevel.AddNamedPermissionSet( ((NamedPermissionSet) (namedPermission.get_Current()))); SecurityManager.SavePolicy(); } // Catch the exception for a duplicate permission set. catch (System.ArgumentException e) { Console.WriteLine(e.get_Message()); return; } Console.WriteLine(((NamedPermissionSet) (namedPermission.get_Current())).ToString()); break; } } } } } //CreateCompanyPermission // Create new code groups using the custom named permission sets previously // created. private static void CreateCodeGroups() { // Create instances of the named permission sets created earlier to // establish the permissions for the new code groups. NamedPermissionSet companyCodeSet = new NamedPermissionSet ("MyCompany", PermissionState.Unrestricted); NamedPermissionSet departmentCodeSet = new NamedPermissionSet ("MyDepartment", PermissionState.Unrestricted); // Create new code groups using the named permission sets. PolicyStatement policyMyCompany = new PolicyStatement (companyCodeSet, PolicyStatementAttribute.LevelFinal); PolicyStatement policyMyDepartment = new PolicyStatement (departmentCodeSet, PolicyStatementAttribute.Exclusive); // Create new code groups using UnionCodeGroup. CodeGroup myCompanyZone = new UnionCodeGroup (new ZoneMembershipCondition(SecurityZone.Intranet) , policyMyCompany); myCompanyZone.set_Name("MyCompanyCodeGroup"); ubyte b1[] = { 0, 36, 0, 0, 4, 128, 0, 0, 148, 0, 0, 0, 6, 2, 0, 0, 0, 36, 0, 0, 82, 83, 65, 49, 0, 4, 0, 0, 1, 0, 1, 0, 237, 146, 145, 51, 34, 97, 123, 196, 90, 174, 41, 170, 173, 221, 41, 193, 175, 39, 7, 151, 178, 0, 230, 152, 218, 8, 206, 206, 170, 84, 111, 145, 26, 208, 158, 240, 246, 219, 228, 34, 31, 163, 11, 130, 16, 199, 111, 224, 4, 112, 46, 84, 0, 104, 229, 38, 39, 63, 53, 189, 0, 157, 32, 38, 34, 109, 0, 171, 114, 244, 34, 59, 9, 232, 150, 192, 247, 175, 104, 143, 171, 42, 219, 66, 66, 194, 191, 218, 121, 59, 92, 42, 37, 158, 13, 108, 210, 189, 9, 203, 204, 32, 48, 91, 212, 101, 193, 19, 227, 107, 25, 133, 70, 2, 220, 83, 206, 71, 102, 245, 104, 252, 87, 109, 190, 56, 34, 180 }; StrongNamePublicKeyBlob blob = new StrongNamePublicKeyBlob(b1); CodeGroup myDepartmentZone = new UnionCodeGroup(new StrongNameMembershipCondition (blob, null, null), policyMyDepartment); myDepartmentZone.set_Name("MyDepartmentCodeGroup"); // Move through the policy levels looking for the Machine policy level. // Create two new code groups at that level. IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy(); while (policyEnumerator.MoveNext()) { // At the Machine level delete already existing copies of the // custom code groups,then create the new code groups. PolicyLevel currentLevel = ((PolicyLevel)(policyEnumerator.get_Current())); if (currentLevel.get_Label().equalsIgnoreCase("Machine")) { // Remove old instances of the custom groups. DeleteCustomCodeGroups(); // Add the new code groups. //******************************************************* // To add a child code group, add the child to the parent // prior to adding the parent to the root. myCompanyZone.AddChild(myDepartmentZone); // Add the parent to the root code group. currentLevel.get_RootCodeGroup().AddChild(myCompanyZone); SecurityManager.SavePolicy(); } } // Save the security policy. SecurityManager.SavePolicy(); Console.WriteLine("Security policy modified."); Console.WriteLine("New code groups added at the Machine" + " policy level."); } //CreateCodeGroups private static void CreateDepartmentPermission() { IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy(); // Move through the policy levels to the Machine policy level. while (policyEnumerator.MoveNext()) { PolicyLevel currentLevel = ((PolicyLevel) (policyEnumerator.get_Current())); if (currentLevel.get_Label().equalsIgnoreCase("Machine")) { // Enumerate the permission sets in the Machine level. IList namedPermissions = currentLevel.get_NamedPermissionSets(); IEnumerator namedPermission = namedPermissions.GetEnumerator(); // Locate the Everything permission set. while (namedPermission.MoveNext()) { if (((NamedPermissionSet)(namedPermission.get_Current())) .get_Name().equalsIgnoreCase("Everything")) { // The current permission set is a copy of the // Everything permission set.It can be modified //to provide the permissions for the new permission // set.Rename the copy to the name chosen for the new // permission set. ((NamedPermissionSet)(namedPermission.get_Current())) .set_Name("MyDepartment"); IEnumerator permissions = ((NamedPermissionSet) (namedPermission.get_Current())).GetEnumerator(); // Modify security permission by removing and // replacing with a new permission. while (permissions.MoveNext()) { if (permissions.get_Current().GetType().ToString() .equalsIgnoreCase ("System.Security.Permissions" + ".SecurityPermission")) { ((NamedPermissionSet) (namedPermission.get_Current())) .RemovePermission(permissions.get_Current() .GetType()); // Add a new security permission with limited // permissions. SecurityPermission limitedPermission = new SecurityPermission( SecurityPermissionFlag.Execution | SecurityPermissionFlag.RemotingConfiguration | SecurityPermissionFlag.ControlThread); ((NamedPermissionSet) (namedPermission.get_Current())). AddPermission(limitedPermission); break; } } try { // If you run this application twice, the // following instruction throws an exception // because the named permission set is already // present.You can remove the custom named // permission set using Caspole.exe or the // .NET Framework Configuration tool currentLevel.AddNamedPermissionSet (((NamedPermissionSet)(namedPermission .get_Current()))); SecurityManager.SavePolicy(); } catch (System.ArgumentException e) { Console.WriteLine(e.get_Message()); } Console.WriteLine(((NamedPermissionSet) (namedPermission.get_Current())).ToString()); break; } } } } } //CreateDepartmentPermission private static void DeleteCustomPermissions() { IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy(); // Move through the policy levels to the Machine policy level. while (policyEnumerator.MoveNext()) { PolicyLevel currentLevel = ((PolicyLevel)(policyEnumerator.get_Current())); if (currentLevel.get_Label().equalsIgnoreCase("Machine")) { try { currentLevel.RemoveNamedPermissionSet("MyCompany"); currentLevel.RemoveNamedPermissionSet("MyDepartment"); } catch (System.ArgumentException e) { // An exception is thrown if the named permission set // cannot be found. Console.WriteLine(e.get_Message()); } } } } //DeleteCustomPermissions // Demonstrate the use of ResolvePolicy. private static void CheckEvidence(Evidence evidence) { // Display the code groups to which the evidence belongs. Console.WriteLine("ResolvePolicy for the given evidence."); Console.WriteLine("Current evidence belongs to the following " + "code groups:"); IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy(); while (policyEnumerator.MoveNext()) { PolicyLevel currentLevel = ((PolicyLevel)(policyEnumerator.get_Current())); CodeGroup cg1 = currentLevel.ResolveMatchingCodeGroups(evidence); Console.WriteLine((currentLevel.get_Label() + " Level")); Console.WriteLine(("\tCodeGroup = " + cg1.get_Name())); Console.WriteLine(("StoreLocation = " + currentLevel.get_StoreLocation())); IEnumerator cgE1 = cg1.get_Children().GetEnumerator(); while (cgE1.MoveNext()) { Console.WriteLine(("\t\tGroup = " + ((CodeGroup)(cgE1.get_Current())).get_Name())); } } // Show how ResolvePolicy is used to determine the set of permissions // that would be granted by the security system to code, based on the // evidence and the permission sets requested. The permission sets // require Execute permission; allow optional Read access permission // to C:\temp; and deny the code permission to control security policy. Console.WriteLine(("\nCreate permission sets requiring Execute" + "permission, requesting optional " + "\nRead permission for " + "'C:\\temp',and dening permission to control policy.")); PermissionSet requiredSet = new PermissionSet(PermissionState.None); requiredSet.AddPermission(new SecurityPermission (SecurityPermissionFlag.Execution)); PermissionSet optionalSet = new PermissionSet(PermissionState.None); optionalSet.AddPermission(new FileIOPermission (FileIOPermissionAccess.Read, new System.String[] { "c:\\temp" })); PermissionSet deniedSet = new PermissionSet(PermissionState.None); deniedSet.AddPermission(new SecurityPermission (SecurityPermissionFlag.ControlPolicy)); // Show the granted permissions. Console.WriteLine("\nCurrent permissions granted:"); PermissionSet permsDenied = null; IEnumerator myEnumerator = SecurityManager.ResolvePolicy( evidence, requiredSet, optionalSet, deniedSet, permsDenied) .GetEnumerator(); while (myEnumerator.MoveNext()) { IPermission perm = (IPermission)myEnumerator.get_Current(); Console.WriteLine(perm.ToXml().ToString()); } // Show the denied permissions. Console.WriteLine("Current permissions denied:"); myEnumerator = permsDenied.GetEnumerator(); while (myEnumerator.MoveNext()) { IPermission perm = (IPermission)myEnumerator.get_Current(); Console.WriteLine(perm.ToXml().ToString()); } return; } //CheckEvidence } //SecurityManagerSample

System.Security.SecurityManager


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
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


SecurityManager プロパティ

名前 | 説明 | |
---|---|---|
![]() | CheckExecutionRights | コードを実行するために Execution が必要かどうかを示す値を取得または設定します。 |
![]() | SecurityEnabled | セキュリティが有効かどうかを示す値を取得または設定します。 |

SecurityManager メソッド

名前 | 説明 | |
---|---|---|
![]() | Equals | オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 ( Object から継承されます。) |
![]() | GetHashCode | 特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 ( Object から継承されます。) |
![]() | GetType | 現在のインスタンスの Type を取得します。 ( Object から継承されます。) |
![]() | GetZoneAndOrigin | 現在のアセンブリに付与されているゾーン ID アクセス許可セットと URL ID アクセス許可セットを取得します。 |
![]() | IsGranted | アクセス許可が呼び出し元に与えられているかどうかを判断します。 |
![]() | LoadPolicyLevelFromFile | 指定したファイルから PolicyLevel を読み込みます。 |
![]() | LoadPolicyLevelFromString | 指定した文字列から PolicyLevel を読み込みます。 |
![]() | PolicyHierarchy | コンピュータ ポリシーやユーザー ポリシーなどのレベルごとに、セキュリティ ポリシー階層にアクセスするための列挙子を提供します。 |
![]() | ReferenceEquals | 指定した複数の Object インスタンスが同一かどうかを判断します。 ( Object から継承されます。) |
![]() | ResolvePolicy | オーバーロードされます。 コードに与えるアクセス許可を決定します。 |
![]() | ResolvePolicyGroups | 提供された証拠と一致するコード グループのコレクションを取得します。 |
![]() | ResolveSystemPolicy | AppDomain レベルのポリシーを除いて、指定された証拠に基づいてコードに与えるアクセス許可を決定します。 |
![]() | SavePolicy | 変更されたセキュリティ ポリシーの状態を保存します。 |
![]() | SavePolicyLevel | LoadPolicyLevelFromFile で読み込んで、変更したセキュリティ ポリシー レベルを保存します。 |
![]() | ToString | 現在の Object を表す String を返します。 ( Object から継承されます。) |

SecurityManager メンバ
セキュリティ システムと対話するクラスに、主要なアクセス ポイントを提供します。このクラスは継承できません。
SecurityManager データ型で公開されるメンバを以下の表に示します。

名前 | 説明 | |
---|---|---|
![]() | CheckExecutionRights | コードを実行するために Execution が必要かどうかを示す値を取得または設定します。 |
![]() | SecurityEnabled | セキュリティが有効かどうかを示す値を取得または設定します。 |

名前 | 説明 | |
---|---|---|
![]() | Equals | オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 (Object から継承されます。) |
![]() | GetHashCode | 特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 (Object から継承されます。) |
![]() | GetType | 現在のインスタンスの Type を取得します。 (Object から継承されます。) |
![]() | GetZoneAndOrigin | 現在のアセンブリに付与されているゾーン ID アクセス許可セットと URL ID アクセス許可セットを取得します。 |
![]() | IsGranted | アクセス許可が呼び出し元に与えられているかどうかを判断します。 |
![]() | LoadPolicyLevelFromFile | 指定したファイルから PolicyLevel を読み込みます。 |
![]() | LoadPolicyLevelFromString | 指定した文字列から PolicyLevel を読み込みます。 |
![]() | PolicyHierarchy | コンピュータ ポリシーやユーザー ポリシーなどのレベルごとに、セキュリティ ポリシー階層にアクセスするための列挙子を提供します。 |
![]() | ReferenceEquals | 指定した複数の Object インスタンスが同一かどうかを判断します。 (Object から継承されます。) |
![]() | ResolvePolicy | オーバーロードされます。 コードに与えるアクセス許可を決定します。 |
![]() | ResolvePolicyGroups | 提供された証拠と一致するコード グループのコレクションを取得します。 |
![]() | ResolveSystemPolicy | AppDomain レベルのポリシーを除いて、指定された証拠に基づいてコードに与えるアクセス許可を決定します。 |
![]() | SavePolicy | 変更されたセキュリティ ポリシーの状態を保存します。 |
![]() | SavePolicyLevel | LoadPolicyLevelFromFile で読み込んで、変更したセキュリティ ポリシー レベルを保存します。 |
![]() | ToString | 現在の Object を表す String を返します。 (Object から継承されます。) |

- SecurityManagerのページへのリンク