O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

14.9. Making a Security Assert Safe

Problem

You want to assert that at a particular point in the call stack, a given permission is understood to be available for all subsequent calls. However, doing this can easily open a security hole to allow other malicious code to spoof your code or to create a back door into your component. You want to assert a given security permission, but you want to do so in a secure and efficient manner.

Solution

In order to make this approach secure, we need to call Demand on the permissions that the subsequent calls need and on which we are using Assert in order to make sure that code that doesn’t have these permissions can’t slip by due to the Assert. This is demonstrated by the function CallSecureFunctionSafelyAndEfficiently, which performs a Demand, then an Assert before calling into SecureFunction, which performs a Demand for a ReflectionPermission.

The code listing for CallSecureFunctionSafelyAndEfficiently is:

public static void CallSecureFunctionSafelyAndEfficiently( ) { // set up a permission to be able to access nonpublic members // via reflection ReflectionPermission perm = new ReflectionPermission(ReflectionPermissionFlag.MemberAccess); // Demand the permission set we have compiled before using Assert // to make sure we have the right before we Assert it. We do // the Demand to insure that we have checked for this permission // before using Assert to short-circuit stackwalking for it, which // helps us stay secure, while performing better. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required