Application Security for Developers

Todo el mundo ha escuchado que usted no debe iniciar sesión en el equipo como administrador. La razón no es porque no confía en si mismo , es porque no confía en las aplicaciones que se ejecutan. Cuando ejecuta una aplicación no administrada en Microsoft Windows Server 2003, Microsoft Windows XP y versiones anteriores de Windows, aquel codigo obtiene todos los privilegios que tu cuenta de usuario tiene. Si ejecuta accidentalmente un virus o un caballo de Troya, la aplicación puede hacer cualquier cosa que su cuenta de usuario tiene permisos para hacer. Por lo tanto está obligado a iniciar sesión con privilegios mínimos para restringir los permisos de la aplicación.

Code access security (CAS), a concept that the .NET Framework introduced to Windows, enables you to control the permissions that individual applications have. If a friend sends you a new .NET Framework text editor, you can restrict it to opening a window and prompting you to open and save files—and nothing else. The text edited wouldn’t be able to send e-mails, upload files to a Web site, or create files, even if you are logged on as an Administrator.

CAS enables users to restrict on a very granular level what managed code can do. As a developer, you must understand how to create applications that work even when some permissions are restricted. You can also use CAS to improve your application’s security by restricting which callers can use your code and forcibly limiting your application to a restricted permission set.

Understanding Code Access Security

If you have worked with previous versions of the .NET Framework, you might already be familiar with code access security (CAS) concepts. If you have been a Microsoft Windows developer but haven’t previously used the .NET Framework, using CAS requires you to understand completely novel security concepts. This lesson describes the concept behind CAS and each of the components that the .NET Framework uses to implement CAS.

What Is Code Access Security?

Code access security (CAS) is a security system that allows administrators and developers to control application authorization similar to the way they have always been able to authorize users. With CAS, you can allow one application to read and write to the registry, while restricting access for a different application. You can control authorization for most of the same resources you’ve always been able to restrict using the operating system’s role-based security (RBS), including the following:

■ The file system

■ The registry

■ Printers

■ The event logs

You can also restrict resources that you can’t control using RBS. For example, you can control whether a particular application can send Web requests to the Internet or whether an application can make DNS requests. These are the types of requests that malicious applications are likely to make to abuse a user’s privacy, so it makes sense that CAS allows you to restrict those permissions.

Unfortunately, CAS can be applied only to managed applications that use the .NET Framework runtime. Unmanaged applications run without any CAS restrictions andare limited only by the operating system’s RBS. If CAS is used to restrict the permissions of an assembly, the assembly is considered partially trusted. Partially trusted assemblies must undergo CAS permission checks each time they access a protected resource. Some assemblies are exempt from CAS checks and are considered fully trusted. Fully trusted assemblies, like unmanaged code, can access any system resource that the user has permissions to access.

Elements of Code Access Security

Every security system needs a way to identify users and determine what a user can and can’t do, and CAS is no exception. However, because CAS identifies and assigns permissions to applications rather than to people, it can’t use the user names, passwords, and access control lists (ACLs) that you’re accustomed to.

Instead, CAS identifies assemblies using evidence. Each piece of evidence is a way that an assembly can be identified, such as the location where the assembly is stored, a hash of the assembly’s code, or the assembly’s signature. An assembly’s evidence determines which code group it belongs to. Code groups, in turn, grant an assembly a permission set. The sections that follow describe each of these components in more detail.

What Is Evidence?

Evidence is the information that the runtime gathers about an assembly to determine which code groups the assembly belongs to. Common forms of evidence include the folder or Web site from which the assembly is running and digital signatures.

Evidence: un término equivocado

La identificación podría ser un término mejor que evidencia. Evidencia suena como un conjunto de pistas que se utilizó para realizar un seguimiento de alguien que no quería ser identificado. En CAS, evidencia es utilizadó como pasaporte de una persona, la contraseña y PIN: información que demuestra la identidad y describe a un individuo como merecedores de un cierto nivel de confianza.

