2013-01-30

Use internal keywords to build safety reference between assemblies.


You probably already know how to use internal keyword in .NET, but I still wanna share this .NET feature in my thought. If you think this is not right, then I am glad to hearing from you what is possible the correct pattern.

In .NET, once we can reference any assembly if we need, e.g. Lib1.dll, then we can directly use most public classes and methods, or even use reflection access some private methods or properties as well. If consider high safety and security, how to protect those private stuff is really important. In another word, sometimes we really do want to expose some class and method to other sibling projects, and generally we just make it public. Which is okay for implement feature, but it is also bad for security, cause some care stuff we really want nobody touch it. For example, in Lib1 project, we really want keep invisible for those core classes/properties/methods which refer to unmanaged stuff, if we exposed it, then there will be a big chance some smart developer -- he or she you have no idea who they are-- 
tries to use them, and if the unmanaged code base is a massive, then all bad things will happening( I have some bad experience on this scenario). So how to avoid this and keep those classes/properties/methods internal visibility is very important to make whole software under high security protection, we need use internal keyword.

Here is my way:
  • First make the assembly strongly name support in client project(I do not want discuss it is necessary or not, but in my onion every assembly need strongly name), e.g. Share.snk
  • Then make client project compile successfully, and open command line to extract publicKey token. See below image:
  • Go back to your shared project, open Properties->AssemblyInfo.cs, adding internal friendly assembly[assembly: InternalsVisibleTo("AQMetaTypeFix, PublicKey=002400000.....370cad")]
  •  Recompile shared project, and in client project, we can be able to access all of internal classes and methods from share project.

Using this mechanism, I build some projects with much strong security than before, especially for those SDK which my company shipped to customer, I never met any unexpected fatal error any more. And except all these, use internal keyword to hidden stuff is a fun game to play.

No comments: