首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >中国科学院IronPython太极拳

中国科学院IronPython太极拳
EN

Stack Overflow用户
提问于 2012-12-20 03:25:02
回答 1查看 910关注 0票数 3

为了编写脚本,我试图将IronPython集成到C#应用程序中。我还希望脚本在一组安全策略下运行,这些策略限制脚本对文件系统/网络/敏感系统资源的访问。

研究表明,最流行的方法是使用CAS。这非常有效,它不允许用户使用套接字、访问文件系统等。但是,当我试图为光盘注入可交互的变量时,每次访问特定参数时,我都会得到一个安全异常。这只发生在我在程序集中定义的变量中。如果我使用标准的.NET类型(比如字典),它就能正常工作。

我的守则:

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Security.Policy;
using System.Security.Permissions;
using System.Security;
using System.IO;
using Microsoft.Scripting.Hosting;
using IronPython.Hosting;
using System.Runtime.Remoting;
using System.Net;

namespace python_in_appdomain
{
    [Serializable]
    public class Whatever
    {
        public int i;
        public Whatever(int i)
        {
            this.i = i;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Remoting();
        }

        public static void Remoting()
        {
            AppDomainSetup setup = new AppDomainSetup();
            Assembly thisAssembly = Assembly.GetExecutingAssembly();
            setup.ApplicationBase = Path.GetDirectoryName(thisAssembly.Location);

            AssemblyName name = typeof(Program).Assembly.GetName();
            StrongName sn = new StrongName(
                new StrongNamePublicKeyBlob(name.GetPublicKey()),
                name.Name,
                name.Version
            );

            PermissionSet pset = new PermissionSet(PermissionState.None);
            pset.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
            pset.AddPermission(new ReflectionPermission(PermissionState.Unrestricted));

            setup.PartialTrustVisibleAssemblies = new[] { sn.Name + ", PublicKey=" + sn.PublicKey.ToString() };
            AppDomain domain = AppDomain.CreateDomain("Sandbox", AppDomain.CurrentDomain.Evidence, setup, pset, sn);

            String script = @"
d.Add('hello', 1)
w.i = 5
";

            Whatever w = new Whatever(4);
            Dictionary<string, int> d = new Dictionary<string,int>();

            ScriptRuntime py = Python.CreateRuntime(domain);
            ScriptEngine engine = py.GetEngine("py");
            ScriptScope scope = engine.CreateScope();
            scope.SetVariable("w", w);
            scope.SetVariable("d", d);

            int result;
            Console.WriteLine(w.i);
            d.TryGetValue("hello", out result);
            Console.WriteLine(result);
            Console.WriteLine("-----");

            try
            {
                engine.Execute(script, scope);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.ToString());
            }

            w = scope.GetVariable<Whatever>("w");
            d = scope.GetVariable<Dictionary<string,int>>("d");

            Console.WriteLine("-----");
            Console.WriteLine(w.i);
            d.TryGetValue("hello", out result);
            Console.WriteLine(result);

        }
    }
}

在第55行中注释掉"w.i=5“会使程序在受限的安全设置下正常执行。在第47行上将PermissionState设置为无限制,允许脚本的两行正常执行。以下是我收到的错误消息:

代码语言:javascript
复制
System.Security.SecurityException: Request failed.
   at System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(IRuntimeMethodInfo method)
   at System.Reflection.Emit.DynamicMethod.CreateDelegate(Type delegateType, Object target)
   at System.Dynamic.Utils.TypeExtensions.CreateDelegate(MethodInfo methodInfo, Type delegateType, Object target)
   at System.Linq.Expressions.Compiler.LambdaCompiler.CreateDelegate()
   at System.Linq.Expressions.Compiler.LambdaCompiler.Compile(LambdaExpression lambda, DebugInfoGenerator debugInfoGenerator)
   at System.Linq.Expressions.Expression`1.Compile()
   at System.Runtime.CompilerServices.CallSiteBinder.BindCore[T](CallSite`1 site, Object[] args)
   at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
   at Microsoft.Scripting.Interpreter.DynamicInstruction`3.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run2[T0,T1,TRet](T0 arg0, T1 arg1)
   at IronPython.Compiler.PythonScriptCode.RunWorker(CodeContext ctx)
   at IronPython.Compiler.PythonScriptCode.Run(Scope scope)
   at IronPython.Compiler.RuntimeScriptCode.InvokeTarget(Scope scope)
   at IronPython.Compiler.RuntimeScriptCode.Run(Scope scope)
   at Microsoft.Scripting.SourceUnit.Execute(Scope scope, ErrorSink errorSink)
   at Microsoft.Scripting.Hosting.ScriptSource.Execute(ScriptScope scope)
   at Microsoft.Scripting.Hosting.ScriptEngine.Execute(String expression, ScriptScope scope)
   at Microsoft.Scripting.Hosting.ScriptEngine.Execute(String expression, ScriptScope scope)
   at python_in_appdomain.Program.Remoting() in C:\Users\dave\Documents\Visual Studio 2010\Projects\IronPythonTest\IronPythonTest\Program.cs:line 7
6
The action that failed was:
Demand
The type of the first permission that failed was:
System.Security.PermissionSet
The demand was for:
<PermissionSet class="System.Security.PermissionSet"
version="1"
Unrestricted="true"/>

The granted set of the failing assembly was:
<PermissionSet class="System.Security.PermissionSet"
version="1">
<IPermission class="System.Security.Permissions.ReflectionPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Unrestricted="true"/>
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Flags="Execution"/>
</PermissionSet>

The assembly or AppDomain that failed was:
Microsoft.Dynamic, Version=1.1.0.20, Culture=neutral, PublicKeyToken=7f709c5b713576e1
The method that caused the failure was:
Int32 Run(Microsoft.Scripting.Interpreter.InterpretedFrame)
The Zone of the assembly that failed was:
Internet
The Url of the assembly that failed was:
file:///C:/Users/dave/Documents/Visual Studio 2010/Projects/IronPythonTest/IronPythonTest/bin/Debug/Microsoft.Dynamic.DLL

Unhandled Exception: System.Security.SecurityException: Request failed.
   at System.Delegate.BindToMethodInfo(Object target, IRuntimeMethodInfo method, RuntimeType methodType, DelegateBindingFlags flags)
   at System.Delegate.CreateDelegate(Type type, MethodInfo method, Boolean throwOnBindFailure)
   at System.Dynamic.Utils.TypeExtensions.CreateDelegate(MethodInfo methodInfo, Type delegateType)
   at System.Runtime.CompilerServices.CallSite`1.MakeUpdateDelegate()
   at System.Runtime.CompilerServices.CallSite`1.GetUpdateDelegate(T& addr)
   at System.Runtime.CompilerServices.CallSite`1.GetUpdateDelegate()
   at System.Runtime.CompilerServices.CallSite`1.Create(CallSiteBinder binder)
   at System.Func`2.Invoke(T arg)
   at Microsoft.Scripting.Runtime.DynamicOperations.GetOrCreateSite[T](CallSiteBinder siteBinder, Func`2 factory)
   at Microsoft.Scripting.Runtime.DynamicOperations.GetOrCreateSite[T1,TResult](CallSiteBinder siteBinder)
   at Microsoft.Scripting.Runtime.DynamicOperations.ConvertTo[T](Object obj)
   at IronPython.Runtime.PythonContext.ScopeGetVariable[T](Scope scope, String name)
   at Microsoft.Scripting.Hosting.ScriptScope.GetVariable[T](String name)
   at Microsoft.Scripting.Hosting.ScriptScope.GetVariable[T](String name)
   at python_in_appdomain.Program.Remoting() in C:\Users\dave\Documents\Visual Studio 2010\Projects\IronPythonTest\IronPythonTest\Program.cs:line 8
3
   at python_in_appdomain.Program.Main(String[] args) in C:\Users\dave\Documents\Visual Studio 2010\Projects\IronPythonTest\IronPythonTest\Program.
cs:line 31

这个错误是惊人的直截了当的。它说,它期望完全不受限制地进入这类行动。有办法绕过这件事吗?为什么字典起作用,而我的变量不起作用?有没有办法让IronPython像字典一样对待我的变量?我错过了什么很明显的东西吗?

非常感谢你的帮助。

更新12/21/2012

我一直在胡闹,想出了一个有效的解决方案。创建这样的AppDomain (具有相同的权限对象)允许一切正常工作。

代码语言:javascript
复制
AppDomainSetup setup = new AppDomainSetup();
            setup.ApplicationBase = System.Environment.CurrentDirectory;
AppDomain domain = AppDomain.CreateDomain("IPyEngine", new Evidence(), setup, pset);

我不能说我完全理解为什么,虽然我可以看到我没有提供我的程序集的证据,我也没有在信任列表中添加任何程序集。我不想把这个标记为答案,直到我确定我没有做任何非常愚蠢的事情。

EN

回答 1

Stack Overflow用户

发布于 2012-12-21 16:48:44

这是可疑的:

代码语言:javascript
复制
The Zone of the assembly that failed was:
Internet
The Url of the assembly that failed was:
file:///C:/Users/dave/Documents/Visual Studio 2010/Projects/IronPythonTest/IronPythonTest/bin/Debug/Microsoft.Dynamic.DLL

我想知道该文件是否有区域标识符。您能检查文件属性和如有必要,解除阻塞吗?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13964828

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档