How can I compile C# user code in a sandbox [duplicate] - c#

Here is the reason why this question was being asked: www.devplusplus.com/Tests/CSharp/Hello_World.
While similar questions were asked before, the many answers online have several issues:
This must be done ".Net 4.0" style, not legacy mode.
The assembly is in-memory and will only be in memory, it cannot be written to the file system.
I would like to limit all access to the file-system, network, etc.
Something like this:
var evidence = new Evidence();
evidence.AddHostEvidence(new Zone(SecurityZone.Internet));
var permissionSet = SecurityManager.GetStandardSandbox(evidence);
So far, I cannot find a way to create an AppDomain and load an assembly THAT IS NOT ON THE FILE SYSTEM, but rather in RAM.
Again, the reasons why the other solutions didn't work are identified above: 1. Many were for pre-4.0, and 2. Many relied on the ".Load" method pointing to the file system.
Answer 2: I have an assembly reference due to it being generated by the CSharpCodeProvider class, so if you know a way to turn that into a byte array, that would be perfect!
Sample Code to Show The Security Flaw
var provider = new CSharpCodeProvider(new Dictionary<String, String>
{ { "CompilerVersion", "v4.0" } });
var compilerparams = new CompilerParameters
{ GenerateExecutable = false, GenerateInMemory = true, };
var compilerResults = provider.CompileAssemblyFromSource(compilerparams,
string_Of_Code_From_A_User);
var instanceOfSomeClass = compilerResults.CompiledAssembly
.CreateInstance(className);
// The 'DoSomething' method can write to the file system and I don't like that!
instanceOfSomeClass.GetType().GetMethod("DoSomething")
.Invoke(instanceOfSomeClass, null);
So why can't I just save the assembly to a file first?
For two reasons:
This code is on a shared web server with limited permissions to the file-system itself.
This code may need to be run potentially thousands of times, and I don't want 1,000 dlls, even temporarily.

OK, first things first: there's no actual way to use the CSharpCodeProvider to do dynamic compilation of C# source entirely in memory. There are methods that seem to support that functionality, but since the C# compiler is a native executable that cannot run in-process, the source string is saved to a temporary file, the compiler is invoked on that file, and then the resulting assembly is saved to disk and then loaded for you using Assembly.Load.
Secondly, as you've discovered, you should be able to use the Compile method from within the AppDomain to load the assembly and give it the desired permissions. I ran into this same unusual behavior, and after a lot of digging found that it was a bug in the framework. I filed an issue report for it on MS Connect.
Since the framework is already writing to the filesystem anyway, the workaround is to have the assembly written to a temporary file and then loaded as needed. When you load it however, you'll need to temporarily assert permissions in the AppDomain, since you've disallowed access to the file system. Here's an example snippet of that:
new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, assemblyPath).Assert();
var assembly = Assembly.LoadFile(assemblyPath);
CodeAccessPermission.RevertAssert();
From there you can use the assembly and reflection to invoke your method. Note that this method lets you hoist the compilation process outside of the sandboxed AppDomain, which is a plus in my opinion.
For reference, here is my Sandbox class created to facilitate the launching of script assemblies in a nice clean separate AppDomain that has limited permissions and can be easily unloaded when necessary:
class Sandbox : MarshalByRefObject
{
const string BaseDirectory = "Untrusted";
const string DomainName = "Sandbox";
public 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 string Execute(string assemblyPath, string scriptType, string method, params object[] parameters)
{
new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, assemblyPath).Assert();
var assembly = Assembly.LoadFile(assemblyPath);
CodeAccessPermission.RevertAssert();
Type type = assembly.GetType(scriptType);
if (type == null)
return null;
var instance = Activator.CreateInstance(type);
return string.Format("{0}", type.GetMethod(method).Invoke(instance, parameters));
}
}
Quick note: if you use this method to supply security evidence for the new AppDomain, you need to sign your assembly to give it a strong name.
Note that this works fine when run in process, but if you really want a bullet-proof script environment, you need to go one step further and isolate the script in a separate process to ensure that scripts that do malicious (or just stupid) things like stack overflows, fork bombs, and out of memory situations don't bring down the whole application process. I can give you more information on doing that if you need it.

