Contact   •   Products   •   Search

Rick Strahl's Web Log

Wind, waves, code and everything in between...
ASP.NET • C# • HTML5 • JavaScript • AngularJs

Running ASP.NET in Medium Trust


I’ve been spending a bit of time testing my ASP.NET West Wind Web Store application in medium trust, and it’s been a hit or miss situation finding little things here and there that don’t work. I’m big on framework code, so I have lots of generic code in my base framework and some of this code has been choking on some of the limited permissions that are available. Fortunately most of these are relatively easy to work.

 

But there are a few that are problematic and not quite so easily worked around:

 

ReflectionPermission

Medium trust doesn’t have access to protected members for Reflection. This is a problem for me because I use a custom databinding scheme which uses Reflection to connect properties and data fields to control properties. Example: Binding a business object entity to a TextBox.Text value. In most ‘normal’ situations you would declare the business object as:

 

protected busInvoice Invoice;

 

and using Reflection on that isn’t going to work.

 

WebPermission

Medium trust allows only HTTP access to the same domain. Ouch! I use the WebRequest class for Credit Card Authorization, and that fails with the default permissions.

 

SocketPermission

Similar situation for a custom SMTP class I’ve been using. I can get around this by using the new System.Net SMTP class, but I haven’t gotten around to convert my class to it yet.

 

UnmagedCode SecurityPermission

This is required when using some of the Credit Card interfaces provided by the credit card vendors. Verisign PayFlowPro and LinkPoint both use COM interfaces (although LinkPoint has a C API that one can wrestle with). Both also tout a .NET interface, but both provide only COM Interop wrappers around the COM APIs (although I haven’t checked recently).

 

 

With the ReflectionPermissions off, my app runs. I’ve had to make a few changes marking members as public where I ordinarily wouldn’t but I can live with that. The other two are more criticial as there’s no clear workaround. Specifically the WebPermission one for the Authorize.NET, AccessPoint, BluePay interfaces or the UnmagedCode permissions when LinkPoint or PayFlow are used have no real workarounds.

 

So, to make this fly I’m shipping a WebStoreMedium.config file with the app that allows limited enabling of functionality without having to go to full trust all out. Depending on what features are used one or two things might need to be enabled.

 

So what do you need to do?

 

<configuration>

    <mscorlib>

        <security>

            <policy>

                <PolicyLevel version="1">

                    <SecurityClasses>

                      <!-- West Wind Web Store Added Security Classes -->

                      <SecurityClass Name="ReflectionPermission" Description="System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.0.0, Culture=neutral,PublicKeyToken=b77a5c561934e089"/>

                      <SecurityClass Name="SocketPermission" Description="System.Net.SocketPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>

                      <!-- End West Wind Web Store Added Security Classes -->

                     

 

 

First thing is to add any non-defined SecurityClass entries for the permissions required. In my case the ReflectionPermission and SocketPermissions needed to be added. This entry only sets up the permissions that can be addressed, not the actual permissions available for it.

 

Note that these permissions must be specified with their full strong name. The easiest way to find these permissions is by looking the base web.config in the .NET Configuration directory (C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG). Here you can find the default web.config as well as high trust and low trust versions of these files and in them you can find the various permission definitions.

 

Next are the permission sets and the actual permissions that need to get set:

 

<NamedPermissionSets>

                        <PermissionSet

                                class="NamedPermissionSet"

                                version="1"

                                Unrestricted="true"

                                Name="FullTrust"

                                Description="Allows full access to all resources"

                        />

                        <PermissionSet

                                class="NamedPermissionSet"

                                version="1"

                                Name="Nothing"

                                Description="Denies all resources, including the right to execute"

                        />

                        <PermissionSet

                                class="NamedPermissionSet"

                                version="1"

                                Name="ASP.Net">

 

                          <!--  West Wind Web Store Specific Permissions Adjustments -->

                          <IPermission class="ReflectionPermission"

                                       version="1"

                                       Unrestricted="true" />

                          <IPermission

                                        class="WebPermission"

                                        version="1"

                                        Unrestricted="true" />

                          <IPermission

                                        class="SocketPermission"

                                        version="1"

                                        Unrestricted="true" />

                          <!--  West Wind Web Store Specific Permissions Adjustments -->

 

                          <IPermission

                                    class="SecurityPermission"

                                    version="1"

                                    Flags="Assertion, Execution, ControlThread, ControlPrincipal, RemotingConfiguration,UnmanagedCode"

                            />

 

</PermissionSet>

          </NamedPermissionSets>

 

 

Each individual permission has its own set of properties, but in most cases you can enable them outright by setting the Unrestricted="true". In the case of Web and Socket Permissions there are options for limiting domain or IP addresses for example.

 

