Last week I showed how to create an AppDomain with a limited set of permissions. I also presented an easy way to create a StrongNameMembershipCondition. Now I'll put the two together to make an enhanced version of the sandboxed AppDomain.
Why create a new version? The version I presented last time works wonderfully if you're going to create the AppDomain and then call AppDomain.ExecuteAssembly to run the untrusted code in it. However, especially in plugin scenarios, a more common approach is to create a MarshalByRefObject in your application that you load into the new AppDomain, and then have this proxy object invoke the untrusted assembly. This scenario won't work with the last version of CreateRestrictedDomain, since all code loaded into the AppDomain will be granted the same limited set of permissions.
This can be easily rectified by modifying CreateRestrictedDomain to take a second parameter, which is an extra code group to add to the policy:
Now, in order to enable the MarshalByRefObject scenario, we just need to make a code group that grants FullTrust to the assembly that's creating the AppDomain. This is easily done with the CreateStrongMembershipCondition method:
Using the above snippet creates an AppDomain policy similar to: