Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating initialization code for .dll

Tags:

c#

c++-cli

I recently heard that it is possible for a .dll to run code as soon as it is loaded, when an application which references the .dll is loaded, for example. Event though I made some tests of my own and tried looking for answers here and on Google I was unable to find some way to generate an initialization method for a .dll.

I would like to know if it is really possible to run code from a .dll when it is loaded by an application.

If so, how can I do so?

like image 406
Bruno Klein Avatar asked Jun 15 '13 18:06

Bruno Klein


1 Answers

WARNING (thanks Ben Voigt for the catch :)): the below code applies only to C# that guarantees that the generated class won't be beforefieldinit. But with C++/CLI should not work as easily: Managed C++ Static Constructor not called in .net4


So as stated in my comment you may use something like this:

using System;

class MyAwesomeLibrary
{
    static MyAwesomeLibrary()
    {
        Console.WriteLine(string.Format("Hey {0} is using me!", Environment.UserName));
    }
    
    public static int GetTheAnswer()
    {
        return 42;
    }
}

class Client
{
    static void Main()
    {
        Console.WriteLine("The answer is: " + MyAwesomeLibrary.GetTheAnswer());
    }
}

In the static constructor you can do advanced things like checking the registry, communicating with a server...

And if you're a bad guy (or just a developer/company who wants to protect its rights) you can throw an exception:

throw new Exception("The library has not been correctly registered...");

This will result in a TypeInitializationException preventing the use of the whole library class.

Or you can implement a CheckMe method ans asks all the user to call it before using the library or even to authenticate and get a security token they'll use each time they use something...

EDIT:

Whatever the protection you use a determined attacker could circumvent all the plumbing by decompiling the library so if you can you should obfuscate your library too to be (a little) more protected.

like image 59
Pragmateek Avatar answered Oct 06 '22 06:10

Pragmateek