Again to see settings available it’s often easiest to look in the base files to see what settings are made for the full-trust scenario and add these in.

 

 

While all of this works, I really wonder whether this will fly with an ISP. An ISP isn’t going to let you make changes at the application level like this. Nevertheless I think it’s a good idea to have a ready-made file like this available so it can be handed off to an ISP to let them know exactly what permissions you might need for an application. After all if you need to do CC processing with Authorize.NET for example, there’s no real way around having the appropriate rights to do HTTP Access.

 

I’d be curious to hear what others are doing with typical ISP setups. I’ve always been lucky enough either to run on my own boxes or have flexible ISPs, so I can’t say anything about how hard ass ISPs get about this. I would appreciate some feedback in this area…

Make Donation


Feedback for this Post

 
# re: Running ASP.NET in Medium Trust
by Joe Brinkman July 10, 2006 @ 5:10am
Rick,
There is a compromise available for Webpermission so that a hoster is not required to provide unrestricted webpermissions. You can add "safe" urls to the permission set. This is covered fairly well by Cathal Connely at http://developers.ie/blogs/cconnolly/archive/2005/07/01/1498.aspx and in an excerpt from "Profession ASP.Net 2.0 Security, Membership and Role Management" by Stefan Schackow at http://www.wrox.com/WileyCDA/Section/id-291738.html.

Also, another eCommerce store vendor that I work with has been able to get many 3rd party CC gateway providers to update their components to work in medium trust. You may just need to contact the vendors to find out if they have solutions available or if they are working on the problem.

I have had several people tell me that more and more hosts are shifting to medium trust, but that they are loosening some restrictions. One host (I believe CrystalTech) authorizes unrestricted webpermissions and reflection. So the problem may not be as serious as it first seems.

HTH
# re: Running ASP.NET in Medium Trust
by dominick July 10, 2006 @ 5:14am
Hi Rick,

re the WebPermission - you can workaround that by using the originUrl attribute in web.config - this allows you to specify a host or service (using a regex) that is allowed to call via HTTP.

For everything that requires unmanaged code i would recommend writing a wrapper around that, strong name it and add a new code group for that wrapper in the policy file that grants the necessary permission. Your app code would use the wrapper who in turn asserts the permissions and calls into the COM component.

Having to grant unmanaged code access for the whole app (for your CC payment components) pretty much defeats the purpose of CAS.

But you are right, in all cases a typical ISP will not allow you to make any changes to their policy. get a dedicated server.

dominick
# Interesting Finds: July 10, 2007
by Jason Haley July 10, 2006 @ 9:48pm
# re: Running ASP.NET in Medium Trust
by Jason Mauer July 11, 2006 @ 1:56am
Some web hosts are tweaking the medium trust permissions... GoDaddy for example has WebPermission enabled for outbound HTTP and HTTPS access.

http://help.godaddy.com/article.php?article_id=1039&topic_id=216&&isc=gppg1753
# More On Medium Trust and Trackbacks
by Community Blogs July 11, 2006 @ 7:21pm
In my last post, one of the restrictions listed when running in medium trust is that HTTP access is only
# re: Running ASP.NET in Medium Trust
by Rick Strahl July 12, 2006 @ 3:27am
Joe, I gave the originUrl a shot but I haven't had any luck getting it to work. If I add:

<trust level="Medium" originUrl="https://secure.authorize.net/*" />

I still can't process credit cards. It's possible that it's because of the https in the url, but it isn't working in any case...


# re: Running ASP.NET in Medium Trust
by Bilal August 17, 2006 @ 10:19pm
I would really like to see a full example of the webpermission work around. My ISP (Magma) has been giving me a hard time for the past two weeks.

Thanks,
Bilal
# re: Running ASP.NET in Medium Trust
by Michael Chung September 11, 2006 @ 5:04am
Rick you're missing a '.' in that regular expression:

<trust level="Medium" originUrl="https://secure.authorize.net/.*" />
# re: Running ASP.NET in Medium Trust
by Rick Strahl September 11, 2006 @ 5:15am
Michael,
Hmmm... I didn't realize that this actual WAS meant to be a regular expression. I figured it was a wild card <s>...
# re: Running ASP.NET in Medium Trust
by Headtonz November 22, 2006 @ 3:23am
Hi All

Recently I informed my provider of the ability to basically download/read/move/delete files on thier entire hosting server using ASP.net 2.

It was using a script as made for admin of my sites Filesystem but was shocked to discover I could navigate to the c drive and all contents of.

The first tech guy went "so whats the problem...your average user cant do this?"

er, when I eventually spoke to someone who had a clue and understood the potential for misuse, they sent me a link.

The solution was to implement a medium policy accross the board from the default 'full'

