.NET Framework 1.1 Performance Guidelines - Code Access Security

From Guidance Share

Jump to: navigation, search

- J.D. Meier, Srinath Vasireddy, Ashish Babbar, Rico Mariani, and Alex Mackman


Choose the Appropriate Remote Communication Mechanism

When you use P/Invoke or COM interop, the interop code is subject to permission demands that walk the call stack to ensure that the calling code is authorized to call unmanaged code.

You can use the SuppressUnmanagedCodeSecurity attribute to improve performance by eliminating the stack walk permission demand and replacing it with a link demand that only checks the immediate caller. Before doing so, you should perform a thorough code review and be certain that your code is not susceptible to luring attacks.

The following code shows how to use SuppressUnmanagedCodeSecurity with P/Invoke.

public NativeMethods
{
 // The use of SuppressUnmanagedCodeSecurity here applies only to 
FormatMessage
 [DllImport("kernel32.dll"), SuppressUnmanagedCodeSecurity]
 private unsafe static extern int FormatMessage(
                                     int dwFlags,
                                     ref IntPtr lpSource,
                                     int dwMessageId,
                                     int dwLanguageId,
                                     ref String lpBuffer, int nSize,
                                     IntPtr *Arguments);
}

The following example shows how to use SuppressUnmanagedCodeSecurity with COM interop, where this attribute must be used at the interface level.

[SuppressUnmanagedCodeSecurity]
public interface IComInterface
{
}



Prefer Declarative Demands Rather Than Imperative Demands

Use declarative demands where possible. Declarative security has a rich syntax and using declarative demands provides the .NET Framework with the maximum ability to optimize code because you are specifying your intent succinctly and directly.


Consider Using Link Demands Rather Than Full Demands for Performance-Critical, Trusted Scenarios

When code accesses a protected resource or performs a privileged operation, code access security demands are used to ensure that the code has the required permissions. Full demands require the runtime to perform a stack walk to ensure that the calling code has the required permissions.

The full stack walk can be avoided by using a link demand instead of a full demand. While performance is improved because the link demand checks only the immediate caller during JIT compilation, you need to balance this performance gain with your security requirements. The link demand significantly increases the chances of your code being subjected to a luring attack, where malicious code calls your code to access a protected resource or perform a privileged operation.

You should consider using link demands only in trusted scenarios where performance is critical, and you should consider it only after you have fully evaluated the security implications.

Personal tools