Obfuscate Assembly and Reflection - c#

I want to obfuscate my assembly files (*.dll, *.exe) by Dotfuscator. my question is if I do this, can I still use classes and types that are in those assemblies by their original names (I mean names before obfuscation) and using System.Reflection methods to work with them?
If you need more detail,please tell me

Obfuscation are Reflection can cause you some problem. Even if you take the suggestion to use option to not obfuscate public method, some of the reflected code may call private method. The problem is that obfuscation will change name of some code that you may need to stay the same.
If you know or can locate the region that is susceptible to be used with reflection you can use
[global::System.Reflection.Obfuscation(Exclude=true, Feature="renaming")]
This will tell the obfuscator to keep the name.
Running obfuscation with reflection require more testing that's for sure but still possible...

Read for example here http://msdn.microsoft.com/en-us/library/ms227298(v=vs.80).aspx There is a "library mode" to disable obfuscation of public members. Otherwhise you probably won't be able to access the methods. There is an attribute to control obfuscation at type level: http://msdn.microsoft.com/en-us/library/ms227281(v=vs.80).aspx

You can use System.Reflection on an obfuscated assembly, but since some of the point of obfuscation is to rename everything in the assembly into random and meaningless things, you can't do reflection on the same names and identifiers as you would in a non-obfuscated assembly. If you want to do reflection on an obfuscated assembly, you would need to do it in a way that aren't dependent on what types and members are named.

You can create your own private map to get new names from old ones.
Mapper must write table of a sort to disk/db with following structure:
Module(executable),Index,OriginalType,ObfuscatedType
Create "Mapper" console application that operates on two modes based on an argument:
The application will receive as argument executable path
Load Assembly
GetTypes from loadedAssembly
PreObfuscation deletes all entries and writes anew the indexes and OriginalType values .
PostObfuscation updates ObfuscatedType by index.
The post build events must be as follows:
Mapper.exe "target.exe" "Pre"
[Obfuscate]
Mapper.exe "target.exe" "Post"
Now you need a function to getObfuscatedName from OriginalName and you're done.
Note that this solution will not work with pruning as the number of types will change and indexes will no longer match between
OriginalAssembly.GetTypes()
and
ObfuscatedAssembly.GetTypes()

Related

How to examine .NET assembly without using reflection

Let's say, we have class Base, and Derived, defined in Base.dll and Derived.dll respectively. Derived is derived from Base (may not be a direct sub-class though)
The problem at hand is, if we have Derived.dll at hand but Base.dll is missing, how to programmatically examine all the types in Derived? e.g. to know what types are available, their accessibility, inheritance relationship, etc
Based on my understanding, reflection (things in System.Reflection namespace) is not an option here because GetTypes() will try to load Base.dll which is not available, thus throw ReflectionTypeLoadException.
In particularly, is this something that can be easily achieved using Roslyn, or some good library?
You're looking for System.Reflection.Metadata, which exposes assembly metadata directly, without loading assemblies via reflection.
For investigate .NET assembly (types, methods etc.) you need to get that from the metadata. Roslyn its not what you are looking for.
Although it's not exactly true, because Roslyn has two types of information about your code, one is nodes and token and the other is symbols. The first don't know about relation info but the second know.
Anyway, you can do it in more than one way. I'll write two of them.
Use Mono.Cecil to open your assembly, get the main module and investigate whatever you want.
var allTypesDefinitaion = ModuleDefinition.ReadModule(assemblyPath).Types;
Use tools like CFF Explorer to investigate the relevant metadata tables. (TypeDef\Ref)

Hide class members from everything except another specific assembly

