Security per .net type - sandbox

Aug 21, 2012 at 11:26 AM
Edited Aug 21, 2012 at 11:28 AM

I'm trying to achieve sandboxed environment. I want Jint script to be able to access only explicitly specified types and classes I experimented with security as described in:

http://jint.codeplex.com/discussions/74935

Problem is that it assumes permission for all classes and allows to fine tune operations. Most of classes I don't want Jint script to access does not have any security attributes. Some time ago Sam asked for something similar but that stayed unanswered:

http://jint.codeplex.com/discussions/310772

As I couldn't find suitable solution I looked as source code and made some modifications:

Added property to JintEngine.cs:

public Func<Type, bool> AllowClrType
{
	get { return visitor.AllowClrType; }
	set { visitor.AllowClrType = value; }
}

Added property to ExecutionVisitor.cs:

public Func<Type, bool> AllowClrType { get; set; }

Then created method on ExecutionVisitor.cs:

private void EnsureClrTypeAllowed(Type t)
{
	if (t != null && AllowClrType != null && !AllowClrType(t))
	{
		throw new SecurityException("Use of Clr Type '" + t.FullName + "' is not allowed");
	}
}

and called it from ExecutionVisitor:Visit methods:

public void Visit(MemberExpression expression) {
	// (...)
	// Try to evaluate a CLR type
	if (Result == JsUndefined.Instance && typeFullname.Length > 0) {
		EnsureClrAllowed();

		Type type = typeResolver.ResolveType(typeFullname.ToString());

		EnsureClrTypeAllowed(type);

		(...)
	}
}

and

public void Visit(Indexer indexer) {

	// (...)
	indexer.Index.Accept(this);
	if (target.IsClr)
	{
		EnsureClrAllowed();
		EnsureClrTypeAllowed(target.Value.GetType());
	}
	// (...)
}

Now you can add it to engine like that:

engine.AllowClrType = x => x.FullName.StartsWith("MySandboxNamespace") || x.FullName.StartsWith("System.Collections.Generic.List");

This gives great flexibility on what types are available in script. I think it may be useful to other people trying to achieve fine grained sandbox effect, feel free to embed that in your project if you think this code is suitable.