c#SecurityException中的沙盒ironpython
本文关键字:ironpython c#SecurityException | 更新日期: 2023-09-27 18:21:53
好吧,这就是我的
private static AppDomain CreateSandbox()
{
var permissions = new PermissionSet(PermissionState.None);
permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
permissions.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read| FileIOPermissionAccess.PathDiscovery, AppDomain.CurrentDomain.BaseDirectory));
var appinfo = new AppDomainSetup();
appinfo.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
return AppDomain.CreateDomain("Scripting sandbox", null, appinfo, permissions, fullTrustAssembly);
}
当我试图加载一些损坏的python代码时
try
{
var src = engine.CreateScriptSourceFromString(s.Python, SourceCodeKind.Statements);
src.Execute(ActionsScope);
}
catch (Exception e)
{
ExceptionOperations eo = engine.GetService<ExceptionOperations>();
string error = eo.FormatException(e);
Debug.WriteLine(error);
}
这给了我一个SecurityException
,而不是让我从代码中看到实际的异常。如果我设置PermissionSet(PermissionState.Unrestricted)
,它可以正常工作。
关于我需要什么权限才能捕捉这些该死的错误,有什么想法吗?
System.Security.SecurityException was caught
Message=Request failed.
Source=Microsoft.Scripting
GrantedSet=<PermissionSet class="System.Security.PermissionSet"
version="1">
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Read="F:'Programming'OCTGN'octgnFX'Octgn'bin'ReleaseMode with Debug'"
PathDiscovery="F:'Programming'OCTGN'octgnFX'Octgn'bin'ReleaseMode with Debug'"/>
<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:///F:/Programming/OCTGN/octgnFX/Octgn/bin/ReleaseMode with Debug/Microsoft.Scripting.DLL
StackTrace:
at Microsoft.Scripting.SyntaxErrorException.GetObjectData(SerializationInfo info, StreamingContext context)
at System.Runtime.Serialization.ObjectCloneHelper.GetObjectData(Object serObj, String& typeName, String& assemName, String[]& fieldNames, Object[]& fieldValues)
at Microsoft.Scripting.Hosting.ScriptSource.Execute(ScriptScope scope)
at Octgn.Scripting.Engine.LoadScripts() in F:'Programming'OCTGN'octgnFX'Octgn'Scripting'Engine.cs:line 58
InnerException:
根据堆栈跟踪,您的代码中存在语法错误,因此Python运行时抛出SyntaxErrorException
。该异常未被捕获,因此必须跨appdomain边界对其进行序列化。
我认为现在的问题是SyntaxErrorException
的方法GetObjectData()
被标记为[SecurityCritical]
,这意味着它只能由完全可信的代码调用。
您可能需要尝试ObjectHandle ExecuteAndWrap(ScriptScope作用域,out ObjectHandle异常)重载。当您刚刚捕获异常时,它会在抛出时从远程域封送到您的域,然后在调用FormatException时返回到远程域。在封送回您的应用程序域时,似乎发生了异常。
如果您调用ExecuteAndWrap重载,那么您将只获得结果和可能的异常的句柄,并避免序列化-然后您可以将句柄传回ExceptionOperations.FormatException.