SecurityManager Class
.NET Framework 2.0
Provides the main access point for classes interacting with the security system. This class cannot be inherited.
Namespace: System.Security
Assembly: mscorlib (in mscorlib.dll)
Assembly: mscorlib (in mscorlib.dll)
'Declaration <ComVisibleAttribute(True)> _ Public NotInheritable Class SecurityManager 'Usage The members of a static class are accessed directly without an instance of the class.
/** @attribute ComVisibleAttribute(true) */ public final class SecurityManager
ComVisibleAttribute(true) public final class SecurityManager
The following example demonstrates the use of 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.
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
Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.
Community Additions
ADD
Show: