Protect value from change with reflection?

here is the problem, I am writing a small third-party library. In this library, I have a class like this

public class TestClass { public int TestField { get; private set; } public TestClass( ) { TestField = 1; } } 

Then I have varialbe to make this class similar

  public TestClass test = new TestClass( ); 

The problem I am facing is that our reflection is similar to this

 PropertyInfo field = typeof( TestClass ).GetProperty( "TestField" ); field.SetValue( test, 2, null ); 
Programmers

can change the internal value of this class. it will be very bad, because it can destroy the library of holes. My question is what is the best way to protect my code form with such changes. I know that I can use some kind of bool flag, so the value can only be changed by one, but this is not a very good solution, is there a better one?
Best wishes,
Jordan

+4
source share
4 answers

Please understand that I mean this with all due respect:

You are wasting your time. Seriously.

Reflection should not be considered when specifying an API or contract.

Believe it. Unable to stop reflection. If a consumer is inclined to look into your code and flip bits that were hidden for some reason, well, the consequences are on them, not on you.

+6
source

You are trying to protect your system from what is stronger than your code. If you do not trust a certain code, run it with partial trust - then when it asks to reflect your type, it will be denied.

Reflection (and related methods such as DynamicMethod ) can, with sufficient confidence, gain almost unlimited access to your data (even, for example, changing string characters without re-assigning it); thus, you should reduce trust for untrusted code.

Similarly, anyone with debugger or administrator access to your process (or the DLL that it loads) can undermine your code. This is not an interesting attack, since a β€œhacker" should have at least the same access as your code (possibly more).

+6
source

You can even change the private readonly field using reflection. So the best way is const .

+2
source

Use the ReadOnly value if you want to have a constant value. or just use const .

Use Enum if you have several "safe values" that you want the client (programmer) to select one of them.

Edit: Apparently, Enum not safe enough. you can use the ReadOnly field with the following format:

 public class SafeValue { private string _value; public static readonly SafeValue Value1 = new SafeValue("value1"); public static readonly SafeValue Value2 = new SafeValue("value2"); private SafeValue(string value) { _value = value; } public override string ToString() { return _value; } } 
0
source

Source: https://habr.com/ru/post/1307917/


All Articles