Use SuppressUnmanagedCodeSecurityAttribute with Caution

Use SuppressUnmanagedCodeSecurityAttribute with Caution

Be incredibly careful if you use SuppressUnmanagedCodeSecurityAttribute in your code. Normally, a call into unmanaged code is successful only if all callers have permission to call into unmanaged code. Applying the custom attribute SuppressUnmanagedCodeSecurityAttribute to the method that calls into unmanaged code suppresses the demand. Rather than a full demand being made, the code performs only a link demand for the ability to call unmanaged code. This can be a huge performance boost if you call many native Win32 function, but it's dangerous too. The following snippet applies SuppressUnmanagedCodeSecurityAttribute to the MyWin32Funtion method:

using System.Security; using System.Runtime.InteropServices;  public class MyClass {  [SuppressUnmanagedCodeSecurityAttribute()] [DllImport("MyDLL.DLL")] private static extern int MyWin32Function(int i); public int DoWork() { return MyWin32Function(0x42); } }

You should double-check all methods decorated with this attribute for safety.

IMPORTANT
You may have noticed a common pattern in LinkDemand and SuppressUnmanagedCodeSecurityAttribute they both offer a trade-off between performance and security. Do not enable these features in an ad hoc manner until you determine whether the potential performance benefit is worth the increased security vulnerability. Do not enable these two features until you have measured the performance gain, if any. Follow these best practices if you choose to enable SuppressUnmanagedCodeSecurity: the native methods should be private or internal, and all arguments to the methods must be validated.



Writing Secure Code
Writing Secure Code, Second Edition
ISBN: 0735617228
EAN: 2147483647
Year: 2001
Pages: 286

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net