Related

WF4.5- Expression Activity type 'CSharpValue`1' requires compilation in order to run

Background
What I'm trying to do is to have a scoped variable of one of my models in the xaml.
In my workflow project "MyProject.Workflows" I have created model classes, code activities and Xaml files. They are all under same namespace. In another project ("Engine"), I load and execute these workflows.
To load the workflows in the "Engine", I use ActivityXamlServices with ActivityXamlServicesSettings including CompileExpressions = true.
When loading the ActivityXamlServices, I use a XamlXmlReader with XamlXmlReaderSettings where I actually point to the "MyProject.Workflows" dll.
Since Both these projects are in the same solution I actually referred MyProject.Workflows in the "Engine".
Because Earlier, they were in different solutions, So when I tried to do this It gave me It cant find the "MyProject.Workflows" dll even though I point it in the XamlXmlReaderSettings.
Then I tried to load the dll to the app domain and then it worked.But I did not want to deal with App Domains so I decided to get both projects under one solution so I can refer the "MyProject.Workflows" in the "Engine".
Issue:
If I use one of those models inside of the Xaml as an expression like "Assign Activity" the Workflow isn't getting compiled when I try to execute this.
For example if I use this in an "Assign" activity having a scoped variable of type MyObject
Newtonsoft.Json.JsonConvert.DeserializeObject<MyProject.Workflows.Models.MyObject>(inputString);
I will get the below error message when I run the workflow.
NotSupportedException:'Expression Activity type 'CSharpValue`1' requires compilation in order to run. Please ensure that the workflow has been compiled.
If I remove these objects and just deal with strings or ints, it works fine.
Things I found in my research:
I found this was a bug in .Net Framework 4.5. But Im using 4.6
Even though I used CompileExpressions = true , I tried this compile method I found. But did not change a thing.
private static void Compile(DynamicActivity dynamicActivity)
{
TextExpressionCompilerSettings settings = new TextExpressionCompilerSettings
{
Activity = dynamicActivity,
Language = "C#",
ActivityName = dynamicActivity.Name.Split('.').Last() + "_CompiledExpressionRoot",
ActivityNamespace = string.Join(".", dynamicActivity.Name.Split('.').Reverse().Skip(1).Reverse()),
RootNamespace = null,
GenerateAsPartialClass = false,
AlwaysGenerateSource = true,
};
TextExpressionCompilerResults results =
new TextExpressionCompiler(settings).Compile();
if (results.HasErrors)
{
throw new Exception("Compilation failed.");
}
ICompiledExpressionRoot compiledExpressionRoot =
Activator.CreateInstance(results.ResultType,
new object[] { dynamicActivity }) as ICompiledExpressionRoot;
CompiledExpressionInvoker.SetCompiledExpressionRootForImplementation(
dynamicActivity, compiledExpressionRoot);
}
I read that some people faced this problem and they had to actually move the models to a diffrent namespace. I did that too. Didn't fix the problem.
My Xaml file has this entry added at the top.
xmlns:local="clr-namespace:MyProject.Workflows.Models"
Can someone please help me to get through this?

AppDomain.Execute Assembly gets stuck

I'm having issues with just this command ExecuteAssembly
I had my app running with pipes streaming data and I switched to wcf with netnamed pipes.
This has nothing to do with the issue.
The server, once starting, performs some operations, one of them is executing the assembly that runs the client and connects to the server.
CODE:
String modulePath = (String)path;
AppDomainSetup objDomainSetup = new AppDomainSetup() { ApplicationBase = Path.GetDirectoryName(modulePath) };
string moduleConfigPath = String.Format("{0}.config", modulePath);
if (File.Exists(moduleConfigPath))
{
// This is important... in case the loding module has a configuration file.
objDomainSetup.ConfigurationFile = moduleConfigPath;
}
//We give the new app domain the same permission its parent has.
System.Security.Policy.Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
System.Security.Policy.Evidence objEvidence = new System.Security.Policy.Evidence(baseEvidence);
objModuleDomain = AppDomain.CreateDomain(ChannelName, objEvidence, objDomainSetup);
objModuleDomain.ExecuteAssembly(modulePath);
I checked the paths, everything and everything seems correct and the .exe pointed from the path is executed.
But ExecuteAssembly gets stuck there and the following statements are not executed.
Any guesses?
Thanks
AppDomain.ExecuteAssembly() executes the assembly and finishes when the assemble .exe finishes.
I had a Sleep(Infinite) that make the assembly not to finish.

Roslyn slow startup time

I've noticed that the startup time for Roslyn parsing/compilation is a fairly significant one-time cost. EDIT: I am using the Roslyn CTP MSI (the assembly is in the GAC). Is this expected? Is there any workaround?
Running the code below takes almost the same amount of time with 1 iteration (~3 seconds) as with 300 iterations (~3 seconds).
[Test]
public void Test()
{
var iters = 300;
foreach (var i in Enumerable.Range(0, iters))
{
// Parse the source file using Roslyn
SyntaxTree syntaxTree = SyntaxTree.ParseText(#"public class Foo" + i + #" { public void Exec() { } }");
// Add all the references we need for the compilation
var references = new List<MetadataReference>();
references.Add(new MetadataFileReference(typeof(int).Assembly.Location));
var compilationOptions = new CompilationOptions(outputKind: OutputKind.DynamicallyLinkedLibrary);
// Note: using a fixed assembly name, which doesn't matter as long as we don't expect cross references of generated assemblies
var compilation = Compilation.Create("SomeAssemblyName", compilationOptions, new[] {syntaxTree}, references);
// Generate the assembly into a memory stream
var memStream = new MemoryStream();
// if we comment out from this line and down, the runtime drops to ~.5 seconds
EmitResult emitResult = compilation.Emit(memStream);
var asm = Assembly.Load(memStream.GetBuffer());
var type = asm.GetTypes().Single(t => t.Name == "Foo" + i);
}
}
I think one issue is using a memory stream, instead you should try using a dynamic module and ModuleBuilder instead. Overall the code is executing faster but still has a heavier first load scenario. I'm pretty new to Roslyn myself so I'm not sure why this is faster but here is the changed code.
var iters = 300;
foreach (var i in Enumerable.Range(0, iters))
{
// Parse the source file using Roslyn
SyntaxTree syntaxTree = SyntaxTree.ParseText(#"public class Foo" + i + #" { public void Exec() { } }");
// Add all the references we need for the compilation
var references = new List<MetadataReference>();
references.Add(new MetadataFileReference(typeof(int).Assembly.Location));
var compilationOptions = new CompilationOptions(outputKind: OutputKind.DynamicallyLinkedLibrary);
// Note: using a fixed assembly name, which doesn't matter as long as we don't expect cross references of generated assemblies
var compilation = Compilation.Create("SomeAssemblyName", compilationOptions, new[] { syntaxTree }, references);
var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new System.Reflection.AssemblyName("CustomerA"),
System.Reflection.Emit.AssemblyBuilderAccess.RunAndCollect);
var moduleBuilder = assemblyBuilder.DefineDynamicModule("MyModule");
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Start();
// if we comment out from this line and down, the runtime drops to ~.5 seconds
var emitResult = compilation.Emit(moduleBuilder);
watch.Stop();
System.Diagnostics.Debug.WriteLine(watch.ElapsedMilliseconds);
if (emitResult.Diagnostics.LongCount() == 0)
{
var type = moduleBuilder.GetTypes().Single(t => t.Name == "Foo" + i);
System.Diagnostics.Debug.Write(type != null);
}
}
By using this technique the compilation took just 96 milliseconds, on subsequent iterations it takes around 3 - 15ms. So I think you could be right in terms of the first load scenario adding some overhead.
Sorry I can't explain why it's faster! I'm just researching Roslyn myself and will do more digging later tonight to see if I can find any more evidence of what the ModuleBuilder provides over the memorystream.
I have came across the same issue using the Microsoft.CodeDom.Providers.DotNetCompilerPlatform package of ASP.net. It turns out this package launches csc.exe which uses VBCSCompiler.exe as a compilation server. By default the VBCSCompiler.exe server lives for 10 seconds and its boot time is of about 3 seconds. This explains why it takes about the same time to run your code once or multiple times. It seems like Microsoft is using this server as well in Visual Studio to avoid paying an extra boot time each time you run a compilation.
With the this package You can monitor your processes and will find a command line which looks like csc.exe /keepalive:10
The nice part is that if this server stays alive (even between two sessions of your application), you can get a fast compilation all the times.
Unfortunately, the Roslyn package is not really customizable and the easiest way I found to change this keepalive constant is to use the reflection to set non public variables value. On my side, I defined it to a full day as it always keep the same server even if I close and restart my application.
/// <summary>
/// Force the compiler to live for an entire day to avoid paying for the boot time of the compiler.
/// </summary>
private static void SetCompilerServerTimeToLive(CSharpCodeProvider codeProvider, TimeSpan timeToLive)
{
const BindingFlags privateField = BindingFlags.NonPublic | BindingFlags.Instance;
var compilerSettingField = typeof(CSharpCodeProvider).GetField("_compilerSettings", privateField);
var compilerSettings = compilerSettingField.GetValue(codeProvider);
var timeToLiveField = compilerSettings.GetType().GetField("_compilerServerTimeToLive", privateField);
timeToLiveField.SetValue(compilerSettings, (int)timeToLive.TotalSeconds);
}
When you call Compilation.Emit() it is the first time you actually need metadata, so the metadata file access occurs. After that, its cached. Though that should not account for 3secs just for mscorlib.
tldr: NGEN-ing roslyn dlls shaves off 1.5s off of the initial compilation/execution time (in my case from ~2s to ~0.5s)
Investigated this just now.
With a brand new console application and a nuget reference to Microsoft.CodeAnalysis.Scripting, the initial execution of a small snippet ("1+2") took about 2s, while subsequent ones were a lot faster - around 80ms (still a bit high for my taste but that's a different topic).
Perfview revealed that the delay was predominantly due to jitting:
Microsoft.CodeAnalysis.CSharp.dll: 941ms (3,205 methods jitted)
Microsoft.CodeAnalysis.dll 426ms (1,600 methods jitted)
I used ngen on Microsoft.CodeAnalysis.CSharp.dll (making sure to specify the /ExeCondig:MyApplication.exe because of the binding redirects in app.config) and got a nice performance improvement, the first-execution time fell to ~580ms.
This of course would need to be done on end user machines. In my case, I'm using Wix as the installer for my software and there's support for NGEN-ing files at install time.

How do i execute 3rd party code in a sandbox [duplicate]

Here is the reason why this question was being asked: www.devplusplus.com/Tests/CSharp/Hello_World.
While similar questions were asked before, the many answers online have several issues:
This must be done ".Net 4.0" style, not legacy mode.
The assembly is in-memory and will only be in memory, it cannot be written to the file system.
I would like to limit all access to the file-system, network, etc.
Something like this:
var evidence = new Evidence();
evidence.AddHostEvidence(new Zone(SecurityZone.Internet));
var permissionSet = SecurityManager.GetStandardSandbox(evidence);
So far, I cannot find a way to create an AppDomain and load an assembly THAT IS NOT ON THE FILE SYSTEM, but rather in RAM.
Again, the reasons why the other solutions didn't work are identified above: 1. Many were for pre-4.0, and 2. Many relied on the ".Load" method pointing to the file system.
Answer 2: I have an assembly reference due to it being generated by the CSharpCodeProvider class, so if you know a way to turn that into a byte array, that would be perfect!
Sample Code to Show The Security Flaw
var provider = new CSharpCodeProvider(new Dictionary<String, String>
{ { "CompilerVersion", "v4.0" } });
var compilerparams = new CompilerParameters
{ GenerateExecutable = false, GenerateInMemory = true, };
var compilerResults = provider.CompileAssemblyFromSource(compilerparams,
string_Of_Code_From_A_User);
var instanceOfSomeClass = compilerResults.CompiledAssembly
.CreateInstance(className);
// The 'DoSomething' method can write to the file system and I don't like that!
instanceOfSomeClass.GetType().GetMethod("DoSomething")
.Invoke(instanceOfSomeClass, null);
So why can't I just save the assembly to a file first?
For two reasons:
This code is on a shared web server with limited permissions to the file-system itself.
This code may need to be run potentially thousands of times, and I don't want 1,000 dlls, even temporarily.
OK, first things first: there's no actual way to use the CSharpCodeProvider to do dynamic compilation of C# source entirely in memory. There are methods that seem to support that functionality, but since the C# compiler is a native executable that cannot run in-process, the source string is saved to a temporary file, the compiler is invoked on that file, and then the resulting assembly is saved to disk and then loaded for you using Assembly.Load.
Secondly, as you've discovered, you should be able to use the Compile method from within the AppDomain to load the assembly and give it the desired permissions. I ran into this same unusual behavior, and after a lot of digging found that it was a bug in the framework. I filed an issue report for it on MS Connect.
Since the framework is already writing to the filesystem anyway, the workaround is to have the assembly written to a temporary file and then loaded as needed. When you load it however, you'll need to temporarily assert permissions in the AppDomain, since you've disallowed access to the file system. Here's an example snippet of that:
new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, assemblyPath).Assert();
var assembly = Assembly.LoadFile(assemblyPath);
CodeAccessPermission.RevertAssert();
From there you can use the assembly and reflection to invoke your method. Note that this method lets you hoist the compilation process outside of the sandboxed AppDomain, which is a plus in my opinion.
For reference, here is my Sandbox class created to facilitate the launching of script assemblies in a nice clean separate AppDomain that has limited permissions and can be easily unloaded when necessary:
class Sandbox : MarshalByRefObject
{
const string BaseDirectory = "Untrusted";
const string DomainName = "Sandbox";
public 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 string Execute(string assemblyPath, string scriptType, string method, params object[] parameters)
{
new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, assemblyPath).Assert();
var assembly = Assembly.LoadFile(assemblyPath);
CodeAccessPermission.RevertAssert();
Type type = assembly.GetType(scriptType);
if (type == null)
return null;
var instance = Activator.CreateInstance(type);
return string.Format("{0}", type.GetMethod(method).Invoke(instance, parameters));
}
}
Quick note: if you use this method to supply security evidence for the new AppDomain, you need to sign your assembly to give it a strong name.
Note that this works fine when run in process, but if you really want a bullet-proof script environment, you need to go one step further and isolate the script in a separate process to ensure that scripts that do malicious (or just stupid) things like stack overflows, fork bombs, and out of memory situations don't bring down the whole application process. I can give you more information on doing that if you need it.

In .NET 4.0, how do I 'sandbox' an in-memory assembly and execute a method?

Here is the reason why this question was being asked: www.devplusplus.com/Tests/CSharp/Hello_World.
While similar questions were asked before, the many answers online have several issues:
This must be done ".Net 4.0" style, not legacy mode.
The assembly is in-memory and will only be in memory, it cannot be written to the file system.
I would like to limit all access to the file-system, network, etc.
Something like this:
var evidence = new Evidence();
evidence.AddHostEvidence(new Zone(SecurityZone.Internet));
var permissionSet = SecurityManager.GetStandardSandbox(evidence);
So far, I cannot find a way to create an AppDomain and load an assembly THAT IS NOT ON THE FILE SYSTEM, but rather in RAM.
Again, the reasons why the other solutions didn't work are identified above: 1. Many were for pre-4.0, and 2. Many relied on the ".Load" method pointing to the file system.
Answer 2: I have an assembly reference due to it being generated by the CSharpCodeProvider class, so if you know a way to turn that into a byte array, that would be perfect!
Sample Code to Show The Security Flaw
var provider = new CSharpCodeProvider(new Dictionary<String, String>
{ { "CompilerVersion", "v4.0" } });
var compilerparams = new CompilerParameters
{ GenerateExecutable = false, GenerateInMemory = true, };
var compilerResults = provider.CompileAssemblyFromSource(compilerparams,
string_Of_Code_From_A_User);
var instanceOfSomeClass = compilerResults.CompiledAssembly
.CreateInstance(className);
// The 'DoSomething' method can write to the file system and I don't like that!
instanceOfSomeClass.GetType().GetMethod("DoSomething")
.Invoke(instanceOfSomeClass, null);
So why can't I just save the assembly to a file first?
For two reasons:
This code is on a shared web server with limited permissions to the file-system itself.
This code may need to be run potentially thousands of times, and I don't want 1,000 dlls, even temporarily.
OK, first things first: there's no actual way to use the CSharpCodeProvider to do dynamic compilation of C# source entirely in memory. There are methods that seem to support that functionality, but since the C# compiler is a native executable that cannot run in-process, the source string is saved to a temporary file, the compiler is invoked on that file, and then the resulting assembly is saved to disk and then loaded for you using Assembly.Load.
Secondly, as you've discovered, you should be able to use the Compile method from within the AppDomain to load the assembly and give it the desired permissions. I ran into this same unusual behavior, and after a lot of digging found that it was a bug in the framework. I filed an issue report for it on MS Connect.
Since the framework is already writing to the filesystem anyway, the workaround is to have the assembly written to a temporary file and then loaded as needed. When you load it however, you'll need to temporarily assert permissions in the AppDomain, since you've disallowed access to the file system. Here's an example snippet of that:
new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, assemblyPath).Assert();
var assembly = Assembly.LoadFile(assemblyPath);
CodeAccessPermission.RevertAssert();
From there you can use the assembly and reflection to invoke your method. Note that this method lets you hoist the compilation process outside of the sandboxed AppDomain, which is a plus in my opinion.
For reference, here is my Sandbox class created to facilitate the launching of script assemblies in a nice clean separate AppDomain that has limited permissions and can be easily unloaded when necessary:
class Sandbox : MarshalByRefObject
{
const string BaseDirectory = "Untrusted";
const string DomainName = "Sandbox";
public 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 string Execute(string assemblyPath, string scriptType, string method, params object[] parameters)
{
new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, assemblyPath).Assert();
var assembly = Assembly.LoadFile(assemblyPath);
CodeAccessPermission.RevertAssert();
Type type = assembly.GetType(scriptType);
if (type == null)
return null;
var instance = Activator.CreateInstance(type);
return string.Format("{0}", type.GetMethod(method).Invoke(instance, parameters));
}
}
Quick note: if you use this method to supply security evidence for the new AppDomain, you need to sign your assembly to give it a strong name.
Note that this works fine when run in process, but if you really want a bullet-proof script environment, you need to go one step further and isolate the script in a separate process to ensure that scripts that do malicious (or just stupid) things like stack overflows, fork bombs, and out of memory situations don't bring down the whole application process. I can give you more information on doing that if you need it.

Categories

Resources