English 中文(简体)
Sand Boxed AppDomain的安全观
原标题:SecurityException in Sandboxed AppDomain

I m 试图使用C#作为描述性语言,使用CSharpCodeProvider(使用VS2010和NET4.0)。 我希望这些文字在经过最少许可的有限审校进行。 目前,我只想在AppDomain(电话:CreateInstanceAnd Unwrap())上调一个班子,但我却成为例外。 这里有些简化的法典转载了例外情况:

using System;
using System.Collections.Generic;
using Microsoft.CSharp;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Security;
using System.Security.Policy;
using System.Security.Permissions;
using System.Reflection;
using System.Runtime.Remoting;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // set permissions
            PermissionSet permissions = new PermissionSet(PermissionState.None);
            permissions.AddPermission(new SecurityPermission( SecurityPermissionFlag.Execution));

            AppDomainSetup adSetup = new AppDomainSetup();
            adSetup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;

            //Create a list of fully trusted assemblies
            Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies();
            List<StrongName> sns = new List<StrongName>();
            for (int x = 0; x < asms.Length; x++)
            {
                StrongName sn = asms[x].Evidence.GetHostEvidence<StrongName>();
                if (sn != null && sns.Contains(sn) == false)
                    sns.Add(sn);
            }
            //this includes: "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"            

            AppDomain domain = AppDomain.CreateDomain("NewAppDomain", AppDomain.CurrentDomain.Evidence, adSetup, permissions);//, sns);//, sn4, sn, sn2, sn3);
            try
            {
                String asmName = Assembly.GetExecutingAssembly().FullName;
                String typeName = typeof(ConsoleApp.ScriptRunner).FullName;
                //Throws exception here
                ScriptRunner scriptRunner = domain.CreateInstanceAndUnwrap(asmName, typeName) as ScriptRunner;
            }
            catch (SecurityException se)
            {
                System.Diagnostics.Debug.WriteLine(se.Message);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
    }

    public class ScriptRunner : MarshalByRefObject
    {      
        public ScriptRunner()
        {
            //A breakpoint placed here is never reached.
            CompilerParameters param;
            param = new CompilerParameters();
            param.CompilerOptions = "";
            param.GenerateExecutable = false;
            param.GenerateInMemory = true;
            param.IncludeDebugInformation = false;

            // C# compiler
            CSharpCodeProvider codeProvider = new CSharpCodeProvider();  

            CompilerResults results = codeProvider.CompileAssemblyFromFile(param, "Danger.cs");           
        }
    }
}

这一例外正在从雕塑中提取,它是一个System.Reflection.TargetInventionException,内有System. Security.Exception。 例外:

System.Reflection.TargetInvocationException was unhandled
  Message=Exception has been thrown by the target of an invocation.
  Source=mscorlib
  StackTrace:
       at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
       at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache)
       at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)
       at System.Activator.CreateInstance(Type type, Boolean nonPublic)
       at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
       at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
       at System.Activator.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo, StackCrawlMark& stackMark)
       at System.Activator.CreateInstance(String assemblyName, String typeName)
       at System.AppDomain.CreateInstance(String assemblyName, String typeName)
       at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName)
       at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName)
       at ConsoleApp.Program.Main(String[] args) in C:Documents and SettingsNaultyCSmy documentsvisual studio 2010ProjectsConsoleApplication4ConsoleApplication4Program.cs:line 46
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.Security.SecurityException
       Message=Request failed.
       Source=ConsoleApplication4
       GrantedSet=<PermissionSet class="System.Security.PermissionSet"
version="1">
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Flags="Execution"/>
</PermissionSet>

       PermissionState=<PermissionSet class="System.Security.PermissionSet"
version="1"
Unrestricted="true"/>

       RefusedSet=""
       Url=file:///C:/Documents and Settings/NaultyCS/my documents/visual studio 2010/Projects/ConsoleApplication4/ConsoleApplication4/bin/Debug/ConsoleApplication4.EXE
       StackTrace:
            at ConsoleApp.ScriptRunner..ctor()
       InnerException: 

因此,在我看来,调子要求完全信任。 我补充说,它是一个完全相信的大会,但它没有效果。 如果我确定允许不受限制的话,上述法典就有效:

PermissionSet permissions = new PermissionSet(PermissionState.Unrestricted);

但我想限制上诉人。 我在这里做了什么错误?

最佳回答

晚间休息。 如下。 我在视力演播室接受测试。 在一旁,我个人并不喜欢建筑商中的“地质”,因为真正的错误往往很少隐藏。 以下步骤从构造者转向新的方法。

  1. Ensure your Console App has a StrongName / Signed.
  2. 将斜体变量作为最后参数列入“应用数据”。 创建网站。 联系组织要求你科索尔阿普完全相信。

    AppDomain domain = AppDomain.CreateDomain("NewAppDomain", AppDomain.CurrentDomain.Evidence, adSetup, permissions, sns.ToArray());
    
  3. Change the asmName to use the Full File Path to your assembly.

    String asmName = Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName;
    
  4. 删除“创建” 安瓦拉布呼吁以下两条法典:

    var handle = Activator.CreateInstanceFrom(domain, asmName, typeName);
    var scriptRunner = (ScriptRunner)handle.Unwrap();
    
  5. 将所有你的法典从核查者翻译成新的方法,如“标准”。

  6. 添加“起步”方法。

    scriptRunner.Start();
    
  7. Add the FileIOPermission to read your Danger.cs file.

    permissions.AddPermission(new FileIOPermission(PermissionState.None) { AllFiles = FileIOPermissionAccess.Read });
    
问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签