The System.Security.Permissions Namespace

The System.Security.Permissions namespace is the namespace used in code to establish and use permissions associated with objects, including the file system, environment variables, and the registry. The namespace controls access to both operating-system-level objects as well as code objects. In order to use this namespace in your project, you need to import it. Using this namespace gives you access to the CodeAccessPermission and PrincipalPermission classes for using role-based permissions and information supplied by identity permissions. CodeAccessPermission controls access to the operating-system-level objects. Role-based permissions and identity permissions grant access to objects based on the identity of the user of the program that is running (the user context).

Table 18.2 lists the members of the System.Security.Permissions namespace that apply to Windows application programming. While there is a description accompanying each member, those classes that end with Attribute, such as EnvironmentPermissionAttribute, are classes that enable you to modify the security level at which your code is allowed to interact with each respective object. These objects create a declarative model for setting security that can be leveraged across multiple different implementation models.

Table 18.2 Members of System.Security.Permissions

Class Description
CodeAccessSecurityAttribute Base class for code access security attribute classes.
DataProtectionPermission Controls access to the data protection APIs, T.
DataProtectionPermissionAttribute Allows declarative control of DataProtectionPermssion via code.
EnvironmentPermission Controls the capability to see and modify system and user environment variables.
EnvironmentPermissionAttribute Allows security actions for environment variables to be added via code.
FileDialogPermission Controls the capability to open files via a file dialogue.
FileDialogPermissionAttribute Allows security actions to be added for file dialogs via code.
FileIOPermission Controls the capability to read and write files in the file system.
FileIOPermissionAttribute Allows security actions to be added for file access attempts via code.
GacIdentityPermission Defines the identity permissions for files that come from the global assembly cache (GAC).
GacIdentityPermissionAttribute Allows security actions to be added for files that originate from the GAC.
HostProtectionAttribute Allows for the use of security actions to determine host protection requirements.
IsolatedStorageFilePermission Controls access to a private virtual file system within the isolated storage area of an application.
IsolatedStorageFilePermissionAttribute Allows security actions to be added for private virtual file systems via code.
IsolatedStoragePermission Controls access to the isolated storage area of an application.
IsolatedStoragePermissionAttribute Allows security actions to be added for the isolated storage area of an application.
KeyContainerPermission Controls access to key containers.
KeyContainerPermissionAccessEntry Defines the access rights for particular key containers.
KeyContainerPermissionAccess EntryCollection Represents a collection of KeyContainerPermission-AccessEntry objects.
KeyContainerPermissionAccess EntryEnumerator Represents the enumerators for the objects contained in the KeyContainerPermissionAccessEntryCollection object.
KeyContainerPermissionAttribute Allows security actions to be added for key containers.
MediaPermission The permission set associated with the capability to access audio, video, and images. WPF leverages this capability.
MediaPermissionAttribute Allows code to set permissions related to the MediaPermission set.
PermissionSetAttribute Allows security actions to be added for a permission set.
PrincipalPermission Controls the capability to verify the active principal.
PrincipalPermissionAttribute Allows verification of a specific user. Security principals are a user and role combination used to establish security identity.
PublisherIdentityPermission Allows access based on the identity of a software publisher.
PublisherIdentityPermissionAttribute Allows security to be defined for a software publisher.
ReflectionPermission Controls access to nonpublic members of a given type.
ReflectionPermissionAttribute Allows security to be defined for public and nonpublic members of a given type.
RegistryPermission Controls access to registry keys and values.
RegistryPermissionAttribute Allows security to be defined for the registry.
ResourcePermissionBase Controls the capability to work with the code access security permissions.
ResourcePermissionBaseEntry Allows you to define the smallest part of a code access security permission set.
SecurityAttribute Controls which security attributes are representing code; used to control security when creating an assembly.
SecurityPermission This collection is used in code to specify a set of permissions for which access will be defined.
SecurityPermissionAttribute Allows security actions for the security permission flags.
StorePermission Controls access to stores that contain X.509 certificates.
StorePermissionAttribute Allows security actions to be added for access stores that contain X.509 certificates.
StrongNameIdentityPermission Defines the permission level for creating strong names.
StrongNameIdentityPermissionAttribute Allows security to be defined on the StrongNameIdentityPermission set.
StrongNamePublicKeyBlob The public key information associated with a strong name.
TypeDescriptorPermission Permission set that controls partial-trust access to the TypeDescriptor class.
TypeDescriptorPermissionAttribute Allows security to be defined on the TypeDescriptorPermission set.
UIPermission Controls access to user interfaces and use of the Windows clipboard.
UIPermissionAttribute Allows security actions to be added for UI interfaces and the use of the clipboard.
UrlIdentityPermission Permission set associated with the identity and related permissions for the URL from which code originates.
UrlIdentityPermissionAttribute Allows security to be defined on the UrlIdentityPermission set.
WebBrowserPermission Controls the capability to create the WebBrowser control.
WebBrowserPermissionAttribute Allows security to be defined on the WebBrowser Permission set.
ZoneIdentityPermission Defines the identity permission for the zone from which code originates.
ZoneIdentityPermissionAttribute Allows security to be defined on the ZoneIdentity Permission set.

The default environment will provide a given level of access. It is not possible to grant access beyond this level via code access security; however, when working with these classes you can specify exactly what should or should not be available in a given situation. Additionally, these classes have been marked to prevent inheritance. It really wouldn't be a very secure system if you could inherit from one of these classes. Code could be written to override the associated security methods and grant unlimited permissions.

Table 18.2 also deals with security in regard to software publishers. A software publisher is a specific entity that is using a digital signature to identify itself in a Web-based scenario.

Code Access Permissions

Code access permissions are controlled through the CodeAccessPermission class within the System.Security namespace. The code access permissions are used extensively by the common language runtime (CLR) to manage and secure the operating environment.

The code access permissions grant and deny access to portions of the operating system such as the file system, but although your code can request permission changes, there is a key limit. Code using this API can request to reduce the rights of the user currently executing the code, but the API will not grant rights that a user does not have within his or her current context or based on those available from the CLR.

When code is downloaded from a website, and the user then attempts to run the code, the CLR can choose to limit the rights of that code given that it shouldn't by default be trusted. For example, requesting access to the system registry will be denied if the operating system does not trust that code. Thus, the primary use of code access security by application developers is to limit the permissions already available to a user given the current context of what the user is doing. Code access security leverages many of the same core security methods used across the various security categories, many of which are described in Table 18.3.

Table 18.3 Methods of CodeAccessPermission

Method Description
Assert Sets the permission to full access so that the specific resource can be accessed even if the caller hasn't been granted permission to access the resource.
Copy Copies a permission object.
Demand Returns an exception unless all callers in the call chain have been granted the permission to access the resource in a given manner.
Deny In prior versions of .NET you would use this to explicitly deny access. This will still work, but it's becoming obsolete and should be avoided.
Equals Determines whether a given object is the same instance of the current object.
FromXml Establishes a permission set given a specific XML encoding. This parameter that this method takes is an XML encoding.
Intersect Returns the permissions that two permission objects have in common.
IsSubsetOf Returns a result indicating whether the current permission object is a subset of a specified permission.
PermitOnly Specifies that only those rights within this permission set can be accessed even if the user of the assembly has been granted additional permission to the underlying objects. This is one of the more common permission levels when working with custom permission sets.
RevertAll Reverses all previous assert, deny, or permit-only methods.
RevertAssert Reverses all previous assert methods.
RevertDeny Reverses all previous deny methods.
RevertPermitOnly Reverses all previous permit-only methods.
Union Creates a permission that is the union of two permission objects.

Identity Permissions

Identity permissions are pieces of information, also called evidence, by which an assembly can be identified. Examples of the evidence would be the strong name of the assembly or the digital signature associated with the assembly.


Note
A strong name is a combination of the name of a program, its version number, and its associated cryptographic key and digital signature files.

Identity permissions are granted by the runtime based on information received from the trusted host, or the operating system's loader. Therefore, they are permissions that you don't specifically request. Identity permissions provide additional information to be used by the runtime. The identity information can take the form of a trusted host's URL or can be supplied via a digital signature, the application directory, or the strong name of the assembly. Identity permissions are similar to code access permissions, discussed in the preceding section. They derive from the same base class as the code access permissions.

Role-Based Permissions

Role-based permissions are permissions granted based on the user and the role that code is being called with. Users are authenticated within the operating system platform and hold a Security Identifier (SID) that is associated within a security context. The SID is associated with one or more roles or group memberships that are established within a security context. .NET supports those users and roles associated within a security context and has support for generic and custom users and roles through the concept of principals.

A principal is an object that holds the current caller's credentials. This includes the identity of the user. Principals come in two types: Windows principals and non-Windows principals. Windows-based principal objects are objects that store the Windows SID information regarding the current user context associated with the code that is calling into the module role-based permissions that are being used. Non-Windows principals are principal objects that are created programmatically via a custom login methodology and which are made available to the current thread.

Role-based permissions are not set against objects within your environment like code access permissions. They are checked within the context of the current user and user's role. The concepts of principals and the PrincipalPermission class are used to establish and check permissions. If a programmer passes the user and role information during a call as captured from a custom login, then the PrincipalPermission class can be used to verify this information as well.

The PrincipalPermission class does not grant access to objects, but has methods that determine whether a caller has been given permissions according to the current permission object through the Demand method. If a security exception is generated, then the user does not have sufficient permission. As an example of how you might use these methods, the following code snippet captures the current Windows principal information and displays it on the screen in a text box. It is included as part of the ProVB2012_Security project, which has the same basic structure as the ProVB_VS2012 project introduced in Chapter 1. Each element of the principal information could be used in a program to validate against, and thus restrict, code execution based on the values in the principal information. The following code example inserts Imports System.Security.Principal and Imports System.Security.Permissions lines at the top of MainWindow.xaml.vb so you can directly reference identity and principal objects without full namespace qualifiers:

Imports System.Security.Principal
Imports System.Security.Permissions
        
    '<PrincipalPermissionAttribute(SecurityAction.Demand, 
                                 Name:="WSheldon", Role:="Users")> _
    Private Sub DisplayPrincipalIdentity()
        ' The attribute above can be used to check security declaratively
        ' similar to how you would check using WPF or Silverlight.
        ' The code below uses imperative commands to get security information.
        Dim objIdentity As WindowsIdentity = WindowsIdentity.GetCurrent()
        TextBoxResult.Text = "User Name: " & objIdentity.Name &
             Environment.NewLine
        TextBoxResult.Text &= "Is Guest: " & objIdentity.IsGuest.ToString() _
             & Environment.NewLine
        TextBoxResult.Text &= "Is Authenticated: " _
          & objIdentity.IsAuthenticated.ToString() & Environment.NewLine
    Dim objPrincipal As New Security.Principal.WindowsPrincipal(objIdentity)
    ' Determine if the user is part of an authorized group.
    TextBoxResult.Text &= "Is in Role Users? " & objPrincipal.IsInRole("Users") _
         & Environment.NewLine
    TextBoxResult.Text &= "Is in Role Administrators? " _
         & objPrincipal.IsInRole("Administrators")
End Sub

This code illustrates a few of the properties that could be used to validate against when a caller wants to run your code. The attribute at the top of this is commented out at this point by design. It represents a declarative security check similar to what you would use from the XAML in a WPF or Silverlight project. First, however, let's examine this code being run, as shown in Figure 18.2.

Figure 18.2 Details of the current user

18.2

It starts by retrieving the user name of the currently authenticated Windows principal. Pay attention to the fact that this is a fully qualified username with the machine name included. It then uses the identity checks to see if the current identity is the Guest account, and ensures that the user was authenticated.

At this point the snippet creates a new WindowsPrincipal based on the current user's identity. This object allows you to query to see if the current user is in a role. In this case, our account is in the role of a user as a member of the Users security group, but is not in the role of an administrator even though it is part of the Administrators group.

Roles are typically defined via security groups, but it is important to not say that this method allowed you to determine if a user were in a given group. That's because under Windows Vista and Windows 7, the operating system keeps a user from running in the Administrator role even if they are part of the Administrators group. Thus, the check for whether the code is running in the role Administrators returns false—even though our WSheldon account is in fact a member of the Administrators group on this machine. Only if the user chooses to have their permission elevated will this query return true.


Note
The issue of permission elevation in relation to User Access Control (UAC) and the fact that the WSheldon account is in fact an Administrator on the system is discussed later in this chapter.

Now uncomment the attribute line that precedes this method. Notice that it is making a Demand security query and passing a user name, and a role name as part of this name. Because these are named optional parameters, the code could in theory check only for a role, which is a much more usable check in a real-world application. However, in this case use only a name and do not include the machine as part of the full user name. As a result, when ButtonTest is clicked this declarative check fails and the error shown in Figure 18.3 is displayed.

Figure 18.3 Security exception for nonexistent user running in the debugger

18.3

This illustrates how the same objects that have been available since the early versions of .NET are still used within XAML to enable the same level of security to declarative applications. The principal and identity objects are used in verifying the identity or aspects of the identity of the caller attempting to execute your code. Based on this information, your application can either lock down system resources or adjust the options available to users within your custom application. The Identity and Principal objects make it possible to have your application respond as changes to user roles occur within Active Directory. Note you'll want to comment this line back out so that this error isn't present as you work with the sample application later in this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset