When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles [1.x] [2.0]
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips
Search

Sections:
Book Reviews
Sample Chapters
Commonly Asked Message Board Questions
Headlines from ASPWire.com
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
Web Hosts
XML
Information:
Advertise
Feedback
Author an Article
Jobs
















internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers
ASP ASP.NET ASP FAQs Message Board Feedback ASP Jobs
Print this Page!

Windows Systems Administrator
Jupitermedia
US-CT-Darien

Justtechjobs.com Post A Job | Post A Resume

Published: Wednesday, October 3, 2007

Hosting ASP.NET Applications in Medium Trust
By Scott Mitchell


Introduction
Many independent developers and small companies building Internet-accessible web applications turn to web hosting companies to host their website. Web hosting companies offer a variety of plans, from dedicated servers to shared plans. Shared plans, which are the most economical and practical for low-traffic websites, can have anywhere from 25 to 150 separated websites hosted from the same web server. When hosting multiple websites on the same server, it is important that one website cannot affect or harm another site. For example, both the web hosting company and its (honest) customers want to prevent one website from, say, reading the connect string information from Web.config of another website.

ASP.NET allows for web hosting companies to define trust levels, which dictate what operations are permitted by ASP.NET applications. A web hosting company can either use one of the preset trust levels - Full, High, Medium, Low, or Minimal - or can create a custom trust level. Full turst, which is the default, allows ASP.NET applications to execute native code, to read from the Registry and Windows Event Log, and to read and write to files outside of the application's virtual directory. In short, with full trust one web application could delete the entire contents of another web application!

Fortunately, most web hosting companies run in medium trust, which greatly reduces the potential for harm by limiting the set of operations an ASP.NET application can perform. While the protection granted by medium trust is reassuring, its limited functionality can be aggrevating for honest developers. In this article we'll look at how the trust-level is specified, what functionality is limited by medium trust, and some techniques to work around these limitations. Read on to learn more!

- continued -

Specifying Trust Levels
An ASP.NET application's trust level is specified in Web.config via the <trust> element:

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

The default trust level is Full, which grants unrestricted permissions. This is a dangerous trust level when working in a shared environment because it allows one web application to interact with the file system of anothers. For example, if you are in a shared environment that physically arranges its shared web applications in a common folder (i.e., C:\Inetpub\wwwroot\WebApplicationName1, C:\Inetpub\wwwroot\WebApplicationName2, ..., C:\Inetpub\wwwroot\WebApplicationNameN, and so on), one web application could use the following code to display the Web.config contents of all of the other web applications on the server:

