.NET Framework 2.0 Security Guidelines - Delegates

From Guidance Share

Jump to: navigation, search

- J.D. Meier, Alex Mackman, Blaine Wastell, Prashant Bansode, Chaitanya Bijwe


Avoid accepting delegates from untrusted sources

If your assembly exposes a delegate or an event, be aware that any code can associate a method with the delegate, and you have no advance knowledge of what the code will do. The safest policy is not to accept delegates from untrusted callers. If your assembly is strong named and does not include the AllowPartiallyTrustedCallersAttribute, only full trust callers can pass a delegate to your code.


Consider restricting permissions to the delegate

If you allow partially trusted callers, you should consider restricting permissions to the delegate. You can either use an appropriate permission demand to authorize the external code when it passes the delegate to your code, or you can use a deny or permit-only stack modifier to restrict the delegate's permissions just prior to calling it. For example, the following code grants the delegate code only execution permission to constrain its capabilities.


using System.Security;
using System.Security.Permissions;
...
// Delegate definition
public delegate void SomeDelegate(string text);
   
public void ExecDelegateWithExcePerm()
{
       // Permit only execution, prior to calling the delegate. This prevents the
       // delegate code accessing resources or performing other privileged
       // operations
       new SecurityPermission(SecurityPermissionFlag.Execution).PermitOnly();
       // Now call the "constrained" delegate
       SomeDelegate del = new SomeDelegate(DisplayResults);
       // Revert the permit only stack modifier
       CodeAccessPermission.RevertPermitOnly();
}
private void DisplayResults(string result)
{
...
} 


Avoid asserting permissions before calling a delegate

Asserting a permission before calling a delegate is dangerous because you have no knowledge about the nature or trust level of the code that will be executed when you invoke the delegate. The code that passes you the delegate is on the call stack and can therefore be checked with an appropriate security demand. However, there is no way of knowing the trust level or permissions granted to the delegate code itself.

Personal tools