LinkDemand and InheritanceDemand

Paladion
By Paladion

April 11, 2006

.NET's Code Access Security is a powerful mechanism to ensure that your code is protected from malicious assemblies. In the first article of this series, we discussed asserts and demands. Now let’s delve a little deeper into two special types of demands.

Assert Yourself!

In the first article of this series, we discussed asserts and demands. Now let’s delve a little deeper into two special types of demands. Before starting off, a quick recap about demands. When an assembly calls a .Net framework class or any other class, the class being called may ask .Net to verify that the calling assembly has the required permissions to access it. That’s called a demand.

LinkDemand

Now consider a scenario where your code spans multiple assemblies. You might have business logic code in Assembly B validate some inputs and call Data access code in Assembly A, as shown below.

LinkDemand

Assembly A would expose public methods that B can call. Now it is possible for any assembly to bypass the validations in B and directly call the public methods in A. This is clearly unsafe for your application. To protect against this, use the LinkDemand feature of .Net.

LinkDemand requires the immediate caller to have specified permissions. You can specify who may link to your assemblies. It occurs at compile time and hence a Stackwalk is not performed.

So how can we use LinkDemand to solve this problem? Couple the LinkDemand with strong names. Do a link demand in A and demand the calling assembly to be signed with the same public key as that of your organization. Then, only your organization’s code can call A’s public methods.

Thus the best practice is: Use LinkDemand with Strong Names to protect your assemblies.

InheritanceDemand

Suppose you have an assembly that demands certain permissions of classes that access it. Are you then safe from unauthorized assemblies? Not completely. A malicious assembly can inherit from your assembly and override the methods making the demands. This will neutralize the demands your component is making.

So to enforce restrictions on such inheritances, .Net provides a feature called InheritanceDemand.  If you set the InheritanceDemand and specify the permissions required, .Net will allow only classes that have that permission to  derive from your class.

How do you use InheritanceDemand to allow only your assemblies to derive and override your classes? By now, you would have seen the pattern. Yes, use InheritanceDemand with strong names. Thus you could set the InheritanceDemand for assemblies to have strong names with your organization’s public keys.

Inheritancedemand also provides the flexibility to be set at a method level. For simplicity, it’s usually used at the assembly/class level, though.

Thus, the best practice: Protect your demands from getting overridden by using InheritanceDemand with Strong names.


Tags: Technical

About

Paladion