Search code examples
c#securityrelative-pathappdomainappdomainsetup

Code in Partially-Trusted AppDomain throws System.Security.Permissions.FileIOPermission on Relative Path resolve


I am adding a Sandbox layer to a framework that I have created.

The main concept is that the framework loads plugin-like DLLs.

On the plugin load, I create an AppDomain to isolate the execution and set the ApplicationBase of the AppDomain to the DLL's directory and set the access to full.

Now the problem is that, inside the plugins, although the base path is correctly set, if the code tries to load a file using it's relative path, .net will raise System.Security.Permissions.FileIOPermission exception.

However the same file will be easily loaded using the absolute path.

I have tried different Security Permissions sets but no one fixes the relative path loading issue.

Here is the code that I am using:

//AppDomain creation

string directory = Path.GetDirectoryName(assemblyPath);

PermissionSet permissionSet = new PermissionSet(PermissionState.None);

permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.AllAccess, directory));

permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Infrastructure));

AppDomainSetup appDomainSetup = new AppDomainSetup
{
   ApplicationBase = directory,

   PrivateBinPath = directory,

   PrivateBinPathProbe = directory
};

AppDomain appDomain = AppDomain.CreateDomain("Sandbox", null, appDomainSetup, permissionSet);


//Code running inside the AppDomain

string path = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,Path.Combine("Resources","Image.jpg"))); //Works fine

string path = Path.GetFullPath(Path.Combine("Resources","Image.jpg")); //Throws System.Security.Permissions.FileIOPermission exception

I am aware that I can just go for the first approach but I want the framework to be as flexible as possible, therefore I prefer to find a workaround for this issue.

Can anyone help with any solution or suggestions please?


Solution

  • Never mind,

    I found the answer to my question myself.

    I had to set the Environment.CurrentDirectory for AppDomain to correct value.