[英]How can I avoid accessing private members of a class using Reflection?
I was reading Security Considerations for Reflection and I saw the following line: 我正在阅读反思的安全注意事项 ,我看到以下行:
Transparent code cannot use reflection to access security-critical members, even if the code is fully trusted.
即使代码完全受信任,透明代码也无法使用反射来访问安全关键成员。 A MethodAccessException, FieldAccessException, or TypeAccessException is thrown.
抛出MethodAccessException,FieldAccessException或TypeAccessException。
So, I've written a test program: 所以,我写了一个测试程序:
Class Library: 班级图书馆:
namespace ClassLibrary
{
public class Foo
{
[SecurityCritical] private int X;
}
}
Test program: 测试程序:
using ClassLibrary;
namespace ReflectionSecurityTest
{
class Program
{
static void Main(string[] args)
{
Foo f = new Foo();
var flags = BindingFlags.Instance | BindingFlags.NonPublic;
var field = f.GetType().GetField("X", flags);
field.SetValue(f,15);
Console.WriteLine(field.GetValue(f));
}
}
}
I would expect to see an exception but instead I see 15
in the Console.The question is why ? 我希望看到一个例外,但我在控制台看到
15
。问题是为什么 ? Did I misunderstand what SecurityCritical
does or did I do something wrong? 我是否误解了
SecurityCritical
做了什么或做了什么我做错了什么?
The bullet point below that states: 下面的要点指出:
- Code that is running with partial trust is treated as transparent.
使用部分信任运行的代码被视为透明。
Application code that is run from the command line runs with full trust.
从命令行运行的应用程序代码以完全信任的方式运行。 As long as it is not marked as transparent, it can use reflection to access security-critical members.
只要它没有标记为透明,它就可以使用反射来访问安全关键成员。 When the same code is run with partial trust (for example, in a sandboxed application domain) the assembly's trust level determines whether it can access security-critical code: If the assembly has a strong name and is installed in the global assembly cache, it is a trusted assembly and can call security-critical members.
当使用部分信任运行相同的代码时(例如,在沙盒应用程序域中),程序集的信任级别确定它是否可以访问安全关键代码:如果程序集具有强名称并安装在全局程序集缓存中,则是一个值得信赖的程序集,可以调用安全关键成员。 If it is not trusted, it becomes transparent even though it was not marked as transparent, and it cannot access security-critical members.
如果它不受信任,即使它没有标记为透明,它也会变得透明,并且它无法访问安全关键成员。
So to answer the question from your title: 所以要回答你标题中的问题:
How can I avoid accessing private members of a class using Reflection?
如何使用Reflection避免访问类的私有成员?
You can't, if you can't sandbox the code performing the reflection. 你不能,如果你不能沙箱执行反射的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.