Running a runtime compiled C# script in a sandbox AppDomain - c#

My application should be scriptable by the users in C#, but the user's script should run in a restricted AppDomain to prevent scripts accidentally causing damage, but I can't really get it to work, and since my understanding of AppDomains is sadly limited, I can't really tell why.
The solution I am currently trying is based on this answer https://stackoverflow.com/a/5998886/276070.
This is a model of my situation (everything except Script.cs residing in a strongly named assembly). Please excuse the wall of code, I could not condense the problem any further.
class Program
{
static void Main(string[] args)
{
// Compile the script
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
CompilerParameters parameters = new CompilerParameters()
{
GenerateExecutable = false,
OutputAssembly = System.IO.Path.GetTempFileName() + ".dll",
};
parameters.ReferencedAssemblies.Add(Assembly.GetEntryAssembly().Location);
CompilerResults results = codeProvider.CompileAssemblyFromFile(parameters, "Script.cs");
// ... here error checks happen ....//
var sandbox = Sandbox.Create();
var script = (IExecutable)sandbox.CreateInstance(results.PathToAssembly, "Script");
if(script != null)
script.Execute();
}
}
public interface IExecutable
{
void Execute();
}
The 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); // ****** I get null here
if (type == null)
return null;
return Activator.CreateInstance(type);
}
}
The loaded Script:
using System;
public class Script : IExecutable
{
public void Execute()
{
Console.WriteLine("Boo");
}
}
In CreateInstance of SandBox, I always get null at the marked line. I tried various forms of giving the name, including reading the type name (or fuly qualified name) from results.CompiledAssembly using reflection.
What am I doing wrong here?

The first thing that i'll check is if there are compilation errors (i had several headache caused by this issues)
The second idea is about the resolution of assemblies. I always add as a security check an event handler for AppDomain.CurrentDomain.AssemblyResolve, where i seek on my known path for the missing Assemblies. When the not found assembly is the one i just compiled i add a static reference to it and return it.
What I usually do is this:
Create the new Assembly on file system with the compiler
Load its content with the File.ReadAllBytes
Load the dll with the Assembly.Load in the AppDomain in which i will be using the object
Add the AppDomain.CurrentDomain.AssemblyResolve event
Just in case (since i use this a lot) i created a small library to accomply this kind of things
The code and documentation are here: Kendar Expression Builder
While the nuget package is here: Nuget Sharp Template

Related

Load Assembly into a new app domain but not CurrentDomain