I have two class libraries "MyLibrary.dll" and "MyLibraryEditor.dll" for a Unity runtime and editor extension. There are several class members inside "MyLibrary.dll" that are only intended for use by "MyLibraryEditor.dll".
My first thought was to use the internal keyword because I mistakenly thought that this constrained visibility to a namespace. Instead it is clear that this keyword limits visibility to the assembly.
What is the best way to constrain access to some class members to "MyLibrary.dll" and "MyLibraryEditor.dll" without hurting performance? Also, reflection is not an option.
I am happy to simply not document the functions, but unfortunately Intellisense (and MonoDevelop's equivalent) show these members.
If you want internals in one assembly to be visible from another assembly, you can use the InternalsVisibleTo attribute on the assembly containing the internals. See http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx:
[assembly:InternalsVisibleTo("MyLibraryEditor")]
That answered, you might want to rethink your architectural design so that you don't need to use it, since it will open up all internals to the other assembly, not only the ones that you want.
You could make the members internal but use [InternalsVisibleTo] to give access to those members to the other assembly. They'd still be visible within the same assembly as well, of course... there's no way of getting round that.
I primarily use InternalsVisibleToAttribute for giving access to internal members to test classes, and would try to avoid doing this for non-test purposes - but sometimes it can be useful.
This is not possible using pure C# concepts. You are two seperate assemblies, that is as far seperate as you can get, and there is no relationship between the two as far as .Net is concerned.
you could do some things with signing or validation to make it so it would be difficult to use one assembly without the other, but not something you can do to prevent visibility of the classes/members.

Prevent loading an assembly in c#

I want to prevent an assembly to be loaded from another application. So that it can be loaded from my application only.
Rigth now I'm using Assambly.LoadFrom to load the assembly.
Ultimately, no. It sounds like you are deploying a dll, but you want to retain sole control over how it is used. That is just an arms race; ultimately if somebody really, really wants to (ab)use it, they can. Even if that means disassembling, de-obfuscating, and disarming any preventative code you have added.
The only way to block that: don't give it to them. Consider using a web-service for some functions. Then they don't have the assembly.
You can try to validating entry assembly (Assembly.GetEntryAssembly) somewhere in your 'protected' assembly.
You can't stop people from using your DLL using technological approach. You can try to make it more difficult but a sufficiently skilled user will be able to modify the assembly so that they can use it.
You could try a legal approach. You can include a clause in your license agreement which disallows people from using your assembly in another application. But it won't stop everyone.
You could use the InternalsVisibleToAttribute in your assembly and specify your application assembly as a "friend". This will prevent other assemblies of using types provided they are marked as internal but will allow your application to still use those types.
From MSDN:
Ordinarily, types and members with
internal scope (in C#) and friend
scope (in Visual Basic) are visible
only in the assembly in which they are
defined. The
InternalsVisibleToAttribute attribute
makes them also visible to the types
in a specified assembly.
The attribute is applied at the
assembly level. This means that it can
be included at the beginning of a
source code file, or it can be
included in the AssemblyInfo file in a
Visual Studio project. You can use the
attribute to specify a single assembly
that can access the internal types and
members of the current assembly. To
make the assembly's internal types and
members visible to additional
assemblies, you must include a
separate InternalsVisibleToAttribute
attribute for each assembly.
Not that this does not prevent anyone from loading your assembly, it just prevents them from using the internal types within the assembly (at least not without some major effort, in the end anyone can just disassemble your code and use it that way).
Obfuscate it and keep documentation secret. Also include a key as in:
http://www.codeguru.com/columns/experts/article.php/c4643

Enforcing type visibility between namespaces in C#

I have the idea that it might be useful to enforce type visibility between namespaces rather than assemblies (internal) in C#.
It would seem that such a concept would assist developers working with a codebase, ensuring the correct types are used in places where another internal type supplying similar functionality is available, but would result in "architectural" disadvantages (unwanted dependencies etc).
Do others think this would be useful and is it currently possible? If not why not?
Also, would the concept of preclusions - the ability to specify negative constraints on references between namespaces and / or assemblies be a useful addition to C#?
A type is strongly bound to the assembly in which it is defined. A namespace is not, it can appear in multiple assemblies. System.Configuration for example.
Let's assume for a moment that the metadata format for an assembly would be changed (-1 billion points) to store attributes for a namespace. Those attributes would still have to be stored in an assembly because that's the storage unit for metadata. Now you have to deal with the possibility that the CLR loads another assembly and finds the same namespace but with conflicting attributes. How could it possibly resolve that?
More seriously, how would you prevent external code from simply using the same namespace and attributes to suddenly get access to implementation details that were meant to be private. This completely destroys the value of having the internal keyword.
You could make them public, tag them with a custom attribute, and then add a FxCop rule to check for accesses from the outside of the namespace.
This doesn't securely enforce the restriction and fails when the member is accessed with reflection, but if it's only about policy/codingstyle this should be enough.
I think there is also an existing attribute to hide members from Intellisense which you might use in conjunction with your custom attribute.

How Do I Load an Assembly and All of its Dependencies at Runtime in C# for Reflection?

I'm writing a utility for myself, partly as an exercise in learning C# Reflection and partly because I actually want the resulting tool for my own use.
What I'm after is basically pointing the application at an assembly and choosing a given class from which to select properties that should be included in an exported HTML form as fields. That form will be then used in my ASP.NET MVC app as the beginning of a View.
As I'm using Subsonic objects for the applications where I want to use, this should be reasonable and I figured that, by wanting to include things like differing output HTML depending on data type, Reflection was the way to get this done.
What I'm looking for, however, seems to be elusive. I'm trying to take the DLL/EXE that's chosen through the OpenFileDialog as the starting point and load it:
String FilePath = Path.GetDirectoryName(FileName);
System.Reflection.Assembly o = System.Reflection.Assembly.LoadFile(FileName);
That works fine, but because Subsonic-generated objects actually are full of object types that are defined in Subsonic.dll, etc., those dependent objects aren't loaded. Enter:
AssemblyName[] ReferencedAssemblies = o.GetReferencedAssemblies();
That, too, contains exactly what I would expect it to. However, what I'm trying to figure out is how to load those assemblies so that my digging into my objects will work properly. I understand that if those assemblies were in the GAC or in the directory of the running executable, I could just load them by their name, but that isn't likely to be the case for this use case and it's my primary use case.
So, what it boils down to is how do I load a given assembly and all of its arbitrary assemblies starting with a filename and resulting in a completely Reflection-browsable tree of types, properties, methods, etc.
I know that tools like Reflector do this, I just can't find the syntax for getting at it.
Couple of options here:
Attach to AppDomain.AssemblyResolve and do another LoadFile based on the requested assembly.
Spin up another AppDomain with the directory as its base and load the assemblies in that AppDomain.
I'd highly recommend pursuing option 2, since that will likely be cleaner and allow you to unload all those assemblies after. Also, consider loading assemblies in the reflection-only context if you only need to reflect over them (see Assembly.ReflectionOnlyLoad).
I worked out Kent Boogaart's second option.
Essentially I had to:
1.) Implement the ResolveEventHandler in a separate class, inheriting from MarshalByRefObject and adding the Serializable attribute.
2.) Add the current ApplicationBase, essentially where the event handler's dll is, to the AppDomain PrivateBinPath.
You can find the code on github.

Categories

Resources