My application should be scriptable for users in C #, but the user script should work in a restricted AppDomain to prevent accidentally damaging scripts, but I cannot get it to work, and since my understanding of AppDomains is sadly limited, I cannot say why .
Currently, this solution is based on this answer https://stackoverflow.com/a/212618/
This is a model of my situation (everything except Script.cs living in a strongly named assembly). Sorry for the wall of code, I could not condense the problem.
class Program { static void Main(string[] args) {
Sandbox Class:
public class Sandbox : MarshalByRefObject { const string BaseDirectory = "Untrusted"; const string DomainName = "Sandbox"; public static Sandbox Create() { var setup = new AppDomainSetup() { ApplicationBase = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, BaseDirectory), ApplicationName = DomainName, DisallowBindingRedirects = true, DisallowCodeDownload = true, DisallowPublisherPolicy = true }; var permissions = new PermissionSet(PermissionState.None); permissions.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess)); permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); var domain = AppDomain.CreateDomain(DomainName, null, setup, permissions, typeof(Sandbox).Assembly.Evidence.GetHostEvidence<StrongName>()); return (Sandbox)Activator.CreateInstanceFrom(domain, typeof(Sandbox).Assembly.ManifestModule.FullyQualifiedName, typeof(Sandbox).FullName).Unwrap(); } public object CreateInstance(string assemblyPath, string typeName) { new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, assemblyPath).Assert(); var assembly = Assembly.LoadFile(assemblyPath); CodeAccessPermission.RevertAssert(); Type type = assembly.GetType(typeName);
Loaded Script:
using System; public class Script : IExecutable { public void Execute() { Console.WriteLine("Boo"); } }
In CreateInstance of SandBox I always get null in the marked line. I tried various forms of naming, including reading the type name (or fuly qualified name) from results.CompiledAssembly using reflection. What am I doing wrong here?
source share