NonPublic causing a permissions error in reflection on medium trust - asp.net

I must say that so far, I've probably just been darn lucky in that I've never come across the problems associated with a web site running in medium trust. I've only ever developed intranet apps or happened to have use a hosting company that runs in full trust. But the host I've been asked to use for a recent project runs at medium trust so I'm trying to get my app running this. Couple of questions - I develop on Windows XP. Can IIS on there be configured for medium trust (easier to debug) and/or is it a web.config setting? There is a wealth of information on this subject and the learning curve is steep.
Secondly, after a lot of fiddling and removing code, I think this line is causing a permissions error:
For Each FieldInfo As FieldInfo In Type.GetFields(BindingFlags.Instance Or BindingFlags.NonPublic Or BindingFlags.Public)
Can anyone clarify this is a possible candidate, esp. that NonPublic flag? This is copy & pasted code (Coding Horror highlighted the risk of this) so I've never really thought about. I assume the loop is through each field in the object both public and non-public fields - and I've read that protected fields are forbidden with reflection on medium trust.
Cheers, Rob.

Sorry, Reflection with NonPublic is equivalent to full trust.
If somehow I didn't have full trust but had NonPublic reflection, I could leverage that into changing my own code trust level (writable strings, etc).

Yes, a website on XP can be configured to run in medium trust:
In the <system.web> section add the following:
<!-- Case is important: it's Medium, not medium -->
<trust level="Medium"/>
And you're there.
What you may well find is that most hosts run their sites in a slightly elevated "Medium" trust setting, with some additional rights beyond the default - their techies should be able to tell you what differences they have if any.
If you take a look in:
C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG\web_mediumtrust.config
you will see the default settings that are applied.
Reflection is one of the key things that is limited in Medium trust - from the Remarks on the GetFields page:
If the requested field is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns a null reference (Nothing in Visual Basic).
As this has the potential to return null you should probably be checking for null before you start iterating through it, or checking that FieldInfo isn't null/nothing before using it.

I'm going to flag this as closed as nobody has answered and also it was just proving too problematic to try and re-code. The program isn't badly written but uses reflection very heavily for object mapping and to be honest, it's easier to find a hosting company that supports full trust.

Related

Is trying to develop for Medium Trust a lost cause?

I started developing a new MVC app with Entity Framework code-first and Unity for dependency injection. I used EF5 and Unity because I thought they were supposed to work in Medium Trust. However, when I threw the <trust level="Medium" /> tag in my web.config, I started getting Reflection Permission exceptions.
It always seems like whenever I go beyond using built-in things like the System.Data.SqlClient ADO.net stuff I always run into problems in Medium Trust. Auto-Mapper: fail. NHibernate: fail. MySQL: fail. EF5 Code-first: fail. IOC: fail.
Am I just chasing a pipe-dream? Is it possible to achieve a well-architected and testable web application using modern technology that will run in Medium Trust?
In the age of VMs/Virtual Servers/Cloud Computing (and even a few shared hosts that will set your application pools to Full Trust) has anyone found developing for Medium Trust to be worth the effort?
The official position of the ASP.NET team is that Medium Trust is obsolete. This means a few things:
We are automatically resolving all Medium Trust-related bugs reported to us as "won't fix".
We have provided guidance to hosters that they should migrate away from Medium Trust and use proper OS-level isolation instead (http://support.microsoft.com/kb/2698981).
We are removing Medium Trust support from the frameworks we develop (MVC, WebAPI, SignalR, and so on). Going forward, applications built on these frameworks will require Full Trust.
Here, the term "Medium Trust" above to refers to all non-Full Trust configurations in ASP.NET, including use of the built-in trust levels (Minimal, Low, Medium, High) or any custom trust levels.
Edit 26 May 2015: The .NET Framework as a whole has deprecated partial trust, and customers are advised not to rely on it as a security boundary. From MSDN:
Code Access Security in .NET Framework should not be used as a
security boundary with partially trusted code, especially code of
unknown origin. We advise against loading and executing code of
unknown origins without putting alternative security measures in
place.
In general everything that needs Reflection in deep way can't run on Medium Trust
In your case:
Automapper: use reflection to discover matching properties and memory stream to clone them (there is a version around that actually works in medium trust with some limitation)
NHIbernate: use reflection emit to allow Lazy Loading becase the lazy loading in NH is implemented by proxies (to avoid this you can disable Lazy Loading or to use a the NHibernate ProxyGenerator that is an utility that help to pre-create Proxies)
Nhibernate ProxyGenerator
EF: Actually I didn't find big issues with EF and Medium Trust....is don't serialize object with associations or collections
IoC: IoC is the Killer Application of reflection :) you can try AutoFac that works on Medium Trust
AutoFac
In general Medium Trust is a big limitation...but it all depends on what kind of project you are working on.
Consider also to use some Full Trust hosting like Arvixe
Hope this helps