'Look for Web.config files in parent directories
Dim myPath As String = Request.PhysicalApplicationPath
Dim parentPath As String = String.Concat(myPath, "..\")
Dim parentPathInfo As New DirectoryInfo(parentPath)

For Each folder As DirectoryInfo In parentPathInfo.GetDirectories()

    Dim fileOfInterest As String = Path.Combine(folder.FullName, "Web.config")

    If File.Exists(fileOfInterest) Then
      Dim webConfigReader As StreamReader = File.OpenText(fileOfInterest)
      Response.Write(String.Format("<p><b>Data for File {0}:</b></p><p>{1}</p><hr />", fileOfInterest, _                                                 Server.HtmlEncode(webConfigReader.ReadToEnd())))
      webConfigReader.Close()
    End If

Next

Since connection strings are usually placed in Web.config, the nefarious user running the above code would now be able to connect to other customers' databases, where there might be sensitive customer information. The point is, if an ASP.NET application is running in full trust, there's nothing to stop them from reading, creating, modifying, or deleting files in your web application's file system.

Fortunately, most web hosting companies follow the advice in Microsoft's ASP.NET 2.0 Hosting Deployment Guide and place their shared web applications in medium trust. This is accomplished by modifying the machine-level Web.config file in the %windir%\Microsoft.NET\Framework\{version}\CONFIG folder. Moreover, this setting can be locked by the web hosting company. See How To: Use Medium Trust in ASP.NET 2.0 for more information on setting the default trust level for a web server and how to lock this setting. The good news is that if the setting is correctly locked in the machine-level Web.config file, a web application hosted on the server cannot override the setting.

If you attempt to run the above code in a medium trust enviornment, a SecurityException will be thrown when attempting to create a DirectoryInfo object on the parent path.

A SecurityException is thrown.

Medium Trust Permissions
If an application is placed in medium tust, it is limited in the operations it can perform. The How To: Use Medium Trust in ASP.NET 2.0 article summarizes the main limitations as follows:

  • Limited FileIOPermissions: Only files within the application's virtual directory hierarchy can be accessed or modified.
  • Limited OleDbPermissions: the ADO.NET managed OLE DB data provider cannot be used to access databases.
  • Limited EventLogPermissions: you cannot access the Windows Event Log.
  • Limited WebPermission: you cannot make HTTP requests outside of your domain.
  • Limited RegistryPermission: you cannot access the Windows Registry.
  • Limited ReflectionPermission: you cannot use reflection.
Rick Strahl provides a more in-depth look at the limitations imposed by running in medium trust in his blog entry Running ASP.NET in Medium Trust.

Of course, a web hosting company may not necessarily be running strictly within medium trust. They may customize the permissions to, say, allow OleDbPermissions so that their customers can work with the managed OLE DB provider. For a detailed understanding of what permissions are allowed and which ones are denied, contact your web hosting company.

Working Around Medium Trust Limitations
If you are writing an application that may be used by others in a hosted environment, it is important to understand the impact of medium trust and to strive to ensure that your application will work in medium trust. It is important to test your application in a medium trust environment, which you can do by setting the <trust> element in Web.config. If you are using a third-party component or application that requires certain permissions that are typically denied when running in medium trust, your best bet it to contact your web hosting company and ask them to customize your trust level so that your website can function properly.

Some code that is prohibited from running in medium trust can be replaced by similar code that is runnable under medium trust. One such example is working with configuration information. Under medium trust you cannot use .NET's configuration API to read elements within the <system.web> element in Web.config. This is because the configuration API is not only inspecting your application's Web.config file, but also is examining configuration information up the chain and therefore in areas that fall outside of your web application's virtual directory. However, if you are only interested in the value(s) within the Web.config file in your application, you can read the file using .NET's XML-related classes.

A concrete example of this can be seen in my skmValidator controls. Back in September 2006 I published an article titled Creating Validator Controls for the CheckBox and CheckBoxList, which looked at building a custom validation control for the CheckBox and CheckBoxList Web controls. For reasons that aren't pertinent to this article, this control needed to determine whether the application was configured to emit legacy HTML. By default, ASP.NET 2.0 applications emit XHTML, but they can be configured to emit legacy HTML instead. This information can be set in the <xhtmlConformance> element in Web.config.

In any event, I wrote the code so that it used .NET 2.0's configuration API:

Configuration cfg = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
XhtmlConformanceSection xhtmlSection = (XhtmlConformanceSection) cfg.GetSection("system.web/xhtmlConformance");

return xhtmlSection.Mode == XhtmlConformanceMode.Legacy;

This code worked fine when running in full trust (which is how I tested it), but failed in medium trust. Since I failed to test in medium trust, I didn't catch this problem. I therefore wasn't aware of this problem until helpful reader Michael T. pointed it out to me (along with a fix). The fix was to use .NET's XML-related classes to open and read the contents of Web.config, searching for the <xhtmlConformance> element. Michael's code follows:

bool result;

try
{
   string webConfigFile = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, "web.config");
   XmlTextReader webConfigReader = new XmlTextReader(new StreamReader(webConfigFile));
   result = ((webConfigReader.ReadToFollowing("xhtmlConformance")) && (webConfigReader.GetAttribute("mode") == "Legacy"));
   webConfigReader.Close();
}
catch
{
   result = false;
}

return result;

Conclusion
Web hosting companies that offer shared plans typically force web applications to run in medium trust so as to prevent one customer from purposefully or accidentally harming another customer's website. Medium trust disables access to the Registry, and the Windows Event Log. It limits code from making external HTTP requests or modifying the file system outside of the application's virtual directory hierarchy.

While the reduced permission set of medium trust helps protect ASP.NET applications in a shared environment, it can introduce problems when integrating third-party applications that might not have been thoroughly tested to work in medium trust (or who need to perform operations that simply cannot be done in medium trust). You may be able to circumvent some of these limitations via alternate techniques, or you may have to contact your web host company and ask them to customize your trust level so that such operations are possible.

Happy Programming!

  • By Scott Mitchell


    Windows Internet Technology | ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article



  • JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
    Microsoft Article: 7.0, Microsoft's Lucky Version?
    Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Windows Server 2008
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES