17.7. Making a Security Assert Safe
Problem
You want to assert that at a particular point in the call stack, a given permission is 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, you need to call Demand on the permissions that the subsequent calls need. This makes sure that code that doesn't have these permissions can't slip by due to the Assert. The Demand is done to ensure that you have indeed been granted this permission before using the Assert to short-circuit the stackwalk. This is demonstrated by the function CallSecureFunctionSafelyAndEfficiently, which performs a Demand and an Assert before calling SecureFunction, which in turn does a Demand for a ReflectionPermission.
The code listing for CallSecureFunctionSafelyAndEfficiently is shown in Example 17-10.
Example 17-10. CallSecureFunctionSafelyAndEfficiently function
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 ensure ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access