Troskyvs
Troskyvs

Reputation: 8047

C# appDomain failed to work for "CodeAccessPermission" reason, why?

I'm trying C# appdomain on win10 using vs2017, I've got this quick example. I've a directory called c:\git, I can create files under this directory with C# app, but when I tried app domain, it throws exception, my code as below:

class UseAppDomain
{
    public static void Test()
    {
        var perm = new PermissionSet(PermissionState.None);
        perm.AddPermission(
            new SecurityPermission(SecurityPermissionFlag.Execution));
        perm.AddPermission(
            new FileIOPermission(FileIOPermissionAccess.NoAccess, @"c:\"));

        var setup = new AppDomainSetup();
        setup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
        AppDomain secureDomain = AppDomain.CreateDomain("secure", null, setup, perm);

        ThirdParty third = new ThirdParty();

        Type thirdParty = typeof(ThirdParty);
        secureDomain.
            CreateInstanceAndUnwrap(thirdParty.Assembly.FullName,
                thirdParty.FullName);  //exception!!!!!!!!!!
        AppDomain.Unload(secureDomain);
    }
}

[Serializable]
class ThirdParty
{
    public ThirdParty()
    {
        Console.WriteLine("3p loadling");
        System.IO.File.Create(@"c:\git\test.txt");//Try to create file failed!
    }
}

The exception message is:

Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
at System.Security.CodeAccessSecurityEngine.Check(CodeAccessPermission cap, StackCrawlMark& stackMark)
at System.Security.CodeAccessPermission.Demand()
... ...

I don't quite get what problem my program has, how to fix this issue?

Thanks.

Upvotes: 1

Views: 173

Answers (1)

György Kőszeg
György Kőszeg

Reputation: 18013

If you want to create files from a partially trusted domain you need to use FileIOPermissionAccess.Write instead. Or FileIOPermissionAccess.AllAccess if you want to allow also reading and directory content discovery.

Side note:

You use the CreateInstanceAndUnwrap for a simple serializable class, which is not derived from MarshalByRefObject. Its effect is that the class will be serialized in the created domain and a copy will be deserialized in the main domain but as you omit the return value it will be dropped anyway.

So either do not unwrap the created object or derive it from the MarshalByRefObject class so its public members can be accessed from the main domain via remoting.

Upvotes: 2

Related Questions