Tip #46 explained the security actions for declarative security at the assembly level.
Let’s explore today the security actions at the methods level and how to demand security.
Although the way to apply a declarative security attribute for assemblies and methods is similar, the biggest difference between declarative security for assemblies and methods is that the security actions options are different and it makes the CLR perform different types of checks.
For assemblies it’s very straightforward. You must define the attributes and the runtime will check all the permissions before the entry point of your assembly to be called. If there is any lack of permissions an exception will be thrown.
Moving this topic to methods there is something very important you should understand: the concept of demanding security checks.
A method that specifies security permissions may be called from a different method, and this may be called from a third method or an assembly and so on. The idea behind the demand security is to check the immediate caller or all callers to ensure that the there is no lack of permission rights to access the method.
Security actions available
1. Assert: Setting the security action to Assert option makes the runtime to not check the callers;
2. Demand: Setting the security action to Demand option makes the runtime to check all callers. If any of the callers lack permissions, an exception is thrown. The following picture describes the process:
3. Link Demand: Setting the security action to LinkDemand option makes the runtime to check only the immediate caller. The following picture describes the steps performed:
4. Inheritance Demand: Setting the security action to InheritanceDemand option makes the runtime to throw an exception if the assembly inheriting from the method class lacks permission;
5. Permit Only: Setting the security action to PermitOnly option makes the runtime to remove all permissions other than the specified ones.
6. Deny: Setting the security action to Deny makes the runtime to remove the access for the particular permission.
Keep in mind that more security checks will bring overhead and loss of performance while less security checks will bring more breaches for an attacker to take advantage of it.