here is the problem case i am writing a little 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 a varialbe form this class like this
public TestClass test = new TestClass( );
The problem i am facing is that usnig reflection like this
PropertyInfo field = typeof( TestClass ).GetProperty( "TestField" );
field.SetValue( test, 2, null );
programers can change internal value of this class. this will be very bad thing becouse it can crash the hole library. My question is what is the best way to protect my code form such changes.I know i can use some kind of bool flag so tha value can be changed only ones but this is not very good salution is there a better one?
Best Regards,
Iordan
Please understand that I mean this with all respect:
You are wasting your time. Seriously.
Reflection is not to be considered when specifying an API or contract.
Believe this. It is not possible to stop reflection. If a consumer is bent on peeking into your code and flipping bits that have been hidden for a reason, well, the consequences are on them, not you.
You are trying to protect your system from something that is stronger than your code. If you don't trust certain code, run it with partial trust - then when it asks to reflect your type it will be denied.
Reflection (and related techniques like DynamicMethod
) can with enough trust get virtually unrestricted access to your data (even, for example, changing the characters of a string
without ever re-assigning it); thus you must reduce trust for non-trusted code.
In a similar way, anyone with debugger or admin access to your process (or the dlls it loads) can subvert your code. This is not an interesting attack, as the "hacker" must already have at least as much access than your code (probably more).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With