So my problem revolves around saving memory.
In essence I need to load an assembly in to a separate app domain other than the main/current domain, check for types within that assembly, and then unload the new domain when done.
Currently my solution is as follows:
AppDomain NewDomain = AppDomain.CreateDomain("newdomain");
foreach(string path in dllPaths) //string list of dll paths
{
byte[] dllBytes = File.ReadAllBytes(dll);
NewDomain.Load(dllBytes); //offending line
}
DoStuffWithNewDomain();
AppDomain.Unload(NewDomain);
The NewDomain.Load line seems to load the assembly into the new domain but also into the current domain of my program.
I used this link as a reference - http://www.csharp411.com/how-to-load-a-net-assembly-into-a-separate-appdomain-so-you-can-unload-it/
Many thanks :)
As mentioned already, loading the assembly from bytes can only happen for the current app domain.
Here is one way to context-switch to make your target app domain the current one, using the DoCallBack method on the app domain (http://msdn.microsoft.com/en-us/library/system.appdomain.docallback%28v=vs.110%29.aspx).
After the assemblies are loaded you can then use the same method to inspect the assemblies and types of the new app domain, and create instances as necessary, before unloading it.
class Program
{
static void Main(string[] args)
{
AppDomain newDomain = AppDomain.CreateDomain("NewDomain");
List<string> dllPaths = new List<string>() { #"c:\dev\taglib-sharp.dll" };
foreach (string dll in dllPaths)
{
AppDomainAsmLoader asmLoad = new AppDomainAsmLoader(File.ReadAllBytes(dll));
newDomain.DoCallBack(new CrossAppDomainDelegate(asmLoad.LoadAsm));
}
newDomain.DoCallBack(new CrossAppDomainDelegate(DoWorkWithAppDomain));
AppDomain.Unload(newDomain);
Console.ReadKey();
}
public static void DoWorkWithAppDomain()
{
Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly asm in asms)
{
Type[] types = asm.GetTypes();
foreach (Type type in types)
{
Console.WriteLine("Found the type: {0}", type.FullName);
}
}
}
[Serializable]
public class AppDomainAsmLoader
{
private byte[] AsmData;
public AppDomainAsmLoader(byte[] data)
{
AsmData = data;
}
public void LoadAsm()
{
Assembly asm = Assembly.Load(AsmData);
}
}
}
As Erik suggested, you need to use CreateInstanceAndWrap. Here's an example I did in VB a while back...
Private Function GetCoupler() As IBatchCoupler
Dim CouplerProxy As IBatchCoupler = Nothing
Try
Dim DomainSetupInfo As AppDomainSetup = New AppDomainSetup()
DomainSetupInfo.ConfigurationFile = Path.Combine(mFilePath, "web.config")
DomainSetupInfo.ApplicationBase = Path.Combine(mFilePath, "bin")
DomainSetupInfo.ShadowCopyFiles = "true"
Dim domain As AppDomain = AppDomain.CreateDomain("CoolDomain", AppDomain.CurrentDomain.Evidence, DomainSetupInfo)
'Create remote object in new appDomain via the coupler interface
'to avoid loading the design library into the calling application's primary appDomain
CouplerProxy = domain.CreateInstanceFromAndUnwrap(Path.Combine(DomainSetupInfo.ApplicationBase, "Design.dll"), "BigApplication.Design.BatchCoupler")
Catch ex As Exception
ThisLogger.Error(ex)
End Try
Return CouplerProxy
End Function

Add new cs files on-the-fly to load on my running application?

I have a command handler which basically works like this:
ControlList.Handlers[CommandType.MyCommandComesHere].Handle(data);
Handlers is a Dictionary<CommandType, ICommandHandler> and CommandType is a enum.
Handle by its turn would lead it to this:
using System;
using log4net;
namespace My_Application
{
public class MyCommand : ICommandHandler
{
private static readonly ILog Logger = LogManager.GetLogger(typeof(MyCommand));
public void Handle(Events data)
{
Console.WriteLine("I can load cs files on the fly yay!!");
}
}
}
My question is how can I make so my application would compile and let me use that cs file while its running?
Any simple example of this would be greatly appreciated but not required as long as I can get some pointers as to what I need to look for as I am not even sure what do I need to make this happen.
To put it simple I am currently trying to understand how could I load a cs file into my application that is already compiled and is currently running.
Using CodeDOM, you need to first create a compiler provider. (You might want to set GenerateExecutable to false and GenerateInMemory to true for your purposes.)
var csc = new CSharpCodeProvider();
var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = true;
Then, you can compile the assembly using CompileAssemblyFromSource and get the CompilerResults returned from it. From this returned object, get a reference to the generated assembly, using its CompiledAssembly property.
var results = csc.CompileAssemblyFromSource(parameters, "contents of the .cs file");
var assembly = results.CompiledAssembly;
Then you can use reflection to create instances from that assembly and call methods on them.
var instance = assembly.CreateInstance("MyCommand");
// etc...
Alternatively, if you're only interested in short code snippets, it might be worth it to use Roslyn instead. You need to create a ScriptEngine first.
var engine = new ScriptEngine();
Then you can just Execute strings on it - or Execute<T> if you're confident that the expression in the string returns a type assignable to T.
var myObject = engine.Execute("1+1");
var myInt = engine.Execute<int>("1+1");
It's definitely more immediate, so it's worth looking into if it serves your purpose.
I have looked for different ways to achieve this and found cs script library lightweight and usable. Here is code snippet how I use it. It runs cs code within app domain so it presumes, that the cs script being compiled comes form trusted source.
using CSScriptLibrary;
using csscript;
using System.CodeDom.Compiler;
using System.Reflection;
//Method example - variable script contains cs code
//This is used to compile cs to DLL and save DLL to a defined location
public Assembly GetAssembly(string script, string assemblyFileName)
{
Assembly assembly;
CSScript.CacheEnabled = true;
try
{
bool debugBuild = false;
#if DEBUG
debugBuild = true;
#endif
if (assemblyFileName == null)
assembly = CSScript.LoadCode(script, null);
else
assembly = CSScript.LoadCode(script, assemblyFileName, debugBuild, null);
return assembly;
}
catch (CompilerException e)
{
//Handle compiler exceptions
}
}
/// <summary>
/// Runs the code either form script text or precompiled DLL
/// </summary>
public void Run(string script)
{
try
{
string tmpPath = GetPathToDLLs(); //Path, where you store precompiled DLLs
string assemblyFileName;
Assembly assembly = null;
if (Directory.Exists(tmpPath))
{
assemblyFileName = Path.Combine(tmpPath, GetExamScriptFileName(exam));
if (File.Exists(assemblyFileName))
{
try
{
assembly = Assembly.LoadFrom(assemblyFileName); //Načtení bez kompilace
}
catch (Exception exAssemblyLoad)
{
Tools.LogError(exAssemblyLoad.Message);
assembly = null;
}
}
}
else
assemblyFileName = null;
//If assembly not found, compile it form script string
if (assembly ==null)
assembly = GetAssembly(script, assemblyFileName);
AsmHelper asmHelper = new AsmHelper(assembly);
//This is how I use the compiled assembly - it depends on your actual code
ICalculateScript calcScript = (ICalculateScript)asmHelper.CreateObject(GetExamScriptClassName(exam));
cex = calcScript.Calculate(this, exam);
Debug.Print("***** Calculated {0} ****", exam.ZV.ZkouskaVzorkuID);
}
catch (Exception e)
{
//handle exceptions
}
}

ShadowCopy assemblies

I have a problem and I really have no clue why it doesn't work. I've read a lot of tutorials (also on stackoverflow) and still nothing.
My goal is to use reflection on some .dll files (they are not use by any program yet) and get inheritance types, methods, constructors etc. Everything works correctly but the problem is that dlls are locked and cannot be deleted until I turn off the program. This is part of my code where I try to resolve the problem.
var apds = new AppDomainSetup();
apds.ApplicationName = "MyAssemblies";
Evidence adevidence = AppDomain.CurrentDomain.Evidence;
AppDomain apd = AppDomain.CreateDomain("newdomain", adevidence, apds);
apd.AppendPrivatePath("Assemblies");
apd.SetCachePath("C:\\Cache");
apd.SetShadowCopyFiles();
foreach (var type in apd.Load(AssemblyName.GetAssemblyName(file.Path)).GetTypes())
{
foreach (var inherits in GetInheritanceHierarchy(type))
{ //rest is ok
I know I use some deprecated methods but it's one of the try. Dlls are succesfully copied into cache directory but they seems to be loaded into current domain too.
Where's the problem?
Thanks in advance.
I modified my code to and use Loader class but i still have locked files.
class Loader : MarshalByRefObject
{
public Assembly assembly;
public void LoadAssembly(string path)
{
assembly = Assembly.Load(AssemblyName.GetAssemblyName(path));
}
public Types[] getTypes()
{
return assembly.getTypes();
}
}
//...
if (file.Type == ".dll")
{
var apds = new AppDomainSetup
{
ApplicationName = "MyAssemblies",
ApplicationBase = Path,
ShadowCopyFiles = "true",
ShadowCopyDirectories = Path
};
AppDomain apd = AppDomain.CreateDomain("newdomain", null, apds);
Loader loader = (Loader)apd.CreateInstanceAndUnwrap(typeof(Loader).Assembly.FullName, typeof(Loader).FullName);
loader.LoadAssembly(file.Path);
foreach (var type in loader.getTypes())
{
foreach (var inherits in GetInheritanceHierarchy(type))
//...
Any idea?
You can load your assembly in the following way.
var types = Assembly.Load(File.ReadAllBytes("YourAssembly.dll")).GetTypes();
Now you can extract the types from the assembly, and you can delete the assembly while the application is still running.

Understanding AppDomains and strong naming

I'm trying to create a sandbox for where I can load plugins. I create the AppDomain and specify a StrongName for my host assembly, and my understanding is that any code running in the assembly that is strongly named runs in Full Trust. However this seems not the case.
Example,
static void Main(string[] args)
{
var permissions = new PermissionSet(PermissionState.None);
var setup = new AppDomainSetup()
{
ApplicationBase = "C:\\Temporary\\Sandbox"
};
var domain = AppDomain.CreateDomain("Sandbox",
null,
setup,
permissions,
typeof (PluginHost).Assembly.Evidence.GetHostEvidence<StrongName>());
var handle = Activator.CreateInstanceFrom(domain,
typeof (PluginHost).Assembly.ManifestModule.FullyQualifiedName,
typeof (PluginHost).FullName);
var host = (PluginHost) handle.Unwrap();
host.RunPlugin();
}
PluginHost (defined in the same assembly I'm strong naming),
public class PluginHost : MarshalByRefObject
{
public void RunPlugin()
{
File.ReadAllText("C:\\Passwords.txt");
var asm = Assembly.LoadFile(#"C:\Plugins\UnsafePlugin.dll");
var t = asm.GetType("UnsafePlugin.FooPlugin");
object plugin = Activator.CreateInstance(t);
plugin.GetType().GetMethod("Run").Invoke(plugin, null);
}
}
And this is the plugin (residing in an external assembly)
public class FooPlugin
{
public void Run()
{
File.ReadAllText("C:\\Passwords.txt");
}
}
I am strong naming the assembly containing PluginHost and therefore I expect to be able to read my passwords file from PluginHost and not from FooPlugin but the code throws a SecurityException when reading the file (in PluginHost).
My understanding from the MSDN documentation on the subject was that the fourth parameter containing StrongName-instances will give those assemblies full trust in the application domain.
From the documentation:
"An array of strong names representing assemblies to be considered
fully trusted in the new application domain."
Since I just proved myself wrong - how am I supposed to get this to work? Why am I not in full trust even though I've passed my StrongName to AppDomain.Create?

C# fully trusted assembly with SecuritySafeCritical funciton still throwing SecurityExceptions

I'm trying to create a sandboxed AppDomain for loading extensions/plugins. I have a MarshalByRefObject that in instantiate inside the appdomain to load the dll. I'm getting SecurityExceptions when trying to load the dll and I can't figure out how to get around them while still limiting what the third party code can do. All my projects are .net 4.
The InDomainLoader class is in a fully trusted domain, the method is marked SecuritySafeCritical. From everything I've read, I think this should work.
Here is my Loader class that creates the AppDomain and jumps into it:
public class Loader
{
public void Load(string dll, string typeName)
{
Log.PrintSecurity();
// Create new AppDomain
var setup = AppDomain.CurrentDomain.SetupInformation;
var permissions = new PermissionSet(null);
permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
var strongname = typeof(InDomainLoader).Assembly.Evidence.GetHostEvidence<StrongName>();
var strongname2 = typeof(IPlugin).Assembly.Evidence.GetHostEvidence<StrongName>();
AppDomain domain = AppDomain.CreateDomain("plugin", null, setup, permissions, strongname, strongname2);
// Create instance
var loader = (InDomainLoader)domain.CreateInstanceAndUnwrap(
typeof (InDomainLoader).Assembly.FullName, typeof (InDomainLoader).FullName);
// Jump into domain
loader.Load(dll, typeName);
}
}
And here's the bootstrap loader that runs in the domain:
public class InDomainLoader : MarshalByRefObject
{
[SecuritySafeCritical]
public void Load(string dll, string typeName)
{
Log.PrintSecurity();
var assembly = Assembly.LoadFrom(dll); // <!-- SecurityException!
var pluginType = assembly.GetType(typeName);
var demoRepository = new DemoRepository();
var plugin = (IPlugin)Activator.CreateInstance(pluginType, demoRepository);
Console.WriteLine(plugin.Run());
}
}
Some logging statements tell me that the assembly's IsFullyTrusted is true and the method has both IsSecurityCritical and IsSecuritySafeCritical set to true, IsSecurityTransparent is false.
I zipped up the whole project to http://davidhogue.com/files/PluginLoader.zip in case that makes this easier.
If anyone has any ideas, I'd be very grateful. I seem to be stuck at a dead end here.
Well for a start you probably shouldn't be marking the function as SecuritySafeCritical as that implies untrusted callers can call you, which you probably don't really want (not that it should be a major issue).
As for your problem the issue is that by default you still don't run with any special permissions, the normal easy way to do the assembly loading is you create your own AppDomainSetup and point it's ApplicationBase at a Plugin directory of some kind (which isn't a bad idea in general), you can then use the normal Assembly.Load("AssemblyName") to load out of the base. However if you must load an arbitrary file then you need to assert FileIOPermission for the plugin dll (full path), i.e.
private Assembly LoadAssemblyFromFile(string file)
{
FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.AllAccess, file);
perm.Assert();
return Assembly.LoadFile(file);
}

Categories

Resources