Table 11-1 shows the common types of evidence that a host can present to the runtime. Each row corresponds to a member class of the System.Security.Policy namespace.

Evidence Types

There are two types of evidence: host evidence and assembly evidence. Host evidence describes the assembly’s origin, such as the application directory, URL, or site. Host evidence can also describe the assembly’s identity, such as the hash, publisher, or strong name. Assembly evidence is custom user- or developer-provided evidence.

What Is a Permission?

A permission is a CAS access control entry. For example, the File Dialog permission determines whether an assembly can prompt the user with the Open dialog box, the Save dialog box, both, or neither. Figure 11-1 shows the File Dialog permission being configured.

By default, 19 permissions are available for configuration in the .NET Framework Configuration tool. Each corresponds to two members of the System.Security.Permissions namespace: one for imperative use and one for declarative use. Table 11-2 describes each of these permissions. Additionally, you can add custom permissions.

Permission Settings

Figure 11-1 Permissions specify whether an assembly can and can’t do specific actions

Default PermissionsDefault Permissions 2 Default Permissions 3 y 4

What Is a Permission Set?

A permission set is a CAS ACL. For example, the Internet default permission set contains the following permissions:

■ File Dialog

■ Isolated Storage File

■ Security

■ User Interface

■ Printing

The LocalIntranet zone contains more permissions, based on the theory that code running on your local network deserves more trust than code running from the Internet:

■ Environment Variables

■ File Dialog

■ Isolated Storage File

■ Reflection

■ Security

■ User Interface

■ DNS

■ Printing

The .NET Framework includes seven default permission sets, as described in Table 11-3.

Default Permission Sets

What Are Code Groups?

Code groups are authorization devices that associate assemblies with permission sets. Code groups provide a similar service to CAS as user groups provide to RBS. For

example, if an administrator wants to grant a set of users access to a folder, the administrator creates a user group, adds the users to the group, and then assigns file permissions to the group. Code groups work similarly, except that you don’t have to manually add individual assemblies to a group. Instead, group membership is determined by the evidence that you specify as the code group’s membership condition.

For example, any code running from the Internet should be a member of the Internet_Zone code group. As you can see from Figure 11-2, the Internet_Zone code group’s default membership condition is that the host presents Zone evidence, and that piece of Zone evidence identifies the assembly as being in the Internet zone.

Internet Zone Properties

Figure 11-2 The Internet_Zone code group membership is restricted by using Zone evidence

Whereas user groups control authorization based on distributed ACLs associated with each resource, code groups use centralized permission sets. For example, Figure 11-3 shows that the Internet_Zone code group assigns the Internet permission set. For convenience, the dialog box lists the permission set’s individual permissions. However, you cannot specify individual permissions for a code group. A code group must be associated with a permission set.

Internet Zone Properties PS

Figure 11-3 The Internet_Zone code group assigns the Internet permission set

BEST PRACTICES: Working with files

Applications running in the Internet and LocalIntranet zones do not receive the FileIOPermission, and as such, cannot directly access files. They do, however, have FileDialogPermission. Therefore, assemblies in the Internet zone can open files by prompting the user to select the file using an OpenFileDialog object. Assemblies in the LocalIntranet zone can also save files by using the SaveFileDialog object. To access files without FileIOPermission, call the ShowDialog method of either OpenFileDialog or SaveFileDialog. If the user selects a file, you can use the file handle returned by the OpenFile method to access the file.

It might seem limiting that you can specify only a single type of evidence and a single permission set for a code group. However, just as a user account can be a member of multiple user groups, an assembly can be a member of multiple code groups. The assembly will receive all the permissions assigned to each of the code groups (known as the union of the permission sets). Additionally, you can nest code groups within each other, and assign permissions only if the assembly meets all the evidence requirements of both the parent and child code groups. Nesting code groups allows you to assign permissions based on an assembly having more than one type of evidence. Figure 11-4 shows the Microsoft_Strong_Name code group nested within the My_Computer_Zone code group, which in turn is nested within the All_Code group.

