Share via


How To: Use Medium Trust in ASP.NET 2.0

 

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

patterns & practices Developer Center

patterns & practices Developer Center

J.D. Meier, Alex Mackman, Blaine Wastell, Prashant Bansode, Andy Wigley, Kishore Gopalan

Microsoft Corporation

August 2005

Applies To

  • ASP.NET version 2.0

Summary

This How To shows you how to configure ASP.NET Web applications to run in medium trust. If you host multiple applications on the same server, you can use code access security and the medium trust level to provide application isolation. By setting and locking the trust level in the machine-level Web.config file, you can establish security policies for all Web applications on the server. Running at medium trust with ASP.NET version 2.0 is easier than with ASP.NET version 1.1 because when using ASP.NET 2.0, you have access to Microsoft SQL Server databases at medium trust. Medium trust still provides a constrained environment for isolating applications from one another and from shared server resources. Medium trust applications have no registry access, no event log access, and no ability to use reflection. Web access is limited to the network address that you define in the <<trust/>> element, and file system access is limited to the application's virtual directory hierarchy. If medium trust policy is too restrictive, you can create and use a custom policy file.

Contents

Objectives
Overview
What's New in 2.0
Medium Trust Summary
Summary of Steps
Step 1. Configure Medium Trust
Step 2. Lock the Trust Level
Step 3. Optionally Create a Custom Policy Based on Medium Trust
OleDbPermission, EventLogPermission and FileIOPermission
Developing for Medium Trust
Additional Resources

Objectives

  • Learn how to develop Web applications using medium trust.
  • Learn what has changed with partial trust Web applications in ASP.NET version 2.0.
  • Learn about the constraints while using medium trust levels.
  • Configure medium trust levels in your Web application.
  • Modify trust levels to create your own custom trust levels.

Overview

By default, ASP.NET 2.0 Web applications and Web services run with full trust and applications can perform privileged operations and access resources subject only to operating system security and Windows access control lists (ACLs).

To lock down an ASP.NET application and to provide an additional level of application isolation in a hosted environment, you can use code access security to restrict the resources the application can access and the privileged operations it can perform. You do this by configuring the <trust> element as shown here.

<trust level="Full|High|Medium|Low|Minimal" />
  

The <trust> element supports a number of default trust levels. Each level in succession provides a more restrictive environment (with fewer code access security permissions) in which to run your application.

Internet service providers (ISPs) that need to host multiple applications from many different companies frequently use the medium trust level to help ensure that applications cannot read each other's data or interfere with one another in any way. Medium trust also places restrictions on the types of shared system resources that the applications can access.

What's New in 2.0

The main differences between ASP.NET version 1.1 and ASP.NET version 2.0 for the trust levels are the following:

  • In ASP.NET versions 1.1 and 2.0, medium trust applications can access SQL Server databases because the SQL Server managed data provider does not demand full trust and SqlClientPermission is granted to medium trust applications.
  • In .NET Framework version 2.0, the Oracle .NET data provider, the OLE DB .NET data provider, and the ODBC .NET data provider no longer demand full trust. This allows you to access SQL Server and other databases from partial trust applications. To use these providers from medium trust applications in ASP.NET, you need to customize policy and grant the appropriate permission: for example, OraclePermission, OleDbPermission or OdbcPermission.
  • In ASP.NET version 2.0, SmtpPermission is available at full, high, and medium trust levels. This allows applications to send e-mail.
  • In ASP.NET version 1.1, you had to grant code full trust to access the event log. This is no longer required in ASP.NET version 2.0, although you must still create a custom trust policy file to grant the EventLogPermission, as described later in this document.

Medium Trust Summary

The main constraints placed on medium trust Web applications are:

  • OleDbPermission is not available. This means you cannot use the ADO.NET managed OLE DB data provider to access databases. However, you can use the managed SQL Server provider to access SQL Server databases.
  • EventLogPermission is not available. This means you cannot access the Windows event log.
  • ReflectionPermission is not available. This means you cannot use reflection.
  • RegistryPermission is not available. This means you cannot access the registry.
  • WebPermission is restricted. This means your application can only communicate with an address or range of addresses that you define in the <trust> element.
  • FileIOPermission is restricted. This means you can only access files in your application's virtual directory hierarchy. Your application is granted Read, Write, Append, and PathDiscovery permissions for your application's virtual directory hierarchy.

You are also prevented from calling unmanaged code or from using Enterprise Services.

Summary of Steps

To use medium trust in your ASP.NET applications:

  • Step 1. Configure medium trust.
  • Step 2. Lock the trust level.
  • Step 3. Optionally create a custom policy based on medium trust.

Step 1. Configure Medium Trust

To configure an application to run with medium trust, add the following element to either the application's specific Web.config file in the application's virtual root directory or to the machine-level Web.config file.

<trust level="Medium" originUrl="" />
  

Note   If present, the originUrl attribute can be used by some permissions, such as WebPermission, to restrict connectivity to a defined set of addresses.

To configure all Web applications on a server to run with medium trust, add this element to the machine-level Web.config file located in the following folder: %windir%\Microsoft.NET\Framework\{version}\CONFIG.

By default, Web applications are configured to run with full trust as shown in the following default configuration from the machine-level Web.config file.

<location allowOverride="true">
 <system.web>
   <securityPolicy>
     <trustLevel name="Full" policyFile="internal" />
     <trustLevel name="High" policyFile="web_hightrust.config" />
     <trustLevel name="Medium" 
                 policyFile="web_mediumtrust.config" />
     <trustLevel name="Low"  policyFile="web_lowtrust.config" />
     <trustLevel name="Minimal" 
                 policyFile="web_minimaltrust.config" />  
   </securityPolicy>
   <trust level="Full" originUrl="" />
 </system.web>
</location>
  

To review the full set of permissions available to medium trust applications, view the Web_mediumtrust.config file.

Step 2. Lock the Trust Level

Application service providers or anyone responsible for running multiple Web applications on the same server should apply the medium trust policy setting in the machine-level Web.config file and then lock the trust level for all Web applications.

To do this, set the allowOverride attribute to false in the machine-level Web.config file, as shown in the following code example.

<location allowOverride="false">
 <system.web>
   <securityPolicy>
     <trustLevel name="Full" policyFile="internal" />
     <trustLevel name="High" policyFile="web_hightrust.config" />
     <trustLevel name="Medium"
                 policyFile="web_mediumtrust.config" />
     <trustLevel name="Low"  
                 policyFile="web_lowtrust.config" />
     <trustLevel name="Minimal" 
                 policyFile="web_minimaltrust.config" />  
   </securityPolicy>
   <trust level="Medium" originUrl="" />
 </system.web>
</location>
  

By setting allowOverride="false", an individual developer is unable to override the medium trust policy setting in their application's Web.config file.

Step 3. Optionally Create a Custom Policy Based on Medium Trust

If medium trust proves too restrictive, you can create a custom policy file based on the medium trust policy. For example, you might want to allow applications to do one of the following: connect to an Oracle database, write events to the Windows event log, or read files from a specified directory outside of the application's virtual directory hierarchy.

To create a custom policy based on medium trust

  1. Copy the medium trust policy file web_MediumTrust.config located in the following directory to create a new policy file in the same directory: %windir%\Microsoft.NET\Framework\{Version}\CONFIG.

    Give it a name that indicates that it is your variation of medium trust; for example, it could be named customWeb_MediumTrust.config.

  2. Add the permissions that you want to grant. In the following example, the FileIOPermission is modified to allow read access to a specific directory outside of the application's virtual directory hierarchy.

    <PermissionSet
        class="NamedPermissionSet"
        version="1"
        Name="ASP.Net">
      ...
        <IPermission
             class="FileIOPermission"
           version="1"
             Read="C:\SomeDir;$AppDir$"
             Write="$AppDir$"
             Append="$AppDir$"
             PathDiscovery="$AppDir$"
    />
      ...
    </PermissionSet>
    
    
  3. Create a new custom policy level in your machine-level Web.config file. The policy file is the name of the policy file you created in step 1.

    <securityPolicy>
      <trustLevel name="CustomMedium" 
                  policyFile="customWeb_mediumtrust.config" />
      ...
    </securityPolicy>
    
    
  4. Configure applications to run at the new custom policy level by setting the trust level to "CustomMedium". Your security policy will resemble the following example.

    <system.web>
      <securityPolicy>
       <trustLevel name="CustomMedium"
                   policyFile="customWeb_mediumtrust.config" />
       <trustLevel name="Full" policyFile="internal" />
       <trustLevel name="High" 
                   policyFile="web_hightrust.config" />
       <trustLevel name="Medium" 
                   policyFile="web_mediumtrust.config" />
       <trustLevel name="Low"  policyFile="web_lowtrust.config" />
       <trustLevel name="Minimal"
                   policyFile="web_minimaltrust.config" />
     </securityPolicy>
     <trust level="CustomMedium" originUrl="" />
    </system.web>
    
    

