Can an appdomain be restricted to one directory?

Deadly 提交于 2020-01-13 09:22:26

问题


I am developing a plugin host. The plugins should have as little trust as they need, however I want to have the possibility for a plugin to read and write files.

Can the AppDomain where the assembly will be loaded be restricted to have access to only one directory for reading and writing?

Other options and ways to go about this are also appreciated like for example easy ways to stream file data from the host to the plugin (reading) and from the plugin to the host (writing).

If its relevant: I am using the MAF infrastructure for the plugins. http://msdn.microsoft.com/en-us/library/bb384200.aspx


回答1:


namespace ConsoleApplication
{
    #region Imports

    using System;
    using System.IO;
    using System.Security;
    using System.Security.Permissions;

    #endregion

    public class Plugin : MarshalByRefObject
    {        
        public string TestRead(string path)
        {
            try
            {
                File.ReadAllBytes(path);
                return "Done";
            }
            catch (SecurityException)
            {
                return "Access Denied";
            }
        }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            var setup = new AppDomainSetup();

            setup.ApplicationBase = 
                AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

            var perm = new PermissionSet(PermissionState.None);

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

            perm.AddPermission(
                new FileIOPermission(
                    FileIOPermissionAccess.Read, "c:\\public\\"));

            var pluginDomain = 
                AppDomain.CreateDomain("PluginDomain", null, setup, perm);

            var plugin = 
                pluginDomain.CreateInstanceAndUnwrap(
                    typeof(Plugin).Assembly.FullName,
                    typeof(Plugin).FullName) as Plugin;

            Console.WriteLine(plugin.TestRead("c:\\public\\test.txt"));
            Console.WriteLine(plugin.TestRead("c:\\secret\\test.txt"));
            Console.ReadKey();
        }
    }
}


来源:https://stackoverflow.com/questions/2869951/can-an-appdomain-be-restricted-to-one-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!