Net FrameWork 2 Configuration Figure 11-4 You can nest code groups to require multiple types of evidence

Table 11-4 lists the default machine code groups residing directly within the All_Code code group. Additionally, some of these code groups contain nested code groups.

Default Code Groups

What Is Security Policy?

A security policy is a logical grouping of code groups and permission sets. Additionally, a security policy can contain custom assemblies that define other types of policies. Security policies provide administrators with the flexibility to configure CAS settings at multiple levels. By default, there are four configurable policy levels: Enterprise, Machine, User, and Application Domain.

The Enterprise level is the highest security policy level, describing security policy for an entire enterprise. Enterprise security policy can be configured by using the Active Directory directory service. Machine policy, the second security policy level, applies to all code run on a particular computer. User policy is the third level, and it defines permissions on a per-user basis. The runtime evaluates the Enterprise, Machine, and User levels separately, and it grants an assembly the minimum set of permissions granted by any of the levels (known as the intersection of the permission sets). By default, the Enterprise and User security policies grant all code full trust, which causes the Machine security policy to alone restrict CAS permissions.

Usefulness of Multiple Layers of Security Policy

To understand how security policies are used, consider an application developer who wants to play with an assembly she downloaded from the Internet. The developer has downloaded the assembly to her local computer, so it will run within the My Computer Zone. The developer’s computer is a member of an Active Directory domain, and a domain administrator has created a code group in the Enterprise security policy that grants assemblies on the local computer the Everything permission set. This is more restrictive than the FullTrust permission set that the Machine security policy grants assemblies in the My Computer zone, so the Everything permission set takes precedence.

The developer isn’t sure that the assembly is safe to run, however, so she wants to apply the Internet permission set to prevent the assembly from writing to the disk or communicating across the network. She doesn’t log on to her computer as an Administrator, but she can still launch the .NET Framework Configuration tool and modify the User security policy. (Standard users aren’t allowed to modify the Machine security policy.) By modifying the User security policy, she can restrict assemblies in the My Computer zone to the Internet permission set. Assemblies that she runs will be restricted without affecting other users of the same computer.

The assembly is a member of three code groups: one in the Enterprise security policy, one in the Machine security policy, and one in the User security policy. The runtime determines the assembly’s permissions by comparing each code group’s permission sets and using the most restrictive set of permissions shared by all three permission sets (the intersection). Because the FullTrust and Everything permission sets contain all the Internet permission set’s permissions (plus a few more permissions), the most restrictive set of permissions is exactly that defined by the Internet permission set.

How CAS Works with Operating System Security

CAS is completely independent of operating system security. In fact, you must use entirely different tools to administer CAS. Although you can control a user’s or group’s file permissions using Microsoft Windows Explorer, you have to use the .NET Framework Configuration tool to grant or restrict an assembly’s file permissions.

CAS works on top of existing operating system security. When determining whether an assembly can take a particular action, both CAS and the operating system security are evaluated. The most restrictive set of permissions is applied. For example, if CAS grants an assembly access to write to the C:\Windows\ folder but the user running the assembly does not have that permission, the assembly cannot write to the folder. Figure 11-5 shows how CAS relates to operating system security.

CAS Complement Figure 11-5 CAS complements, but does not replace, role-based security

How to Use the .NET Framework Configuration Tool to Configure CAS The .NET Framework Configuration tool provides a graphical interface for managing .NET Framework security policy and applications that use remoting services. You can perform many different CAS-related tasks, including the following:

■ Evaluating an assembly to determine which code groups it is a member of

■ Evaluating an assembly to determine which permissions it will be assigned

■ Adding new permission sets

■ Adding new code groups