What risk does Reflection pose? (Medium Trust)

The lack of reflection in Medium Trust hosting environments seems to cause a lot of problems for many popular web applications.
Why is ReflectionPermission disabled by default with Medium Trust?
What risk does reflection pose in a shared hosting environment?
For random reference, see MSDN: How to use Medium Trust in ASP.NET 2.0
Reflection allows malicious code to inspect all kinds of secrets: not so much intellectual property (though sure, that too), but data that should be private and secure, like connection strings, passwords, bank account data, etc..
Of course, many programs expose this data as a matter of course through even more-easily compromised vectors, but there's no reason to increase an application's attack surface.
Edited to bring some of the conversation up from the comments:
It's probably true that the real risk is unrestricted file system access, which is what turns reflection into a real danger. If a bad actor can get an assembly (or something that gets compiled into an assembly) into your virtual directory, you're in trouble if they have reflection permission. (Of course if this happens, there are other potential problems as well, but that shouldn't discount this particular vulnerability.)
In a shared hosting environment that's just harder to prevent, though it certainly isn't impossible. Perhaps it's worth cross-posting this question to ServerFault to see what the good folks there have to say.
I've never found anything 'bad' that a user will be able to do using reflection.
People get scared off because you're able to call methods that are marked as private or protected, but from what I've seen, none of them impose any real risk.
Most likely, it's at least in part a sales technique to get you to shell out for (semi-) dedicated hosting :)
I found the following MSDN article on this subject:
Security Considerations for Reflection
This article echo's Jeff's answer:
Reflection provides the ability to
obtain information about types and
members, and to access members.
Accessing nonpublic members could
create a security risk. Therefore,
code that accesses nonpublic members
requires ReflectionPermission with the
appropriate flags.
However, I don't believe this risk can be exploited between customer's hosting accounts. It appears this would only pose a personal risk. For example, using reflection I could explore my own assemblies in my hosting environment. Other customers, however, could not use reflection to explore my assemblies. They could only explore their assemblies.
This might pose a problem for a single web application that involves multiple development teams. One development team could use reflection to explore another development team's assemblies.
However, this is a rare scenario for a shared hosting environment. Most shared hosting web sites involve a very small team who have full access to all the code. In other words, there are no secrets. As long as the assembly is safe from other shared hosting customers, then it's not a problem.
Enabling reflection shouldn't pose any risk for most shared hosting web applications:
<IPermission class="ReflectionPermission" version="1" Flags="RestrictedMemberAccess"/>
Please correct me if I'm wrong.

Running ASP.Net websites in Medium Trust environments

Disclaimer: I have limited ASP.Net skills
I have a couple of websites which I am transferring from my current hosting onto the Mosso hosting service. When I tried transferring one of the websites, I got the error "System.Security.SecurityException: That assembly does not allow partially trusted callers.", which appears to have to do with the fact that Mosso runs on Medium Trust for ASP.Net apps, and the code in the website appears to require full-trust.
Unfortunately, I don't have access to the full source code for the app, and the original developer is not available. Is there any easy workaround to porting these websites? I tried adding in web.config but that didn't work.
I don't think asking Mosso to adjust the security level is an option, because they had refused when I asked them.
Does anybody have any ideas?
Is your assembly strong named? Does it call strong named assemblies?
You should apply the 'AllowPartiallyTrustedCallers` attribute to the Assembly. More information about this attribute is available here.
From the docs:
By default, a strong-named assembly
that does not explicitly apply this
attribute at assembly level to allow
its use by partially trusted code can
be called only by other assemblies
that are granted full trust by
security policy. This restriction is
enforced by placing a LinkDemand for
FullTrust on every public or protected
method on every publicly accessible
class in the assembly. Assemblies that
are intended to be called by partially
trusted code can declare their intent
through the use of the
AllowPartiallyTrustedCallersAttribute.
See this MSDN article for more information.
Edit:
Some information that confirms my suspicions that the APTCA attribute is a possible solution to the problem:
https://support.isqsolutions.com/article.aspx?id=10334
http://bloggingabout.net/blogs/rick/archive/2006/04/07/11929.aspx
Sorry to say but unless they allow you to set the trust level, you could have big issues. You could have a look here.
Professional ASP.NET 2.0 Security, Membership, and Role Management
Almost exactly the same thing happened to me, except the my hosting company changed their trust policy after I a number of websites running on their servers for a couple of years. In the end I had to give up and move to DiscountASP as they overrode <trust level="Full" /> in my congfig file.
Here was my original question.
ASP.NET WebPermission Security Exception
Good luck
I know this is old, but I thought I'd add something to it that might help. Mosso's change to Medium trust caused us some issues as well.
We use BlogEngine.NET and access MySQL for its backend. We had the MySQL dll in our bin directory and that was causing issues with medium trust. Once Mosso added a MySQL dll to the GAC, we were able to use it successfully.
Obviously, I don't know your particular details and what you are trying to do, but if it is related to MySQL, let me know.

ASP.NET - Trust Level = Full?

I recently joined a firm and when analyzing their environment I noticed that the SharePoint web.config had the trust level set to Full. I know this is an absolutely terrible practice and was hoping the stackoverflow community could help me outline the flaws in this decision.
Oh, it appears this decision was made to allow the developers to deploy dlls to the Bin folder without creating CAS policies. Sigh.
Just want to clarify and make matters worse, we are also deploying third party code to this web application.
Todd,
The book, "Programming Microsoft ASP.Net 3.5", by Dino Espisito provides some sound reasoning for not allowing Full Trust in ASP.Net applications.
Among other reasons, Dino states that web applications exposed to the internet are "one of the most hostile environments for computer security you can imagine." And:
a publicly exposed fully trusted
application is a potential platform
for hackers to launch attacks. The
less an application is trusted, the
more secure that application happens
to be.
I'm surprised the StackOverflow community did not outline the problem with Full Trust better. I was hoping for the same thing so I didn't have to go digging through my pile of books to find the answer, lazy me.
If they're ignoring the CAS policies, it might be a tough sell to get them to dial it back, since it makes their job a little harder (or, at least, a little less forgiving). Changing security practices is always tough - like when I had to convince my boss that using the SA accounts in the SQL connection string of our web applications was a bad idea - but hang in there.
Full Trust allows the application to escalate to control of any resource on the computer. While you'd have to have a security flaw in your application to allow these, and they'll probably claim that they've prevented any escalations through astute programming, remind them that in the case that something happens, wouldn't they rather the web application didn't have control of the whole computer? I mean, just in case?
EDIT: I was a little overzealous with my language here. Full Trust would allow the application to control whatever it wants, but only if the Application Pool process has sufficient rights to do it. So if you're running as a limited user with no rights on the server except what the applicaition needs, then I suppose there's essentially no risk to "Full Trust". The reality is that the app pool owner most likely has a number of rights you wouldn't want your app to have (and in some cases, many, many more), so it's much safer to limit app security and grant additional rights needs individually to the application. Thanks for the correction, Barry.
Flaws? Many. But the most damning thing is straight out of the CAS utility:
"...it allows full access to your computer's resources such as the file system or network access, potentially operating outside the control of the security system."
That means, code granted Full Trust can execute any other piece of code (managed or otherwise) on the system, can call across the network to any machine, can do anything in the file system (including changing permissions on restricted files - even OS files).
Most web programmers would say "that's not a problem, it's just my code," which is fine.... until a security flaw crops up in their code that allows an attacker to use it to do unsavoury things. Then previously-granted Full Trust becomes quite unfortunate.
I honestly have found sharepoint to be too restrictive.
Take a look at the following page to see what can and cannot be done based on trust levels
http://msdn.microsoft.com/en-us/library/ms916855.aspx
One problem I ran into immediately was I could not use the Caching Application Block. We were using this application block instead of the ASP.NET caching because we had used an MVP pattern and may open up a win forms application.
Another problem is no reflection, this caused the About page to fail because the version number is pulled from the metadata of the assembly.
I think the best solution is to not use Sharepoint as an application host. I would only use Sharepoint as an application host if the amount of coding was so small that it didn't affect the trust level and it would be less work then setting up a new application. If you are doing some type of coding which is starting to hit the walls of the trust level, move your application into a proper ASP.NET enviroment. But that is just me, and I am biased. Maybe you should try to aim for a Medium trust level compromise.
I use full trust on my development machines.. so I can deploy to the BIN when building new code.
I trust my own code and run it in the GAC on production because creating CAS policies is a pain.
The third party thing would have me worried.. however:
Most 3rd party solutions found on the web also deploy to the GAC (assuming for the same reasons). This gives them all rights regardless of trust level.
Feels like it has more to do with if you trust the 3rd parties or not.. and do you really trust your own developers?
What would a hacker do?
The scenario where a hacker drops an evil dll in your BIN folder I don't see as very realistic.. regardless if he can do that he can also probably change the trust level.

What are the most common, typical things to AVOID coding into my ASP.NET app in order for it to run under Medium Trust on a shared host?

What are the things that Medium Trust stops you from doing? For example, I've already learned that Medium Trust stops you from using System.IO.Path.GetTempPath(). What other things like that?
Here's how to learn about and resolve trust issues.
1) Search your Windows\Microsoft.NET\Framework[YOUR VERSION]\CONFIG folders for the files:
web.config (this is the root config file)
web_mediumtrust.config
web_hightrust.config
2) Change the web.config to say
<trust level="Medium" originUrl="" />
3) Try your ASP.NET app. Mine failed with a permission error.
4) Diff the web_mediumtrust.config and web_hightrust.config in a diff tool, like WinMerge.
5) Copy settings from the high to the medium one at a time and see how they affect your app. In my case, the error message referred to ConfigurationPermission, so it was easy to diagnose.
If you can pin down the precise lines in the web_mediumtrust.config file that are blocking you, then maybe you can share that with your hosting company and have a better chance of working things out.
More documentation here:
http://msdn.microsoft.com/en-us/library/aa302425.aspx
#Oli, my app IS hosted at GoDaddy and I had to do some workarounds in code when I started using Lucene.NET. I had to modify the Lucene.NET source code to not use GetTempPath and System.IO.FileInfo.
Who can be sure? That's why you should develop with a trust level of medium set in your web.config.
<trust level="Full|High|Medium|Low|Minimal" />
Most shared hosts don't use a true medium trust environment because it restricts some things that are just too vital. Others restrict some extra settings for their own anal reasons.
The best thing you can do is ask your host what settings they use for ASPNET. Ask for the specs of the trust level they're using. Find out the memory limits. Once you've got those details you should be able to replicate the scenario at a local level.
If they won't tell you, just set your app to run in medium trust but it (obviously) won't necessarily work if they're using a modified trust level.
Here is some information on setting trust levels in IIS.
In general the only issue I've run into is: If you're pushing assemblies, make sure you allow partially trusted requests (it's an Assembly meta-tag) otherwise you won't be able to use them.
Here's an extract of GoDaddy's Medium Trust information page:
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.
That might not map exactly to what you'll have to work around with your host (unless you're with GoDaddy) but it's a typical example.
Make sure any third party libraries/frameworks (Castle comes to mind) are build (or can be built) in medium trust.
The system.runtime.serialization library is completely unavailable in medium trust.
I coded around this for json serialization/deserialization and found out the hard way. It took a week to get an associate to confirm that medium trust restrictions were to blame. I ended up switching hosting companies as a result.
In medium trust, at least at my host, P/INVOKE calls are unavailable, ie using [DLLImport] to call a COM component is not going to work.
-Edoode

Resources