问题
In a shell application, I need to be able to load and execute other .NET assemblies at runtime, but without giving them full trust. Essentially, I want to limit them (the loaded assemblies) from touching any system resources (threading, networking, etc), with the only exception being isolated storage. However, assemblies which are from "me" need to be executed with full trust.
I've been considering Code Access Security, but I'm not quite sure it's what I should use.
How would you go about this?
回答1:
CAS is pretty much what you need here. More specifically, you want to load the assembly in its own Application Domain:
var myEvidence = new Evidence(new object[] {SecurityZone.Internet});
var newDomain = AppDomain.CreateDomain("InternetDomain");
myDomain.Load("MyUntrustedAssembly.dll", myEvidence);
myDomain.CreateInstanceAndUnwrap("MyUntrustedAssembly","MyUntrustedObjectType");
//do your work with the untrusted assembly/type
AppDomain.Unload(myDomain);
Read up on Application Domains, the various zones, and the default permission sets assigned to them. Internet is the most restrictive of the system-defined zones/permission sets available in which assemblies can still actually execute (there's also the Restricted zone; assemblies falling into this zone cannot run). You can use the .NET Configuration tool to create permission sets and define the conditions (evidence) that code must satisfy to be granted the permission set.
来源:https://stackoverflow.com/questions/3807069/net-security-limiting-runtime-loaded-assemblies-from-accessing-certain-apis