Accessing public members of my own confused dll - c#

I've asked a question here before, about protecting an application from being stolen and I've got an answer.
I decided to use confuserEX which is free and works fine with WPF. But when I checked the documentation, I noticed that it renames all the strings in the code with other meaningless strings.
My question is that, if any string is replaced with another meaningless string how can I used my own dll to access public members or functions of a class inside it?

Public types and members are generally not obfuscated, so if there is code in your DLL that your app can call into from the outside, chances are that anyone else can call into it. There's not much you can do about that. If you have code that you don't want someone reverse engineering, then have that code run on a server that you control, as #Habib suggests.

Related

How are APIs or Frameworks made, so scripts can use their functions but you cannot see the code?

I was wondering how I could program like a certain API, I have written an algorithm that I want to publish so people can use it, but I don't want people to see the code, and steal it? Paranoid, I know, but still.
How is that made, so for instance I can in a C# script (the API would also be written in C#), include it (with using ApiName) and use the functions inside, for instance if the API has a function that I program like "void Calculate(float x, float y)", and then from a script they can call "Calculate(100, 200)" for instance. I know it's somehow possible because of the Windows API, etc. Also is creating a Class Library the same thing?
Before any code runs, it is either compiled or interpreted into binary. This is highly simplified but that is the general idea. As long as a library or API provides an interface like names of functions, the implementation itself can be compiled and still work.
For C#, NuGet is a good example, you can create a NuGet of your code (see https://learn.microsoft.com/en-us/nuget/create-packages/creating-a-package) where the public function and method signatures will be visible and usable but the implementations will be compiled. DLLs work in a similar way. You can reference them and call their public members but not see the code unless you use a tool to decompile them.

How to Instantiate object of private class from .DLL? [duplicate]

This question already has answers here:
Instantiating Internal class with private constructor
(5 answers)
Closed 7 years ago.
I'm either googling the wrong thing or trying to head down the completely wrong path (most likely)... but now I'm curious so I thought I'd ask.
Long story short, I'm trying to tap into the underlying "API" framework of Microsoft's Message Analyzer tool for a custom application. I say "API" because there is no formal support for an API, no documentation, and there won't be any in the near future, if ever (so says Paul at Microsoft anyway). So instead I've been using the IL DASM tool to poke around some of the Message Analyzer and PowerShell .dlls to try to get an understanding of how this stuff works; the ultimate goal of course is to use MA's .dlls and drivers to do what I want for the custom app. I'm looking at Microsoft.Protocols.Tools.PowerShell.dll, which has a class (Microsoft.Protocols.Tools.PowerShell.PpkTraceSession) that I'm trying to instantiate:
However, if you look right below it, it says something about the class being private (it's cut off in the picture, but the class does implement IPpkTraceSession and IPpkTraceSessionEx). Sure enough, when I reference this .dll in some C# code and try to instantiate an object, I get a compile error saying its inaccessible due to its protection level:
Windows PowerShell has no problem at all creating one of these objects. It just so happens the printout seen below matches all the properties (not seen in the first picture) of the PpkTraceSession class, so I know Windows PowerShell is working some magic to create an object of that class,, I just can't figure out how since apparently this class is private.
So my question,, what's going on here? I've poked around in a lot of the classes shown in the IL DASM output, and there are a surprising number of them that appear to be private. Maybe it's just my bad practice, but I've rarely if ever used or seen many private classes. It's my understanding they have to be nested in other classes to be of any particular use. If PpkTraceSession is nested in another class, that's not clear from the IL DASM output at all. You may see the IPpkTraceSession(Ex) interfaces above,, if there's a way to access the class properties using those I haven't figured it out yet. Is there anyway to instantiate an object of this class, or am I going about this all wrong?
This might be close to a duplicate, but not quite I don't think. Any help is much appreciated! I clearly don't know much about Windows programming.
yano
EDIT:::::
Just to tie off all the loose ends (in case somebody else makes my mistake), I discovered the source of my confusion a couple of days ago. All the classes indicated as "private" by the IL DASM tool are actually "internal" classes, meaning that they're meant to be visible only within their own assembly. That was my missing piece, I couldn't understand where all these private classes were coming from when C# won't even let you compile a standalone private class (it must be nested within another class). I should've done some more research on IL DASM before I posted a question, but it didn't even occur to me; I thought private meant private. It's my observation that IL DASM does make a distinction between private/internal classes and nested private classes. This issue has also already been addressed here: When I declare a class as internal, why does the IL show it as private? . Thanks for the help everyone!
I suspect that what you are seeing is that other classes, probably deep inside the PowerShell plumbing, might expose some of the properties of the PpkTraceSession class. You might be able to find them by inspecting the intermediate language of the public classes exposed by the same dll THAT contains the private PpkTraceSession class. However, I suspect that you are wasting your time, and will not find a way to use those classes in your own code.
They are marked private because Microsoft has no intention of supporting them, and their behavior might change without notice. That isn't a problem within the PowerShell team, which has access to them, most likely through other private classes. So, if they need to change the way one of those classes behaves, they can do it, and the affected audience is small and easily reachable.
Speaking as a developer, I can think of a host of reasons that Microsoft might not want to support it, such as that it is very fussy, or that doing so would involve disclosing proprietary or patented technology that they have a legal right to keep secret.
Perhaps you could start a campaign to make them public, but you'll need to make a really good case, and convince a lot of other people, preferably people who already pay Microsoft a lot of money, to get behind you.

Will the compiler only compile code that can get executed?

I have a class library and am using only part of it. Is there a need to delete what isn't being used in order to shrink the size of the created code (in release configuration)?
As far as I've seen, the compiler takes care of that, and removing the code doesn't change the EXE file size. Will this always be true? Removing all unneeded code would take very long, so I want to know if there's need for that.
More information: there are methods and classes in the class library that aren't called from the executing code, but are referenced by other parts of code in the class library (which themselves are never called).
No, the compiler includes the "dead" code as well. A simple reason for this is that it's not always possible to know exactly what code will and won't be executed. For example, even a private method that is never referenced could be called via reflection, and public methods could be referenced by external assemblies.
You can use a tool to help you find and remove unused methods (including ones only called by other unused methods). Try What tools and techniques do you use to find dead code? and Find unused code to get you started.
It all gets compiled. Regardless of whether it is called or not. The code may be called by an external library.
The only way to make the compiler ignore code is by using Compiler Preprocessor Directives. More about those here.
I doubt the compiler will remove anything. The fact is, the compiler can't tell what is used and what is not, as types can be instantiated and methods called by name, thanks to reflection.
Let's suppose there is a class library called Utility. You created a new project and added this class library to that project. Even if your EXE calls only 1-2 methods from the class library, it's never a good idea to delete the unreferenced code.
It would go against the principle of reusablity. Despite the fact that there would be some classes present in the library unreferenced from the EXE, it would not have any bad impact on performance or size of the program.
Determining all and only dead code is (if one makes the idealization that one has a "math world" like language) recursively undecidable, in most languages. (A few rare ones like the Blaise language are decidable.)
to the question of whether there is a "need to delete what isn't being used in order to shrink the size of the created code": i think this would only be useful to save network bandwidth. removing unused code is crucial in web applications to improve loading speeds etc.
if you're code is an exe or a library, the only reason i see to remove dead code, is to improve your code quality. so that someone looking at your code 2 years down the line won't scratch their heads wondering what it does.

Is there an equivalent to Java's ClassFileTransformer in .NET? (a way to replace a class)

I've been searching for this for quite a while with no luck so far. Is there an equivalent to Java's ClassFileTransformer in .NET? Basically, I want to create a class CustomClassFileTransformer (which in Java would implement the interface ClassFileTransformer) that gets called whenever a class is loaded, and is allowed to tweak it and replace it with the tweaked version.
I know there are frameworks that do similar things, but I was looking for something more straightforward, like implementing my own ClassFileTransformer. Is it possible?
EDIT #1. More details about why I need this:
Basically, I have a C# application and I need to monitor the instructions it wants to run in order to detect read or write operations to fields (operations Ldfld and Stfld) and insert some instructions before the read/write takes place.
I know how to do this (except for the part where I need to be invoked to replace the class): for every method whose code I want to monitor, I must:
Get the method's MethodBody using MethodBase.GetMethodBody()
Transform it to byte array with MethodBody.GetILAsByteArray(). The byte[] it returns contains the bytecode.
Analyse the bytecode as explained here, possibly inserting new instructions or deleting/modifying existing ones by changing the contents of the array.
Create a new method and use the new bytecode to create its body, with MethodBuilder.CreateMethodBody(byte[] il, int count), where il is the array with the bytecode.
I put all these tweaked methods in a new class and use the new class to replace the one that was originally going to be loaded.
An alternative to replacing classes would be somehow getting notified whenever a method is invoked. Then I'd replace the call to that method with a call to my own tweaked method, which I would tweak only the first time is invoked and then I'd put it in a dictionary for future uses, to reduce overhead (for future calls I'll just look up the method and invoke it; I won't need to analyse the bytecode again). I'm currently investigating ways to do this and LinFu looks pretty interesting, but if there was something like a ClassFileTransformer it would be much simpler: I just rewrite the class, replace it, and let the code run without monitoring anything.
An additional note: the classes may be sealed. I want to be able to replace any kind of class, I cannot impose restrictions on their attributes.
EDIT #2. Why I need to do this at runtime.
I need to monitor everything that is going on so that I can detect every access to data. This applies to the code of library classes as well. However, I cannot know in advance which classes are going to be used, and even if I knew every possible class that may get loaded it would be a huge performance hit to tweak all of them instead of waiting to see whether they actually get invoked or not.
POSSIBLE (BUT PRETTY HARDCORE) SOLUTION. In case anyone is interested (and I see the question has been faved, so I guess someone is), this is what I'm looking at right now. Basically I'd have to implement the profiling API and I'll register for the events that I'm interested in, in my case whenever a JIT compilation starts. An extract of the blogpost:
In your ICorProfilerCallback2::ModuleLoadFinished callback, you call ICorProfilerInfo2::GetModuleMetadata to get a pointer to a metadata interface on that module.
QI for the metadata interface you want. Search MSDN for "IMetaDataImport", and grope through the table of contents to find topics on the metadata interfaces.
Once you're in metadata-land, you have access to all the types in the module, including their fields and function prototypes. You may need to parse metadata signatures and this signature parser may be of use to you.
In your ICorProfilerCallback2::JITCompilationStarted callback, you may use ICorProfilerInfo2::GetILFunctionBody to inspect the original IL, and ICorProfilerInfo2::GetILFunctionBodyAllocator and then ICorProfilerInfo2::SetILFunctionBody to replace that IL with your own.
The great news: I get notified when a JIT compilation starts and I can replace the bytecode right there, without having to worry about replacing the class, etc. The not-so-great news: you cannot invoke managed code from the API's callback methods, which makes sense but means I'm on my own parsing the IL code, etc, as opposed to be able to use Cecil, which would've been a breeze.
I don't think there's a simpler way to do this without using AOP frameworks (such as PostSharp). If anyone has any other idea please let me know. I'm not marking the question as answered yet.
I don't know of a direct equivalent in .NET for this.
However, there are some ways to implement similar functionality, such as using Reflection.Emit to generate assemblies and types on demand, uing RealProxy to create proxy objects for interfaces and MarshalByRefObject objects. However, to advise what to use, it would be important to know more about the actual use case.
After quite some research I'm answering my own question: there isn't an equivalent to the ClassFileTransformer in .NET, or any straightforward way to replace classes.
It's possible to gain control over the class-loading process by hosting the CLR, but this is pretty low-level, you have to be careful with it, and it's not possible in every scenario. For example if you're running on a server you may not have the rights to host the CLR. Also if you're running an ASP.NET application you cannot do this because ASP.NET already provides a CLR host.
It's a pity .NET doesn't support this; it would be so easy for them to do this, they just have to notify you before a class is loaded and give you the chance to modify the class before passing it on the CLR to load it.

Modify an internal .NET class' method implementation

I would like to modify the way my C#/.NET application works internally. I have dug into the .NET framework with Reflector and found a pretty good place where I could use a different implementation of a method. This is an internal class in the System.Windows.Forms namespace. You obviously cannot alter the code of this class with the usual means so I thought it would be possible to replace a method in there through reflection at runtime. The method I would like to entirely replace for my application is this:
public static WindowsFontQuality WindowsFontQualityFromTextRenderingHint(Graphics g)
in the class:
internal sealed class System.Windows.Forms.Internal.WindowsFont
Is there any way to load that type and replace the method at runtime, not affecting any other applications that are currently running or started afterwards? I have tried to load the type with Type.GetType() and similar things but failed so far.
You may be able to do this with the debugger API - but it's a really, really bad idea.
For one thing, running with the debugger hooks installed may well be slower - but more importantly, tampering with the framework code could easily lead to unexpected behaviour. Do you know exactly how this method is used, in all possible scenarios, even within your own app?
It would also quite possibly have undesirable legal consequences, although you should consult a lawyer about that.
I would personally abandon this line of thinking and try to work out a different way to accomplish whatever it is you're trying to do.
Anything you do to make this happen would be an unsupported, unreliable hack that could break with any .NET Framework update
There's another, more correct, way to do what you are trying to accomplish (and I don't need to know what you're trying to do to know this for certain).
Edit: If editing core Framework code is your interest, feel free to experiment with Mono, but don't expect to redistribute your modifications if they are application-specific. :)
I realy think, this is not good idea. But if you realy need it, you can use a Mono Cecil and change the assembly content. Then you need setup a config file for Redirecting Assembly Versions.
And last but not least, your advance will be propable illegal.

Categories

Resources