Unfortunately this was a knee jerk reaction where no customers were informed.

This required all dlls to be recompiled and dependant classes permission set to allowed.

You can see the pain/devastation caused here.

http://forums.brinkster.com/forumresponse.asp?id=113605&respond=T&fid=23

I thought i was doing them a favour but its affected a lot of businesses. My site is broken, along with many others.

My Dev enviroment with the web config set to trust = medium doesnt work the same. Components dont work.
OLedb doesnt work.
All in all a really sad state of affairs.

You cant blame an ISP for setting thier sites to Medium, but this I feel is a major issue when purchasing a host.

I believe this should be advertised up front.

Anyone else had similar issues? This is an ASP.NET 2.0 issue only.

Allan
# re: Running ASP.NET in Medium Trust
by Rick Strahl November 22, 2006 @ 1:41pm
Allan,

Well, as you're pointing out here ISPs have to walk the line between usability and the ability to control their environment. Running in Medium trust is somewhat reasonable and truthfully most things work just fine. The problem is that if you haven't been developing in medium trust and you make the switch it's going to be incredibly difficult to find all the places where it breaks.

As a general guideline (and one I fell into the hard way myself) is to always develop in medium trust if at all possible and if you hit something that doesn't work with MT add the appropriate permission and document in web.config WHY you required the change.

I suspect most of the navigation problems (navigating to the C drive) you were mentioning above have little to do with medium trust but with badly configured directory permissions by the ISP!
# re: Running ASP.NET in Medium Trust
by Allan November 24, 2006 @ 9:26am
Thanks Rick

Interestingly this trust issue has opened an ethical issue and associated dillema. That is is if you discover a vulnerability in a providers unfrastraucture do you report it?

Computer and Ethics is something that is not really discussed alot - and is perhaps a topic for another forum albiet this is about security/trust. Generally techies are interested in the challenge of coding and producing the result as opposed to its usage and moral/ethical issues.

In this case informing the ISP of the situation above has caused alot of pain for other customers. Yet not to act would top be knowingly leaving not only mine but many other users data at risk. I chose to act.

Unfortunately, the weaknesses exposed above have meant that the resulting administration changes in the network infrastructure have significantly affected the businesses that rely on a website for an income stream.

Talking to a friend last night about this issue, he made the anology of a document factory leaving its back door open. Sure you would tell them right? Maybe if the factories' contents weren't so valuable it wouldnt matter, but how would you know unless you had a look? I mean what would you do?

There are some definite lessons to be learnt here, about trust and security that is - oh and .net lessons that go beyond just coding.

I have yet to get up and running with my site in medium trust (both local and live remote) and to get everything working even after recompiling certain components for medium trust. For starters theres getting OLEDB working, which is now done but wheres the security config tool? Did I miss some thing or is it really of editing all those policy and config files - to me thats not promoting an easy way to secure your server.

There is a disturbing element to all of this as my ISP Put it,

"ABCCompany(changed) is not the only company that has had this issue. All other hosting companies that support .NET 2.0 either have or will have the same issue when they find out about it."

Potentially the default install settings of the .net framework leave a gaping hole in security.

Well I kinda get the shivers when data protection and privacy come to mind.

Now its another black hole of time, scouring the net trying to get my project on the road again and find those places where it breaks and the difficulties you mentioned.

Strong coffee anyone?

Allan

PS Rick could you please remove the link (and this PS) I provided above as it gives away my host and its probably not cool to include this detail (plus it doesnt work anyway!). Thanks
# Running ASP.NET in Medium Trust - Rick Strahl's Web Log
by Rick Strahl's Web Log November 27, 2006 @ 2:40am
I’ve been spending a bit of time testing my ASP.NET Web Store application in medium trust, and it’s been a hit or miss situation finding little things here and there that don’t work. I’m big on framework code, so I have lots of generic code in my base framework and some of this code has been choking on some of the limited permissions that are available. Fortunately most of these are relatively easy to work. But there are a few that are problematic and not quite so easily worked around. Here's wh
# DotNetSlackers: Running ASP.NET in Medium Trust
by DotNetSlackers Latest ASP.NET News December 13, 2006 @ 2:09am
# SourceForge.net: Open Discussion
by March 08, 2007 @ 11:30am
The world's largest development and download repository of Open Source code and applications
# re: Running ASP.NET in Medium Trust
by alex March 25, 2007 @ 8:54pm
im running a DNN 3 installation and trying to use the verisign payflow gateway but i run into problems when i set the unmanaged code permission i get the following configuration error. I've tried so many things. Setting the trust level to full gives this message as well so its obviously something to do with the unmanaged code setting

Parser Error Message: ?

Source Error:

Line 196: <add assembly="System.EnterpriseServices, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
Line 197: <add assembly="System.Web.Mobile, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
Line 198: <add assembly="*"/>
Line 199: </assemblies>
Line 200: </compilation>


If anyone has a solution or workaround please email me on rupurt@gmail.com
# Custom Trust Level For Community Server
by Dave's Tech Shop July 05, 2007 @ 7:49am
# re: Running ASP.NET in Medium Trust
by Some Jerk October 25, 2007 @ 2:20pm
2 questions, and while I am a bit impatient to get back to work I apologize if they have been answered and I did not notice.

1. It seems like there should be a way to override some base security principals and simplify the web.config modifications. The web.config entries appear to be reflecting authentic classes, is it possible to reduce this to a single entry in web.config to reference a class that adjusts the other entries by implication?

2. I hope this does not suggest that my coding skills are inadequet (because I am quite a talented coder) but I do not see the relationship between SecurityClass, PermissionSet, and IPermission. What I mean by that is that they seem to arbitrarily define possibilities. What I Personaly want is AssemblyID {SOME BIG GUID} to have full trust for ReflectionPermission, and all other assemblies can bugger off. This seems generic and arbitrary, allowing all external assemblies the same permissions. And exactly what is the deal with the <PermissionSet entries? They do not appear to serve a purpose. They are unrefferenced and apparently as arbitrary as the other, only they all have the same names.
# The importance of sandboxing when developing
by Sogeti Phoenix Blogs March 22, 2008 @ 12:02pm
The importance of sandboxing when developing
# ASP.NET:C#:MediumTrust Sucks
by .NET:ACL August 28, 2008 @ 8:59pm
<p><a href="/Portals/SkySigal/images/Blog/WLW/ASP.NETCMediumTrustSucks_10245/image_2.png"><img style="border-bottom: 0px; border-left: 0px; border-top: 0px; border-right: ...
# re: Running ASP.NET in Medium Trust
by chriskuizon May 13, 2009 @ 7:55am
Thanks for this piece of knowledge it will help my project...

I have a class in my asp.net web project written in c# its a binary serialization and de-serialization function. It works find in my local but when I uploaded it in the web server it post me and error.

Security Exception
Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.

Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

This is my code:
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Assert,Unrestricted=true)]  
    public class Click2PaySecurity
    {
         public static string Serialize(string str)
        {
            IFormatter serializer = new BinaryFormatter();
            MemoryStream memStream = new MemoryStream();
            object request = (object)str;

            serializer.Serialize(memStream, request);

            byte[] arrSerialize = memStream.ToArray();

            memStream.Flush();
            memStream.Close();

            return Convert.ToBase64String(arrSerialize);
        }
     }
# re: Running ASP.NET in Medium Trust
by JT December 03, 2009 @ 10:48am
Hi: I have same problem recently while godaddy server made a shift.

I can't put a "login" control in a simple testing aspx page, the error is:

Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

I am using Visual studio 2005, C# to design a website, everything works fine on my local pc and also the old server in godaddy.

Here is what godaddy support told me:

<div style="background-color:Gainsboro;">
I understand you have a question about a security error that you see when running a login control in your hosting plan. Our shared hosting plans operate at Medium Trust.
Trust level refers to permissions set in the Web.config file that dictate what operations can and cannot be performed by Web applications. Our ASP.NET 3.5 shared hosting servers use the default Medium trust level with the addition of OleDbPermission, OdbcPermission, and a less-restrictive WebPermission.
Applications operating under a Medium trust level have no registry access, no access to the Windows event log, and cannot use ReflectionPermission (but can use Reflection). Such applications can communicate only with a defined range of network addresses and file system access is limited to the application's virtual directory hierarchy.
Using a Medium trust level prevents applications from accessing shared system resources and eliminates the potential for application interference. Adding OleDbPermission and OdbcPermission allows applications to use those data providers to access databases. WebPermission is modified to allow outbound http and https traffic.
</div>

Is it possible to modify the "Medium" level to "Full" level?
# re: Running ASP.NET in Medium Trust
by Dann January 02, 2010 @ 10:12am
No, you can't change it. You can simulate (most of the restrictions) by adding <trust level="Medium"/> to your web.config

I'm having the same issue with godaddy right now, but I have changed over to ASP.NET MVC so I dont use any of the standard controls for web forms.
# re: Running ASP.NET in Medium Trust
by omar June 17, 2010 @ 3:00am
hi all i have a problem ,
i have a web site hosted on godaddy , with medium trust level ,
is there any way to call a web service hosted on another server.

i get this error

Request for the permission of type 'System.Net.WebPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

is there any way to make this call work under medium trust level , or i have to change the host to another one with full trust ?

godaddy prevent override web config .
 


West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2014