■ Increasing an assembly’s trust

■ Adjusting zone security

■ Resetting policy levels

How to Determine Which Code Groups Grant Permissions to an Assembly

When troubleshooting CAS permissions, you might need to determine which code groups grant permissions to your assembly. To do this, launch the .NET Framework Configuration tool and perform the following steps:

1. Click Runtime Security Policy.

2. Click Evaluate Assembly. The Evaluate An Assembly Wizard appears.

3. On the What Would You Like To Evaluate page, click Browse. Select your assembly and then click Open.

4. Click the View Code Groups That Grant Permissions To The Assembly option. Click Next.

5. Expand each policy level to determine which code groups grant permissions to your assembly. Figure 11-6 shows an assembly that receives permissions from the My_Computer_Zone code group.

Evaluate an Assembly

Figure 11-6 Use the Evaluate An Assembly Wizard to determine which code groups apply permissions to your assembly

6. Click Finish.

How to Determine Total CAS Permissions Granted to an Assembly

When troubleshooting CAS permissions, you might need to determine which permissions the runtime will grant to your assembly. To do this, launch the .NET Framework Configuration tool and perform the following steps:

1. Click Runtime Security Policy.

2. Click Evaluate Assembly. The Evaluate An Assembly Wizard appears.

3. On the What Would You Like To Evaluate page, click Browse. Select your assembly and then click Open.

4. Click the View Permissions Granted To The Assembly option. Click Next.

5. The wizard displays each permission assigned to your assembly. To view the detailed permission settings, select any permission and then click the View Permission button.

6. Click Finish.

How to Add a Permission Set

To create a new permission set, launch the .NET Framework Configuration tool and perform the following steps:

1. Expand Runtime Security Policy.

2. Expand Enterprise, Machine, or User, depending on the policy level in which you want to define the permission set.

3. Click Permission Sets. In the right pane, click Create New Permission Set.

4. On the Identify The New Permission Set page, specify a name and description. Click Next.

5. On the Assign Individual Permissions To Permission Set page, perform the following steps:

A. Click the permission you want to add to the permission set, and click Add.

B. For each permission, specify the permission settings that are unique to that permission and click OK.

C. Repeat this process for each individual permission required by your permission set.

6. Click Finish.

How to Add a Code Group

To add a code group, launch the .NET Framework Configuration tool and perform the following steps:

1. Expand Runtime Security Policy.

2. Expand Enterprise, Machine, or User, depending on the policy level in which you want to define the code group.

3. Expand Code Groups, expand All_Code, and examine the existing child code groups. If the code group you want to create defines a subset of permissions for an existing code group, click that code group. Otherwise, click All_Code.

4. Click Add A Child Code Group.

5. On the Identify The New Code Group page, type a name and a description, and then click Next.

6. On the Choose A Condition Type page, specify the condition type for the code group by choosing the evidence the runtime will use to identify the code. Click Next.

7. On the Assign A Permission Set To The Code Group page, click the Use Existing Permission Set option if one of the current permission sets exactly meets your needs. Otherwise, click Create A New Permission Set. Click Next.

8. If you selected Create A New Permission Set, perform the following steps:

A. On the Identify The New Permission Set page, specify a name and description. Click Next.

B. On the Assign Individual Permissions To Permission Set page, click the permissions you want in the permission set and click Add. For each permission, specify the permission settings that are unique to that permission and click OK. Click Next.

9. On the Completing The Wizard page, click Finish.

How to Increase an Assembly’s Trust

If you have restricted the default CAS permissions on your computer, you might need to grant additional trust to specific assemblies to grant them the permissions they need to run correctly. To do this, launch the .NET Framework Configuration tool and perform the following steps:

1. Click Runtime Security Policy.

2. Click Increase Assembly Trust. The Trust An Assembly Wizard appears.

3. On the What Would You Like To Modify page, click Make Changes To This Computer to adjust the Mach ine policy level, or click Make Changes For The Current User Only to affect the User policy level. Click Next. You must be an administrator to adjust the Machine policy level.

4. On the What Assembly Do You Want To Trust page, click Browse. Select the assembly you want to trust and then click Open. You can trust only assemblies that have a strong name. Click Next.

5. On the Choose The Minimum Level Of Trust For The Assembly page, select the minimum trust level for the assembly. Click Next.

6. On the Completing The Wizard page, review your selections and then click Finish.

How to Adjust Zone Security

By default, the .NET Framework includes five zones, each with a unique set of CAS permissions. You should make use of these default zones whenever possible, but you might need to change the permission set that a zone uses. To do this, launch the .NET Framework Configuration tool and perform the following steps:

1. Expand Runtime Security Policy, expand Machine, expand Code Groups, and then expand All_Code.

2. Click the zone you want to adjust. In the right pane, click Edit Code Group Properties.

3. Click the Permission Set tab (shown in Figure 11-7) and then click an item in the Permission Set list to specify the desired permission set. Click OK.

LocalIntranet zone properties

Figure 11-7 Adjust the permissions assigned to a zone by adjusting the associated code group’s properties

As a developer, one of the first things you should do is adjust the permission set assigned to the My_Computer_Zone code group. By default, it’s set to Full Trust, which means any CAS statements in your applications will be completely ignored. Change this to the Everything permission set, which grants similar permissions but respects CAS statements in assemblies. Alternatively, you can further restrict access to local assemblies by choosing another permission set.

How to Reset Policy Levels

You might need to restore the default policy levels after making modifications. To do this, launch the .NET Framework Configuration tool and perform the following steps:

1. Click Runtime Security Policy. In the right pane, click Reset All Policy Levels.

2. Click Yes and then click OK.

The .NET Framework Configuration tool restores the original policy level settings, including removing all custom code groups and permission sets that you created.

Demo: Compile and Test the Permissions of a Sample Assembly

using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Printing;
using System.Security;
using System.Security.Permissions;

namespace ListPermissions
{
    class Program
    {
        static void Main(string[] args)
        {
            writePermissionState(new FileIOPermission(PermissionState.Unrestricted));
            writePermissionState(new EnvironmentPermission(EnvironmentPermissionAccess.Read, "USERNAME"));
            writePermissionState(new FileDialogPermission(FileDialogPermissionAccess.Open));
            writePermissionState(new IsolatedStorageFilePermission(PermissionState.Unrestricted));
            writePermissionState(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess));
            writePermissionState(new UIPermission(UIPermissionWindow.SafeTopLevelWindows));
            writePermissionState(new PrintingPermission(PrintingPermissionLevel.SafePrinting));

            Console.WriteLine("\nPress Enter key to continue");
            Console.Read();
        }

        static private void writePermissionState(CodeAccessPermission p)
        {
            // Write True or False depending on whether the user has the permission
            Console.WriteLine(p.GetType().ToString() + ": " + SecurityManager.IsGranted(p));
        }
    }
}

Resultado:

Ch11 Lesson 1 Exercise 01

Como era de esperarse, tengo todos los permisos, pues claro es mi laptop.

Published by justindeveloper

I am MCP (Microsoft Certified Professional). MCTS (Microsoft Certified Technology Specialist) and MCPD (Microsoft Certified Professional Developer), also I am SAP Business One Certified!! Desarrollando desde el IDE de Visual Studio NET 2003 hasta ahora con el Visual Studio NET 2010. Desde Microsoft SQL Server 2000 hasta ahora con el Microsoft SQL Server 2008 R2 y tambien con SharePoint, desde WSS 3.0 y MOSS 2007 y ahora familirizandome con el Sharepoint Foundation 2010 & Sharepoint Server 2010. The software development will follow being every time more wonderful!

One thought on “Application Security for Developers

Leave a comment