描述:在执行当前的web请求时,发生了一个未处理的异常。请检查堆栈跟踪(stack trace)以获取关于此错误的更多信息以及哪行代码引起的。
异常详情:System.UnauthorizedAccessException: 拒绝访问注册表键。ASP.NET进程没有获得访问此资源的授权。
概述:默认情况下,ASP.NET 2.0 Web应用程序和Web服务的信任级别为Full。它在Web.config文件中指定,位于
Full级别赋予了无限制的特权,因此在web应用程序中可以对文件,注册表,Windows事件日志等进行操作。
前些天,在编写Web应用程序时,某项功能需要修改注册表。奇怪的是在VS 2005 内置的web服务器中,程序运行正常;部署到本机,使用http://localhost/...访问一切也是正常;但是使用http://hostname/或者部署到其它计算机时却出现了拒绝访问注册表异常。后来google一番,发现可能是
后记:最近项目快要做完了,于是有了想把在项目过程中遇到的问题以及解决方法记录下来,供后来参考。无奈只是大概记得当初出现了这么一个错误以及解决方法,有些却记不得了。因此下次遇到问题时一定要详细的记录,问题描述,出现时的context,以及解决方法。
另外附上两篇关于ASP.NET2.0中关于trust的文章,希望对遇到类似问题的朋友有所帮助。
patterns & practices Developer Center
J.D. Meier, Alex Mackman, Blaine Wastell, Prashant Bansode, Andy Wigley, Kishore Gopalan
Microsoft Corporation
August 2005
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.
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
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.
Copy Code
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.
The main differences between ASP.NET version 1.1 and ASP.NET version 2.0 for the trust levels are the following:
The main constraints placed on medium trust Web applications are:
You are also prevented from calling unmanaged code or from using Enterprise Services.
To use medium trust in your ASP.NET applications:
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.
Copy Code
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.
Copy Code
policyFile="web_mediumtrust.config" />
policyFile="web_minimaltrust.config" />
To review the full set of permissions available to medium trust applications, view the Web_mediumtrust.config file.
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.
Copy Code
policyFile="web_mediumtrust.config" />
policyFile="web_lowtrust.config" />
policyFile="web_minimaltrust.config" />
By setting allowOverride="false", an individual developer is unable to override the medium trust policy setting in their application's Web.config file.
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.
Copy Code
class="NamedPermissionSet"
version="1"
Name="ASP.Net">
...
class="FileIOPermission"
version="1"
Read="C:/SomeDir;$AppDir$"
Write="$AppDir$"
Append="$AppDir$"
PathDiscovery="$AppDir$"
/>
...
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.
Copy Code
policyFile="customWeb_mediumtrust.config" />
...
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.
Copy Code
policyFile="customWeb_mediumtrust.config" />
policyFile="web_hightrust.config" />
policyFile="web_mediumtrust.config" />
policyFile="web_minimaltrust.config" />
Common permissions that you might need to add include:
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.
Copy Code
Description="System.Data.OleDb.OleDbPermission, System.Data, Version= 2.0.0 .0,
Culture=neutral, PublicKeyToken=b 77a 5c 561934e089"/>
3. Add the unrestricted OleDbPermission to the "ASP.Net" named permission set, as shown in the following example.
Copy Code
class="NamedPermissionSet"
version="1"
Name="ASP.Net">
...
version="1"
Unrestricted="true"/>
...
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.
Copy Code
version="1">
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/data/w4w.mdb"
KeyRestrictions=""
KeyRestrictionBehavior="AllowOnly"/>
The <add> element supports the following attributes:
· 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.
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.
Copy Code
...
Description="System.Diagnostics.EventLogPermission, System, Version= 2.0.0 .0,
Culture=neutral, PublicKeyToken=b 77a 5c 561934e089" />
...
3. Add the following EventLogPermission to the "ASP.Net" named permission set.
Copy Code
class="NamedPermissionSet"
version="1"
Name="ASP.Net">
...
class="EventLogPermission"
version="1">
access="Write"/>
...
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.
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
Copy Code
HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/Eventlog/
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.
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.
Copy Code
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.
To help design and develop your applications for medium trust, consider the following:
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.
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.
Do this at the start of development so that you can immediately see what permission requests fail and what issues need to be addressed.
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:
Provide feedback by using either a Wiki or e-mail:
We are particularly interested in feedback regarding the following:
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 http://support.microsoft.com.
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.
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!
Specifying Trust Levels
An ASP.NET application's trust level is specified in Web.config via the
|
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 Data for File {0}: {1} |
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.
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:
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
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
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
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); |
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
bool 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