How do I safely use an obfuscator? - c#

When I attempt to use dotfuscate on my application, I get an application error when I run it.

Dotfuscator (and all obfuscators) are typically safe to run on an application, but they do occasionally cause problems. Without specific details of your problem, it's difficult to diagnose.
However, one common problem with obfuscators is when you mix them with reflection. Since you're changing the type names, but not strings, any time you try to reflect on objects with a specific string name, and use the reflection namespace to construct objects, you'll likely have problems.

Most of the problem I have encountered with obfuscation revolve around types that can't have their name changed, because something needs to reflect on them (your code or the runtime).
for example if you have a class that is being used as a web service proxy, you can't safely obfuscate the class name:
public class MyWebServiceProxy : SoapHttpClientProtocol
{
}
Also some obfuscators can not handle generic methods and classes.
The trick is you need to find these types and prevent the obfuscater from renaming them. This is done with the Obfuscation attribute:
[global::System.Reflection.Obfuscation(Exclude=true, Feature="renaming")]

Another thing that can be a problem with obfuscators is serialization using BinaryFormatter, since it changes the field names. I have some users who use protobuf-net for serialization on their obfuscated code for this reason.

Related

Which strategy can be used when converting back and forth between a domain class and several versions of the same target class?

For my specific context I control the target classes. They were auto-generated based on XSDs and have huge overlaps because they represent different versions of the same class.
Each version is a huge C# class of over 5.000 lines.
Support can't be dropped for old versions. This means we always need to be able to map the domain class to several different versions and back again. There are always small but breaking changes from version to version. More than 90% of the target class is always the same, even if the code is duplicated for each version.
Currently there is one big mapping for each format, which is a horror. There is so. much. duplicated. code. Furthermore, developers tend to make updates where they need it, and skip everything else, which means individual versions often go out of sync, meaning that one version will be updated to do something that other versions don't. This is also not ideal.
So my question to you is: What strategy can you use for this kind of mapping?
Given the size of your classes, and having to maintain multiple versions, I'd suggest serializing and serializing. Assuming that they otherwise approximate one another, JsonConvert doing JsonConvert.Deserialize<TargetClass>(JsonConvert.Serialize(sourceClass)) should solve it, though I've not worked with such large models to have any idea on how performant it is.
Alternatively, you could use a t4 template (if you're not in .net Core anyway) to generate the mapping using reflection into a common method or whatever.
As far as preventing the Developer problem... Interfaces, base classes that define as much of this centrally as possible. Code reviews to ensure that developers are making changes to the lowest layer they possibly can.
You can do some tricky things with inheretence with static using statements, I'm pretty sure.
Something dumb like
using OldVersion = path.to.the.class.CantRenameThis;
class CantRenameThis : OldVersion
We ended up with a solution that achieved the main targets:
Decent compile-time safety to spot mapping errors
De-duplication of code
No messing with the auto-generated code
We did this by exploiting that the auto-generated classes are generated as partial. That means we can extend them.
We ended up creating hierarchies of interfaces/classes looking like this:
ClassV1 implements IClassVerySpecificV1
ClassV2 implements IClassVerySpecificV2
IClassVerySpecificV1 implements SpecificA, SpecificB, SpecificC and IClassBasic
IClassVerySpecificV1 implements SpecificB, SpecificC, SpecificD and IClassBasic
A mapper would then look like:
ClassV1Mapper requires a SpecificAMapper, SpecificBMapper, SpecificCMapper and ClassBasicMapper
ClassV2Mapper requires a SpecificBMapper, SpecificCMapper, SpecificDMapper and ClassBasicMapper
This way we could map 90% of everything by just throwing everything that belongs to IClassBasic into a ClassBasicMapper.
We did run into some issues however:
As you can already guess, we end up with a LOT of interfaces. More than you want.
Sometimes a field exists across versions, but has different (enum) values. Our domain model would have the superset, with an attribute specifiying which values were valid for which versions.

Retrieve custom attributes of Type in .NET Standard

I'd like to use C#'s reflection and custom attributes to simplify registering a series of types with a central management class (i.e. it provides static methods taking a string key and invoking/retrieving the proper method/parameter for the associated type). Looking at other questions here and a couple places elsewhere, it seems like the best way of doing so is to simply iterate through all public types of the assembly -- since it's intended to be a library -- and check if each type has the proper attribute before adding the relevant values to the underlying Dictionaries. The reflection and iteration will definitely be slow, but I can live with it since it should only occur once.
Unfortunately, I can't figure out how to get an attribute from a type. For methods and assemblies, I can use CustomAttributeExtensions.GetCustomAttribute<MyAttribute>(base) from System.Reflection.Extensions, but that doesn't provide an overload for Type; the same for Assembly.GetCustomAttribute(Assembly, Type) and the .IsDefined(...) methods used in this question. Other suggestions use methods on the Type itself that, from the documentation, seem to be loaded from mscorelib.dll, but it didn't seem to be showing up in Intellisense even after adding the reference and I'm not sure how that .dll interacts with .NET Standard, anyway (as in, does it reduce the ability to run on arbitrary platforms at all?)
Am I missing something obvious, or is it really this hard to get an Attribute back off of a Type?
Try typeof(YourType).GetTypeInfo().GetCustomAttributes();

Force the usage of an attribute on properties, if they already have another attribute

I want to force the usage of an attribute, if another attribute is used.
If a special 3rd party attribute is attached to a property, this attribute also needs to be given to a property.
Is there any possibility of doing this?
For example:
[Some3rdPartyAttribute("...")]
[RequiredAttribute("...)]
public bool Example{get; set;}
should bring no compile error,
[Some3rdPartyAttribute("...")]
public bool Example{get; set;}
should bring a compile error or warning.
The attribute itself is definded like the example from http://msdn.microsoft.com/en-US/library/z919e8tw(v=vs.80).aspx itself . But how to force the usage of the attribute if another attribute is used?
Unfortunately you cannot generate custom compiler warnings from attributes. Some attributes like System.ObsoleteAttribute will generate a warning or error, but this is hard-coded into the C# compiler. You should find another solution to your problem, maybe letting Some3rdPartyAttribute inherit from RequiredAttribute?
Otherwise you have to change the compiler.
Another option is using some AOP techniques. Like for example:
PostSharp.
Using it you can at compilation analyze yur code and emit a error if some condition does not sutisfies your requirements.
For concrete example on attributes, can have a look on :
PostSharp 2.1: Reflecting Custom Attributes
You can make a console app, that will iterate trough all types in your assembly trough reflection, check if the rule is satisfied and return 0 if it is, and some other error code and output error if the rule is broken.
Then make this console app run as post-build task.
As far as I know, there is no way to check for attributes at compile time.
I recently needed to enforce something similar (all classes derived from a certain base class need certain attributes). I ended up putting a manual check (with [Conditional("DEBUG")]) using reflection into the constructor of the base class. This way, whenever someone creates an instance of a class with missing attributes, they get an exception. But this might not be applicable in your case, if your classes do not all derive from the same class.
You could write some code that runs on application start which uses reflection and would then throw runtime exceptions if an attribute was used without the proper match but I believe that's as far as you can go and personally I wouldn't consider that a good approach as you would need to run the application once to make sure it complies with your rules.
Also, take a look at PostSharp which may help you.
How about using #warning + Unit testing? In this way, whenever you run Unit tests, an warning will be generated (or you could just use Debug.Fail instead of #warning)

Using reflection to SetValue on property with private setter

I ran into, what I thought was a bug is actually, a feature detailed in This post. Can anyone explain to me why this is allowed? It seems like a legacy quirk/bug that became useful.
I'm not sure which part of that you think is a bug, but it has always been possible to access the internals of a class via reflection when you cannot do so at compile time. This is by design. Numerous aspects of the CLR rely on reflection to access fields, such as serialization. The compiled IL needs to be able to access all fields of all objects, or else you couldn't set private fields from within your class.
The access modifiers in C# are not a security mechanism. If you are relying on a field being private to prevent anyone from setting it from the outside, you're doing something wrong. They exist to clearly delineate which parts of your class are it's public contract (and thus, in theory, stable) from those parts that are implementation details (and thus can change without notice.)
If you choose to use reflection to change the internal state of an object, despite all indications that you should leave it alone, you are taking the stability of your application into your own hands, and you get what deserve.
Reflection is allowed only for Full Trust code, so the code already able to do anything (including directly poking in memory of the process). So having supported way of changing values even for private properties does not make code any less secure. It makes reflection API consistent and allows useful scenarios especially for testing.

Justification for Reflection in C#

I have wondered about the appropriateness of reflection in C# code. For example I have written a function which iterates through the properties of a given source object and creates a new instance of a specified type, then copies the values of properties with the same name from one to the other. I created this to copy data from one auto-generated LINQ object to another in order to get around the lack of inheritance from multiple tables in LINQ.
However, I can't help but think code like this is really 'cheating', i.e. rather than using using the provided language constructs to achieve a given end it allows you to circumvent them.
To what degree is this sort of code acceptable? What are the risks? What are legitimate uses of this approach?
Sometimes using reflection can be a bit of a hack, but a lot of the time it's simply the most fantastic code tool.
Look at the .Net property grid - anyone who's used Visual Studio will be familiar with it. You can point it at any object and it it will produce a simple property editor. That uses reflection, in fact most of VS's toolbox does.
Look at unit tests - they're loaded by reflection (at least in NUnit and MSTest).
Reflection allows dynamic-style behaviour from static languages.
The one thing it really needs is duck typing - the C# compiler already supports this: you can foreach anything that looks like IEnumerable, whether it implements the interface or not. You can use the C#3 collection syntax on any class that has a method called Add.
Use reflection wherever you need dynamic-style behaviour - for instance you have a collection of objects and you want to check the same property on each.
The risks are similar for dynamic types - compile time exceptions become run time ones. You code is not as 'safe' and you have to react accordingly.
The .Net reflection code is very quick, but not as fast as the explicit call would have been.
I agree, it gives me the it works but it feels like a hack feeling. I try to avoid reflection whenever possible. I have been burned many times after refactoring code which had reflection in it. Code compiles fine, tests even run, but under special circumstances (which the tests didn't cover) the program blows up run-time because of my refactoring in one of the objects the reflection code poked into.
Example 1: Reflection in OR mapper, you change the name or the type of the property in your object model: Blows up run-time.
Example 2: You are in a SOA shop. Web Services are complete decoupled (or so you think). They have their own set of generated proxy classes, but in the mapping you decide to save some time and you do this:
ExternalColor c = (ExternalColor)Enum.Parse(typeof(ExternalColor),
internalColor.ToString());
Under the covers this is also reflection but done by the .net framework itself. Now what happens if you decide to rename InternalColor.Grey to InternalColor.Gray? Everything looks ok, it builds fine, and even runs fine.. until the day some stupid user decides to use the color Gray... at which point the mapper will blow up.
Reflection is a wonderful tool that I could not live without. It can make programming much easier and faster.
For instance, I use reflection in my ORM layer to be able to assign properties with column values from tables. If it wasn't for reflection I have had to create a copy class for each table/class mapping.
As for the external color exception above. The problem is not Enum.Parse, but that the coder didnt not catch the proper exception. Since a string is parsed, the coder should always assume that the string can contain an incorrect value.
The same problem applies to all advanced programming in .Net. "With great power, comes great responsibility". Using reflection gives you much power. But make sure that you know how to use it properly. There are dozens of examples on the web.
It may be just me, but the way I'd get into this is by creating a code generator - using reflection at runtime is a bit costly and untyped. Creating classes that would get generated according to your latest code and copy everything in a strongly typed manner would mean that you will catch these errors at build-time.
For instance, a generated class may look like this:
static class AtoBCopier
{
public static B Copy(A item)
{
return new B() { Prop1 = item.Prop1, Prop2 = item.Prop2 };
}
}
If either class doesn't have the properties or their types change, the code doesn't compile. Plus, there's a huge improvement in times.
I recently used reflection in C# for finding implementations of a specific interface. I had written a simple batch-style interpreter that looked up "actions" for each step of the computation based on the class name. Reflecting the current namespace then pops up the right implementation of my IStep inteface that can be Execute()ed. This way, adding new "actions" is as easy as creating a new derived class - no need to add it to a registry, or even worse: forgetting to add it to a registry...
Reflection makes it very easy to implement plugin architectures where plugin DLLs are automatically loaded at runtime (not explicitly linked at compile time).
These can be scanned for classes that implement/extend relevant interfaces/classes. Reflection can then be used to instantiate instances of these on demand.

Categories