OleDbPermission, EventLogPermission and FileIOPermission

Common permissions that you might need to add include:

  • OleDbPermission
  • EventLogPermision
  • FileIOPermission

OleDbPermission

If you support multiple database server types, you need to grant OleDbPermission to Web applications in addition to SqlClientPermission, which is already granted by medium trust policy.

To extend medium trust policy to grant OleDbPermission

  1. Create a custom policy file and configure your application to use the custom trust level, as described in the "Modifying Medium Trust Policy" section earlier in this document.

  2. Add the following permission class to the <SecurityClasses> section.

    <SecurityClass Name="OleDbPermission" 
                   Description="System.Data.OleDb.OleDbPermission, System.Data, Version=2.0.0.0, 
                                Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
    
    
  3. Add the unrestricted OleDbPermission to the "ASP.Net" named permission set, as shown in the following example.

    <PermissionSet
        class="NamedPermissionSet"
        version="1"
        Name="ASP.Net">
      ...
         <IPermission class="OleDbPermission" 
                      version="1" 
                      Unrestricted="true"/>
         ...
       </PermissionSet>
    
    

Locking Down Connection Strings

Adding the unrestricted OleDbPermission to your policy file means that your application can use any OLE DB provider on the server. In a hosted environment, an administrator may need to use the more advanced form of the OleDbPermission syntax to lock down connection strings used with OleDbPermission to allow access only to specific databases. The following example shows how to restrict access to a specific OLE DB data source.

<IPermission class="OleDbPermission"
             version="1">
  <add ConnectionString=
          "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\data\w4w.mdb"
       KeyRestrictions=""
       KeyRestrictionBehavior="AllowOnly"/>
</IPermission>
  

The <add> element supports the following attributes:

  • ConnectionString. This element specifies a permitted connection string.
  • KeyRestrictions. This element specifies additional connection string parameters that may or may not be added to the connection string depending on the value of KeyRestrictionBehavior. Specify connection string parameters using the syntax parameterName=. You can specify multiple parameters by delimiting each one with a semi-colon (;).
  • KeyRestrictionBehavior. You can set this to AllowOnly or PreventUsage.
    • If you use AllowOnly, only the additional connection string parameters specified in the KeyRestrictions attribute may be added to the connection string specified in ConnectionString.
    • If you use PreventUsage, the connection string parameters specified in the KeyRestrictions attribute may not be added to the connection string specified in ConnectionString, although other connection string parameters may be added.

If no key restrictions are specified, and the KeyRestrictionBehavior attribute is set to AllowOnly, no additional connection string parameters are allowed.

If no key restrictions are specified, and the KeyRestrictionBehavior property is set to PreventUsage, additional connection string parameters are allowed.

EventLogPermission

Medium trust policy does not permit access to the Windows event log.

To enable access to the event log

  1. Create a custom policy file and configure your application to use the custom trust level, as described in the "Modifying Medium Trust Policy" section earlier in this document.

  2. Add the following permission class to the <SecurityClasses> section to the custom policy file.

    <SecurityClasses>
      ...
      <SecurityClass Name="EventLogPermission"
                     Description="System.Diagnostics.EventLogPermission, System, Version=2.0.0.0, 
                                 Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      ...
    </SecurityClasses>
    
    
    
  3. Add the following EventLogPermission to the "ASP.Net" named permission set.

    <PermissionSet
        class="NamedPermissionSet"
        version="1"
        Name="ASP.Net">
      ...
         <IPermission
              class="EventLogPermission"
              version="1">
            <Machine name="."
            access="Write"/>
         </IPermission>
         ...
       </PermissionSet>
    
    

Note   At the time of writing, you must set access="administer" to be able to write to the event log from a partial trust application.

Creating Event Sources

If your application needs to use application specific event sources, you should create them at installation time when administrator privileges are available. A good approach is to use a .NET installer class, which can be instantiated by the Windows Installer (if you are using .msi deployment) or by the InstallUtil.exe system utility.

If you are unable to create event sources at installation time, and you are in deployment, the administrator should manually create new event source entry beneath the following registry key

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\<LogName>

Note   You should not grant write permission to the ASP.NET process account (or any impersonated account if your application uses impersonation) on the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\ registry key. If you allow write access to this key and the account is compromised, the attacker can modify any log-related setting, including access control to the log, for any log on the system.

FileIOPermission

If you need to allow your application to access files outside of the application's virtual directory hierarchy, you can create a custom policy file based on the medium trust file, and then modify the FileIOPermission.

For example, the following definition enables an application to read files in the "C:\SomeDir" directory.

<IPermission
  class="FileIOPermission"
  version="1"
  Read="C:\SomeDir;$AppDir$"
  Write="$AppDir$"
  Append="$AppDir$"
  PathDiscovery="$AppDir$"
/>
  

By letting applications access files beyond the application's virtual directory hierarchy, you diminish the ability of code access security to provide application isolation. If you have multiple applications on a single server, you need to protect resources, such as files with ACLs, and use separate identities for each application.

Developing for Medium Trust

To help design and develop your applications for medium trust, consider the following:

  • Identify the types of resources that your application needs to access and the privileged operations it needs to perform.

    You need to know which code access security permissions your application requires. For more information about permission requirements, see the "Resource Access Permissions Summary" and "Privileged Operation Permissions Summary" sections in How To: Use Code Access Security in ASP.NET 2.0.

  • Know what permissions are available at medium trust.

    The best way to learn what permissions are available is to open and examine the web_MediumTrust.config file in the following folder: %windir%\Microsoft.NET\Framework\{Version}\CONFIG.

  • Configure your development environment and your application's Web.config file for medium trust.

    Do this at the start of development so that you can immediately see what permission requests fail and what issues need to be addressed.

  • For existing applications, consider using the Permcalc tool.

    If you have an existing application that you want to run at medium trust, consider using the Permcalc tool to help you determine precisely which permissions your application needs. You should also make sure that extensive testing is performed to verify that all code paths through your application have been executed. Failure to do so can lead to unexpected security exceptions at run time.

The best approach is to target your trust level before you begin design and development work and to design and develop specifically for this trust level. Common causes of security exceptions when you switch an existing application to medium trust include:

  • Calling unmanaged code.
  • Accessing the registry.
  • Writing to the event log.
  • Connecting to databases other than SQL Server.
  • Accessing Web resources on remote servers.
  • Accessing the file system beyond your application's virtual directory hierarchy.

Additional Resources

Feedback

Provide feedback by using either a Wiki or e-mail:

We are particularly interested in feedback regarding the following:

  • Technical issues specific to recommendations
  • Usefulness and usability issues

Technical Support

Technical support for the Microsoft products and technologies referenced in this guidance is provided by Microsoft Support Services. For product support information, please visit the Microsoft Product Support Web site at https://support.microsoft.com.

Community and Newsgroups

Community support is provided in the forums and newsgroups:

To get the most benefit, find the newsgroup that corresponds to your technology or problem. For example, if you have a problem with ASP.NET security features, you would use the ASP.NET Security forum.

Contributors and Reviewers

  • External Contributors and Reviewers: Jason Taylor, Security Innovation; Rudolph Araujo, Foundstone Professional Services
  • Microsoft Consulting Services and PSS Contributors and Reviewers: Adam Semel, Tom Christian, Wade Mascia
  • Microsoft Product Group Contributors and Reviewers: Stefan Schackow
  • Test team: Larry Brader, Microsoft Corporation; Nadupalli Venkata Surya Sateesh, Infosys Technologies Ltd; Sivanthapatham Shanmugasundaram, Infosys Technologies Ltd.
  • Edit team: Nelly Delgado, Microsoft Corporation; Tina Burden McGrayne, TinaTech Inc.
  • Release Management: Sanjeev Garg, Microsoft Corporation

patterns & practices Developer Center

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.