Tuesday, February 6, 2007

.NET Security: Limit Access to a Class Library

I have used StrongNameIdentityPermission in a few projects to ensure only my own applications get access to my libraries. Here is how it was done. However, the fine print on this page seems to indicate that the old trick is not gonna work on .NET 2.0.

...In the .NET Framework version 2.0, demands for
identity permissions are ineffective if the calling
assembly has full trust...
In 2.0, the alternative is Friend Assemblies , or InternalsVisibleToAttribute: suppose you are writing a class library (SecureLib.dll) and an application (SecureApp.exe), and you want to ensure that only SecureApp can access SecureLib classes and functions:
  1. Use sn.exe to generate a key file (mykey.snk) and use the same key file to sign both assemblies (Property -> Signing):
  2. sn -k mykey.snk
  3. Use the following commands to print the public key in the keyfile: the public key is a long hex string.
  4. sn -p mykey.snk mypublickey.snk
    sn -tp mypublickey.snk
  5. Declare ALL public classes in SecureLib project as internal, and add following attribute declaration (replace the long hex string with the output from step 2):
  6. [assembly: InternalsVisibleTo("SecureApp,
              PublicKey=long hex string")]
Now, only SecureApp can successfully link to SecureLib. Any other application trying to link to SecureLib will fail at compile-time.