简体   繁体   English

.Net中的隐藏变量

[英]Hidden variable in closure in .Net

I have some C# code. 我有一些C#代码。 It has some configuration settings that stored as auto property or private fields. 它有一些存储为auto属性或私有字段的配置设置。 In theory the person who uses it can modify private variables via Reflection. 从理论上讲,使用它的人可以通过Reflection修改私有变量。

Is there a way to deny it? 有没有办法否认它? I can use readonly static fields, and then they can't be modified. 我可以使用只读静态字段,然后无法修改它们。 But the reference to that class itself still can be replaced to another one with malicious settings. 但是对该类本身的引用仍然可以被替换为具有恶意设置的另一个类。

I thought about anonymous method and variable in closures. 我想到了闭包中的匿名方法和变量。 But in that case, the link to that delegate still can be replaced. 但在这种情况下,仍然可以替换该代表的链接。

Also I've tried to specify SecurityCriticalAttribute for my fields, as caller may not have FullTrust access, but seems it doesn't verify access for fields. 此外,我已经尝试为我的字段指定SecurityCriticalAttribute,因为调用者可能没有FullTrust访问权限,但似乎它不验证字段的访问权限。 Just for methods\\classes itselfs 仅适用于方法\\类本身

UPDATE UPDATE

I fixed it in such way: 我用这样的方式修复它:

  • Initialize all variables via constructor 通过构造函数初始化所有变量
  • All variables has readonly definition 所有变量都具有只读定义
  • I've added CAS attribute to constructor, so no one without FullTrust can't modify it 我已经将CAS属性添加到构造函数中,因此没有没有FullTrust的人无法修改它

     [PermissionSetAttribute(SecurityAction.Demand, Unrestricted = true)] 

So to update variables, a user needs to create new instance of that class. 因此,要更新变量,用户需要创建该类的新实例。 And then CAS validation will verify caller. 然后CAS验证将验证呼叫者。

I don't like this approach too much, and if you have better way, I'll appreciate it 我不太喜欢这种方法,如果你有更好的方法,我会很感激

Unfortunately, the readonly modifiers on your fields will not prevent post-construction modification via reflection. 不幸的是,字段上的readonly修饰符不会阻止通过反射进行构造后修改。 There is no way to prevent code with private reflection permissions from making modifications to in-memory application state. 没有办法阻止具有私有反射权限的代码修改内存中的应用程序状态。 In fact, ReflectionPermission is considered one of the "dangerous" permissions, for which a grant is essentially analogous to a full trust grant ( http://msdn.microsoft.com/en-us/library/wybyf7a0.aspx ). 实际上, ReflectionPermission被认为是“危险”权限之一,其授权基本上类似于完全信任授权( http://msdn.microsoft.com/en-us/library/wybyf7a0.aspx )。

In other words, you might as well not bother sandboxing at all if you're going to grant private reflection permissions in the sandbox... 换句话说,如果您要在沙箱中授予私有反射权限,您可能根本不打扰沙盒...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM