This documentation is archived and is not being maintained.

SecurityManager Class

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)

'Declaration
<ComVisibleAttribute(True)> _
Public NotInheritable Class SecurityManager
'Usage
You do not need to declare an instance of a static class in order to access its members.

Security provides methods to access and manipulate the security policy configuration. You cannot create instances of 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 

System.Object
  System.Security.SecurityManager

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

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

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

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0
Show: