Lesson 3: Securing Your Application

Lesson 3: Securing Your Application

When writing an application, it is important to protect your code. Hackers and malicious users cause significant damage to businesses every year. It is your responsibility to ensure that your code is secure from attack. In addition, sensitive information, such as company databases and personal information, must be kept secure from unauthorized users. The .NET Framework provides ample tools to secure your applications from unauthorized use. In this lesson, you will learn how to use imperative and declarative security checks to secure your application. You will learn how to protect against unauthorized users, unauthorized code groups, and unidentified code. You will also learn to implement custom security checks.

After this lesson, you will be able to

  • Explain what a permission is and how it is used

  • Explain the difference between declarative and imperative security

  • Explain how to configure role-based security

  • Explain how to configure code access security

Estimated lesson time: 40 minutes

Security is about protection. You can use the security features provided by the .NET Framework to protect your code from unauthorized users and to protect the system from unauthorized use of your code. The system administrator sets the overall system security policy. The administrator decides what kind of code a machine will be allowed to execute, whether a particular assembly is trusted, and if so, what kind of trust is extended to the assembly. The security policy set by the system administrator cannot be overridden by your code: it is the highest level of security on a given machine.

Security further protects your application within the bounds set by the system administrator. You can use role-based security to authorize users and code access security to protect your code from misuse by unauthorized callers. Security authorizations can be either imperative or declarative. In imperative security, permission to execute is demanded at run time. Declarative security, on the other hand, specifies permissions required by the assembly in the assembly manifest. If the required permissions are in conflict with the security policy, the assembly is not allowed to execute. Permission objects are the central objects in code security.

NOTE
Unless otherwise specified, all of the code examples in this lesson use Imports System.Security.Permissions for Visual Basic .NET or using System.Security.Permissions for Visual C#.

Permissions

A permission is a code object that represents a user, an identity, or a code resource. Permission objects are used for a variety of security-related functions, such as to represent security clearances and to enforce security policy.

The IPermission Interface

All security permissions in the .NET Framework must implement the IPermission interface, which provides a common level of functionality for all security objects, though you will rarely, if ever need to implement this interface as the security permissions provided by the .NET Framework have already implemented it. Nevertheless, an examination of the methods described by the IPermission interface give insight into how the objects it implements work. The member methods of the IPermission interface are described in Table 9.2.

Table 9-2. Methods of the IPermission Interface

Method

Description

Copy

Creates and returns an identical copy of the permission

Demand

Walks the call stack and throws a SecurityException if any callers in the stack lack the permission

Intersect

Creates and returns a permission that is the intersection of two permissions

IsSubsetOf

Determines whether the current permission is a subset of a specified permission

Union

Creates a permission that is the union of the current permission and the specified permission

Permissions can use the Demand method to enforce security. The method requires that callers must have been granted the appropriate permission to access the protected code. If the appropriate permission has not been granted, a SecurityException is thrown. The Copy method creates an identical copy of the permission, and the IsSubsetOf method determines whether the current permission is a subset of a specified permission. The Union and Intersect methods are used to create a new permission from two specified permissions of the same type. The permission returned by a Union method represents the sum of the two permissions specified, and the permission returned by the Intersect method represents only those resources that both permissions have in common. In the following sections, you will learn how to use these methods as implemented in the Permission objects provided by the .NET Framework.

Configuring Role-Based Authorization

Role-based security is security that grants or denies access to an application or resource based on the identity and role of the user. For example, suppose you have an application that is used by both managers and clerks. You might want to allow everyone to access some parts of the application, but make sensitive parts of the application, such as payroll or personal information, available to managers only. Role-based authorization implements this kind of security.

The Principal

In the .NET Framework, authenticated users are represented by a Principal object. The Principal object contains information about a user s identity and role, and can be used to validate identity against a PrincipalPermission object, which is used to protect sensitive parts of an application from unauthenticated users.

When writing a Windows application, you can use the built-in security to verify the identity and role of the current user. You can associate the WindowsPrincipal object that represents the current user with your application by setting the principal policy for the current application domain as follows:

Visual Basic .NET

AppDomain.CurrentDomain.SetPrincipalPolicy _ (PrincipalPolicy.WindowsPrincipal) Visual C# AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.WindowsPrincipal);

The WindowsPrincipal contains a reference to the WindowsIdentity object that represents the current user. You can obtain information about your current user by accessing the WindowsIdentity exposed by the current WindowsPrincipal. Because the WindowsPrincipal returns the Identity property as an IIdentity interface, you must explicitly convert it to a WindowsIdentity object. For example:

Visual Basic .NET

' This example assumes that the Principal policy has been set to ' WindowsPrincipal. Dim myPrincipal As WindowsPrincipal ' Gets a reference to the current WindowsPrincipal myPrincipal = CType(Threading.Thread.CurrentPrincipal, _ WindowsPrincipal) Dim myIdentity As WindowsIdentity ' Gets the WindowsIdentity of the current principal myIdentity = CType(myPrincipal.Identity, WindowsIdentity) ' Displays the username of the current user MessageBox.Show(myIdentity.Name)

Visual C#

// This example assumes that the Principal policy has been set to // WindowsPrincipal WindowsPrincipal myPrincipal; // Gets a reference to the current WindowsPrincipal myPrincipal = (WindowsPrincipal) System.Threading.Thread.CurrentPrincipal; WindowsIdentity myIdentity; // Gets the WindowsIdentity of the current principal myIdentity = (WindowsIdentity)myPrincipal.Identity; // Displays the username of the current user MessageBox.Show(myIdentity.Name);

Imperative Role-Based Security

You can use a PrincipalPermission object to perform imperative security checks. A PrincipalPermission object can specify an identity and a role, and can demand that the current user match the name and role specified by the PrincipalPermission. The Demand method checks the current Principal against the name and role specified in the PrincipalPermission. The following code example demonstrates how to create a PrincipalPermission and use it to validate the current user:

Visual Basic .NET

' The PrincipalPermission constructor requires the name and role ' as strings Dim myPermission As New PrincipalPermission("Megan", "Manager") ' Demands that the CurrentPrincipal be named Megan in the role of ' Manager myPermission.Demand()

Visual C#

// The PrincipalPermission constructor requires the name and role // as strings PrincipalPermission myPermission = new PrincipalPermission("Megan",  "Manager"); // Demands that the CurrentPrincipal be named Megan in the role of // Manager myPermission.Demand();

You can use the Union method to create a permission that combines two permissions. For example, the following code example creates a new permission that combines two others:

Visual Basic .NET

Dim Permission1 As New PrincipalPermission("Megan", "Manager") Dim Permission2 As New PrincipalPermission("Ann", "Group Manager") Dim Permission3 As PrincipalPermission ' Creates a union of Permission1 and Permission2 Permission3 = Permission2.Union(Permission1) ' Requires that either Ann:Group Manager, or Megan:Manager be the ' current Principal to access this code Permission3.Demand()

Visual C#

PrincipalPermission Permission1 = new PrincipalPermission("Megan",  "Manager"); PrincipalPermission Permission2 = new PrincipalPermission("Ann",  "Group Manager"); PrincipalPermission Permission3; // Creates a union of Permission1 and Permission2 Permission3 = (PrincipalPermission)Permission2.Union(Permission1); // Requires that either Ann:Group Manager, or Megan:Manager be the // current Principal to access this code Permission3.Demand();

When creating a PrincipalPermission object, you can specify Nothing (null) for either the name or the role. This allows you to create a permission that validates only the name or only the role of the permission. For example, the following lines of code create a PrincipalPermission object that validates only the role of the current Principal:

Visual Basic .NET

' Creates a permission that checks only if you are a manager Dim myPermission As New PrincipalPermission(Nothing, "Manager")

Visual C#

// Creates a permission that checks only if you are a manager PrincipalPermission myPermission = new PrincipalPermission(null, "Manager");

You can use the Intersect method to create a new permission that encompasses only the intersection of two other permissions, as shown in the following example:

Visual Basic .NET

Dim Permission1 As New PrincipalPermission(Nothing, "Manager") Dim Permission2 As New PrincipalPermission("Megan", Nothing) Dim Permission3 As PrincipalPermission ' Creates a new permission that represents the intersection of ' Permission1 and Permission2 Permission3 = Permission2.Intersect(Permission1) ' Requires that the Principal who accesses this code be named Megan ' in the role of Manager Permission3.Demand()

Visual C#

PrincipalPermission Permission1 = new PrincipalPermission(null,  "Manager"); PrincipalPermission Permission2 = new PrincipalPermission("Megan", null); PrincipalPermission Permission3; // Creates a new permission that represents the intersection of // Permission1 and Permission2 Permission3 = (PrincipalPermission)Permission2.Intersect(Permission1); // Requires that the Principal who accesses this code be named Megan // in the role of Manager Permission3.Demand();

You can also use PrincipalPermissions to authenticate membership in the Windows built-in roles such as Administrators. When specifying a built-in role, you must precede it with BUILTIN\ as follows:

Visual Basic .NET

Dim myPermission as New PrincipalPermission("Rob", _  "BUILTIN\Administrators")

Visual C#

// Two backslashes (\\) are required for C# because a single // backslash specifies an escape sequence. PrincipalPermission myPermission = new PrincipalPermission("Rob", "BUILTIN\\Administrators");

Declarative Role-Based Security

Every Permission object has a corresponding attribute. These attributes can be attached to classes and members and used to control access to those classes or members. Attributes play a key role in declarative security. In the declarative security model, permission attributes are attached to the members they protect to specify the level of access. Additionally, the attributes are emitted into the type metadata so that the metadata for the assembly can be examined. The administrator can make a decision to allow the assembly to execute or not based on that metadata. Each permission attribute requires a SecurityAction in the constructor that indicates the action to be taken. In role-based security, this is usually a Demand action. You can set properties for permission attributes at creation by using the := operator (Visual Basic .NET) or the = operator (Visual C#). The following code example demonstrates how to implement declarative role-based security for a method named myMethod:

Visual Basic .NET

<PrincipalPermission(SecurityAction.Demand, Name:="Joe", _ Role:="Clerk")> Public Sub MyMethod() ' Method implementation omitted End Sub

Visual C#

[PrincipalPermission(SecurityAction.Demand, Name="Joe", Role="Clerk")] public void myMethod() { // Method implementation omitted }

Configuring Code Access Security

Code access security prevents your code from being misused by unauthorized callers. You can also use code access security to communicate security requirements to the system administrator.

Like role-based security, code access security is based on permissions. In role-based security, a permission represents the identity or role of the user. In code access security, a permission represents system resources and control access to those resources. A good example is the file system. If you have an application that writes to files, you should ensure that unauthorized callers are unable to use that resource to maliciously inflict damage to your file structure. A FileIOPermission object protects any code that accesses the file system by ensuring that all callers have the appropriate level of permission.

Code Access Permissions

Each code access permission represents a particular resource. Most permissions are found in the System.Security namespace, but some specialized permissions are supplied by other namespaces. Table 9.3 lists and briefly describes some of the code access permissions supplied by the .NET Framework. This list is by no means exhaustive, but provides a sampling of the kinds of permissions you can use to control security in your applications.

Table 9-3. Code Access Permissions

Permission

Description

DirectoryServicesPermission

Controls the ability to access Active Directory

EnvironmentPermission

Controls the ability to read and set environment variables

EventLogPermission

Controls the ability to read and write to event logs

FileDialogPermission

Controls the ability to access files or folders through a file dialog box

FileIOPermission

Controls the ability to create, read, and write to the file system

OleDbPermission

Controls the ability to access an OleDb database

PrintingPermission

Controls access to the printer

ReflectionPermission

Controls the ability to use the System.Reflection classes to discover information about types at run time

RegistryPermission

Controls the ability to read and write to the registry

SecurityPermission

Controls several rights, including the ability to execute code, manipulate threads and principals, and call into unmanaged code

SQLClientPermission

Controls the ability to access a Microsoft SQL Server database

UIPermission

Controls the ability to access the user interface

Creating Code Access Permissions

Every code access permission exposes a different set of overloaded constructors that allow you to specifically configure the resources that the code access permission protects. You can create a permission that represents access to all of the resources it protects or a subset based on the parameters supplied at instantiation.

You can create a permission that provides unrestricted access to the resource it represents by using the PermissionState.Unrestricted flag. You can also use the PermissionState.None flag to create a permission that represents no access. Examples of both follow:

Visual Basic .NET

' Represents unrestricted access to Reflection resources Dim myPermission As New _ ReflectionPermission(PermissionState.Unrestricted) ' Represents completely restricted access to UI resources Dim anotherPermission As New _ UIPermission(PermissionState.None)

Visual C#

// Represents unrestricted access to Reflection resources ReflectionPermission myPermission = new ReflectionPermission(PermissionState.Unrestricted); // Represents completely restricted access to UI resources UIPermission anotherPermission = new UIPermission(PermissionState.None);

Each permission also exposes additional constructors that allow you to specifically configure the permission. Although it is beyond the scope of this book to detail each constructor, you should be aware of the level of fine-tuning that each permission can provide. The following code example demonstrates how to create a permission that represents the right to write to only a single file in the file system:

Visual Basic .NET

Dim myPermission As New _ FileIOPermission(FileIOPermissionAccess.Write, "C:\myFile.txt")

Visual C#

FileIOPermission myPermission = new FileIOPermission(FileIOPermissionAccess.Write, "C:\\myFile.txt");

CodeAccessPermission Members

All code access permissions inherit from the base class CodeAccessPermission. As such, they all expose a similar set of methods that can be used to validate and enforce security policy. Table 9.4 lists and describes some of the common members that are important for enforcing security policy. The next section discusses how to use these methods to enforce code access security.

Table 9-4. CodeAccessPermission Methods

Method

Description

Assert

Asserts that the code calling this method can access the resource represented by the permission even if callers higher in the call stack do not have that permission

Demand

Requires that all callers higher in the call stack have permission to access the resource represented by this permission

Deny

Denies code that calls this method permission to access the resource represented by this permission

PermitOnly

Denies code that calls this method permission to access the resource represented by this permission except for the subset of that resource that the permission instance specifies.

RevertAll

Removes all previous Assert, Deny, and PermitOnly overrides

RevertAssert

Removes all previous Assert overrides

RevertDeny

Removes all previous Deny overrides

RevertPermitOnly

Removes all previous PermitOnly overrides

Imperative Code Access Security

Like role-based security, code access security can be used imperatively or declaratively. When using imperative code access security, security is enforced at run time.

The Demand method is the primary method for enforcing code access security. Permission to access protected resources is granted by the common language run time, which checks the security policy for the assembly set by the system administrator. When the Demand method of a permission object is called, it walks the call stack to verify that each and every caller higher in the stack has been granted permission to access the resource represented by the permission. Thus, a trusted assembly might have a method that calls another method protected by a code access permission. If the call to the second method originates in a trusted assembly, the call will succeed and the protected resource can be used. However, if an untrusted assembly calls the method in the trusted assembly, which then calls the protected method, the Permission object will walk the stack to verify that every caller has permission to access this resource. Because the untrusted assembly does not have the appropriate permission, the call will fail.

The following code example demonstrates how to use the Demand method:

Visual Basic .NET

' Creates a permission object that represents unrestricted ' access to the file system Dim myPermission As New _ FileIOPermission(PermissionState.Unrestricted) ' Demands that all callers to this code have permission for ' unrestricted access to the file system myPermission.Demand()

Visual C#

// Creates a permission object that represents unrestricted // access to the file system FileIOPermission myPermission = new FileIOPermission(PermissionState.Unrestricted); // Demands that all callers to this code have permission for // unrestricted access to the file system myPermission.Demand();

You can also use code access permissions to protect code above and beyond the security policy. The Deny method denies callers to your code permission to access the protected resource even if they have been granted that permission by the common language runtime. For example:

Visual Basic .NET

' Creates a permission object that represents unrestricted ' access to the file system Dim myPermission As New _ FileIOPermission(PermissionState.Unrestricted) ' Denies access to the file system to this method myPermission.Deny()

Visual C#

// Creates a permission object that represents unrestricted // access to the file system FileIOPermission myPermission = new FileIOPermission(PermissionState.Unrestricted); // Denies access to the file system to this method myPermission.Deny();

Similar to the Deny method is the PermitOnly method. This method allows you to deny access to the resource except for the resource explicitly represented by the permission. For example, suppose you create a FileIOPermission object that only represents the ability to write to a particular file. Calling the PermitOnly method of this permission will cause any attempt to access the file system to fail unless it is an attempt to write to that particular file. The following code example demonstrates how to use the PermitOnly method:

Visual Basic .NET

' Creates a permission object that represents access to a ' specific file Dim myPermission As New _ FileIOPermission(FileIOPermissionAccess.Write, "C:\myFile.txt") ' Permits only access to this file, and denies all other ' permission myPermission.PermitOnly()

Visual C#

// Creates a permission object that represents access to a // specific file FileIOPermission myPermission = new FileIOPermission(FileIOPermissionAccess.Write, "C:\\myFile.txt"); // Permits only access to this file, and denies all other // permission myPermission.PermitOnly();

The Assert method is used to declare that a method has permission to access the specified resource. This causes any Demand stack walks to cease checking for permission from callers higher in the stack. Thus, if an untrusted assembly calls a method containing an Assert call, which then attempts to call a method protected by a Demand, the Demand will be satisfied by the Assert and will allow the call to proceed even though it originated in an untrusted assembly. However, using Assert calls is risky because they can allow untrusted code to access protected resources. Therefore, you should be careful when making Assert calls. You should also note that Assert calls cannot be used to bypass the system security policy. An assembly must be given the appropriate permission to make Assert calls for them to be valid. The following code example demonstrates how to Assert a permission:

Visual Basic .NET

' Creates a permission object that represents unrestricted ' access to the file system Dim myPermission As New _ FileIOPermission(PermissionState.Unrestricted) ' Asserts permission to access the file system myPermission.Assert()

Visual C#

// Creates a permission object that represents unrestricted // access to the file system FileIOPermission myPermission = new FileIOPermission(PermissionState.Unrestricted); // Asserts permission to access the file system myPermission.Assert();

You can use the Revert methods provided by each permission class to remove any previous Deny, Assert, or PermitOnly calls. The Revert methods are static methods belonging to the class as opposed to any one instance of the class, and thus affect all objects of that type. The following code example shows how to use the Revert methods:

Visual Basic .NET

' Reverts all ReflectionPermission overrides ReflectionPermission.RevertAll() ' Reverts EnvironmentPermission Deny calls EnvironmentPermission.RevertDeny() ' Reverts FileIOPermission Assert calls FileIOPermission.RevertAssert() ' Reverts MessageQueuePermission PermitOnly calls MessageQueuePermission.RevertPermitOnly()

Visual C#

// Reverts all ReflectionPermission overrides ReflectionPermission.RevertAll(); // Reverts EnvironmentPermission Deny calls EnvironmentPermission.RevertDeny(); // Reverts FileIOPermission Assert calls FileIOPermission.RevertAssert(); // Reverts MessageQueuePermission PermitOnly calls MessageQueuePermission.RevertPermitOnly();

Declarative Code Access Security

You can use declarative code access security instead of imperative code access security to configure access to system resources. As in role-based security, each code access permission has a corresponding attribute that can be attached to methods or classes to specify security actions. Additionally, you can use declarative code access security to request permissions for the entire assembly.

You can attach a code access permission attribute to a class or method in the same way you specify a role-based security attribute. However, instead of specifying a role, you must specify the SecurityAction represented by the attribute. The following code example demonstrates how to deny the FileIOPermission to a class using declarative security:

Visual Basic .NET

<FileIOPermission(SecurityAction.Deny)>Public Class aClass ' Class implementation omitted End Class

Visual C#

[FileIOPermission(SecurityAction.Deny)] public class aClass { // Class implementation omitted }

The SecurityAction.Demand, SecurityAction.Deny, SecurityAction.Assert, and SecurityAction.PermitOnly flags respectively correspond to the Demand, Deny, Assert, and PermitOnly methods of the relevant permission. There are additional security actions that can be applied to classes and methods with declarative security. If you specify SecurityAction.LinkDemand, you only require the immediate caller to this class or method to have been granted the appropriate permission. Specifying SecurityAction.InheritanceDemand requires that any derived class inheriting this class or overriding this method must have the appropriate permission.

You can also use permission attributes to make security requests for the entire assembly. There are three SecurityAction flags that can be specified in an assembly-wide directive. When SecurityAction.RequestMinimum is specified, it makes a request to the common language runtime to be granted the requested permission. If the requested permission is not granted by the security policy, the assembly will not execute. A SecurityAction.RequestOptional is similar, but the assembly will still run even if the requested permission is not granted. Specifying SecurityAction.RequestRefuse requests that the assembly be denied the specified permission. You must use the Assembly (assembly) directive when specifying these actions, as shown in the following example:

Visual Basic .NET

<Assembly: FileIOPermission(SecurityAction.RequestMinimum)>

Visual C#

[assembly: FileIOPermission(SecurityAction.RequestMinimum)]

As in role-based declarative security, you can set any properties for the permission attribute upon initialization by using the := operator (Visual Basic .NET) or the = operator (Visual C#). The following code example demonstrates how to create an Assert for permission to access a single file using declarative security:

Visual Basic .NET

<FileIOPermission(SecurityAction.Assert, _ Write:="C:\myFile.txt")>Public Sub WriteFile() ' Method implementation omitted End Sub

Visual C#

[FileIOPermission(SecurityAction.Assert, Write="C:\\myFile.txt")] public void WriteFile() { // Method implementation omitted }

Using Exception Handling with Imperative Security

Your applications should anticipate possible error conditions and appropriately handle any exceptions that might be thrown. Because a security failure will throw a SecurityException, imperative security demands should be wrapped in appropriate exception handling that allows your application to degrade gracefully if security permissions are not granted. You must decide on the appropriate course of action when a requested permission is not granted. An appropriate course of action is to allow the user to save data and then end the program, or else to proceed with program execution, bypassing the protected resource. Whatever route you decide for your application, good programming practice directs that foreseeable exceptions should never go unhandled.

Configuring Network and Machine Code Access Security Policy

Code access security is enforced by the machine s code access security policy. This policy consists of a hierarchical set of policy levels and code groups, and it assigns code access security permissions to assemblies based on where the code originated from as well as any evidence that it is trustworthy. Policy levels represent levels of code execution within which permissions can be granted, while code groups represent code with common characteristics that can be grouped on the basis of permissions granted to them.

Policy Levels

The .NET Framework provides four security policy levels. They are described in Table 9.5.

Table 9-5. Security Policy Levels

Policy Level

Description

Enterprise

The Enterprise policy applies to every computer on the network. It can be changed only by a domain or network administrator. Any managed code that is executed in a network or distributed context is subject to the Enterprise security policy, as well as the Machine and User policies.

Machine

The Machine policy applies to the individual computer. It can be changed by a domain or machine administrator. The machine policy contains most of the default security policy for a computer. All managed code executed on the local computer is subject to the Machine policy.

User

The User policy applies to processes associated with the current user, and can be modified by that user or an administrator. All managed code executed in processes associated with the current user is subject to the User policy.

Application Domain

The Application Domain policy applies to managed code executed in the host s application domain.

These policy levels are arranged hierarchically, with Enterprise level at the top, then Machine, User, and Application Domain. Permissions granted at a higher level, cannot be increased by security policy at a lower level, but can be further restricted. Thus, for example, if Machine policy grants permission to access the file system, but not the registry, User policy cannot allow access to the registry, but it can further restrict access to the file system. Granting and denying permissions at the security policy level is accomplished through the administration of that policy s code groups and their associated permission sets.

Code Groups

Each policy level has its own associated set of code groups. A code group is a logical set of code with similar characteristics. Each code group can encompass any number of assemblies, and an assembly can belong to multiple code groups. Each code group has its own set of permissions that are granted and denied to assemblies affected by that code group.

Assemblies are placed in code groups upon the examination of evidence. Evidence is information about an assembly collected by the run time, including the Strong Name, the URL that the code originated from, the publisher of the code, and security certificates. The .NET Framework provides the code groups and associated permission sets listed in Table 9.6.

Table 9-6. Code Groups Provided by the .NET Framework

Code Group

Membership Criteria

All code

All code is included in this code group.

Application Directory

All code installed in the application directory represented by this code group.

Cryptographic Hash

Code that has an MD5, SHA1, or another cryptographic hash.

Software Publisher

All code signed with the public key of a valid Authenticode signature.

Site Membership

All code that originates from a particular HTTP, HTTPS, or FTP site.

Strong Name

All code that has a cryptographically strong name.

URL

All code that originates from a particular URL.

Zone

All code that originates from the zone represented by this code group.

Note that most of these code groups usually have multiple instances. For example, there is an Application Directory code group for each directory that has an installed managed code assembly. All code groups and their associated permissions can be administered through the Code Access Security Policy utility (caspol.exe).

The Code Access Security Policy Utility (caspol.exe)

Caspol.exe is a command-line utility used to view and modify code groups. To run caspol.exe, open the command prompt then type caspol followed by any appropriate flags. If you type caspol without any flags you will view information describing how to use the utility.

NOTE
Using Caspol from the command line requires a valid path to the utility. To ensure that the path to the utility is set, you should use the Visual Studio .NET command prompt accessed from the Visual Studio .NET entry in your operating system s Start menu.

Viewing Code Groups and Permission Sets

You can view the code groups present on your machine by using the -listgroups flag, as shown in the following code example (typed in the Command Prompt window):

caspol.exe listgroups

This command writes a list of all the code groups in the current security policy level to the console output. You can also use the -all flag if you want to view all code groups in all security policy levels, as shown in the example that follows:

caspol.exe all listgroups

Note that each code group can be expressed numerically when configuring security policy for your machine. For example, All Code is group 1. Similarly, you can view the named permission sets on your machine by using the -lp flag:

caspol.exe lp

Adding, Removing, and Changing Security Policy

You can use caspol to add, remove, and alter the security policy of code groups, but this powerful tool should be used with caution. Incorrect settings can allow malicious users to attack and exploit your machine. You can add a new code group by using the -addgroup flag. In this following example, the website www.microsoft.com is added as a code group subordinate to code group 1. The new code group is created with Full Trust, meaning that any code downloaded from www.microsoft.com will be granted full security permissions, as shown here:

caspol.exe addgroup 1 site www.microsoft.com FullTrust

You can view the newly created code group with the -listgroups flag.

NOTE
Each time you use caspol to alter your computer s security policy, you will be prompted to confirm that is what you want to do. Altering security policy should be undertaken with great care.

After creating a new code group, you might decide to change the policy of the group. For example, you might reconsider granting Full Trust to a code group or want to increase permissions of another. You can use the -chggroup flag to alter permissions. The following code example changes the permission set associated with the code group created in the last example to the LocalIntranet permission set:

caspol.exe chggroup 1.6 LocalIntranet

You can also remove entire groups with the -remgroup flag, as shown:

caspol.exe remgroup 1.6

Lesson Summary

  • There are two basic types of code security: role-based security, which authenticates users and roles, and code access security, which protects system resources from unauthorized calls.

  • The ability to access code and system resources is represented by Permission objects. All Permission objects implement the IPermission interface, which provides a basic set of functionality required by all Permission objects.

  • Role-based authorization verifies the role and/or identity of the current Principal object. You can use the built-in Windows authentication to validate against the WindowsPrincipal by setting the PrincipalPolicy of the current AppDomain.

  • Access to system resources is represented by code access Permission objects. Code access permissions can represent all access to the specified resource or a specific subset of that resource.

  • Security checks can be applied imperatively or declaratively. Declarative security is applied by associating attribute declarations that specify a security action with classes or methods. Imperative security is applied by calling the appropriate methods of a Permission object that represents the Principal (for role-based security) or system resource (for code access security).

  • You can use declarative security to request permissions for the entire assembly. You can use the Assembly (assembly) directive to make a declarative security request for the entire assembly.

  • Code groups represent collections of code with common characteristics, such has a URL of origin or certificate credentials. Each code group has an associated set of permissions that it grants to the code that is a member of that group. Code that exists on a particular machine can belong to many code groups at once and is subject to the security policy of each of those code groups.

  • Caspol.exe is a command-line utility that can be used to view and alter code access security policy on a machine.



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[.  .. ]0-316
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[. .. ]0-316
ISBN: 735619263
EAN: N/A
Year: 2003
Pages: 110

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net