Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing arbitrary C# code in Sandbox mode?

I am using RazorEngine. I have some dynamic templates which I will bind with a view-model at run-time. My requirement is to run-code in a sandbox. So, only bindings will be allowed. RazorEngine allows me to run code in arbitrary app-domain using,

using (var service = new IsolatedTemplateService(() => appDomain))
{
   return service.Parse(newTemplate, model, null, null);
}

If I run the app-domain with the following permission then it works,

var permissionSet = new PermissionSet(PermissionState.Unrestricted);

But If I run it using these permissions,

var permissionSet = new PermissionSet(PermissionState.None);
permissionSet.AddPermission(new SecurityPermission(PermissionState.Unrestricted));
permissionSet.AddPermission(new ReflectionPermission(PermissionState.Unrestricted));

I will get,

[SecurityException: Request failed.]
   System.AppDomain.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) +0
   RazorEngine.Templating.IsolatedTemplateService..ctor(Language language, Encoding encoding, IAppDomainFactory appDomainFactory) +408
   RazorEngine.Templating.IsolatedTemplateService..ctor(Language language, Encoding encoding, Func`1 appDomainFactory) +73
   RazorEngine.Templating.IsolatedTemplateService..ctor(Func`1 appDomainFactory) +41

Is there any special permission I need to grant?

like image 816
Imran Qadir Baksh - Baloch Avatar asked Nov 10 '22 14:11

Imran Qadir Baksh - Baloch


1 Answers

Unfortunately, the CodeDOM API (which is likely what RazorEngine uses to generate C# code from the syntax tree that the Razor compiler generates) requires full trust. There's not really anything you can do other than strong-name and GAC your assembly so you get full trust. Unfortunately, because it demands the entire "FullTrust" permission set you can't just grant a specific permission.

like image 180
Andrew Stanton-Nurse Avatar answered Nov 14 '22 23:11

Andrew Stanton-Nurse