CA2145: Transparent methods should not be decorated with the SuppressUnmanagedCodeSecurityAttribute
Applies to: Visual Studio Visual Studio for Mac
Note
This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here
Item | Value |
---|---|
RuleId | CA2145 |
Category | Microsoft.Security |
Breaking change | Breaking |
Cause
A transparent method, a method that is marked with the SecuritySafeCriticalAttribute attribute, or a type that contains a method is marked with the SuppressUnmanagedCodeSecurityAttribute attribute.
Note
This rule has been deprecated. For more information, see Deprecated rules.
Rule description
Methods decorated with the SuppressUnmanagedCodeSecurityAttribute attribute have an implicit LinkDemand placed upon any method that calls it. This LinkDemand requires that the calling code be security critical. Marking the method that uses SuppressUnmanagedCodeSecurity with the SecurityCriticalAttribute attribute makes this requirement more obvious for callers of the method.
How to fix violations
To fix a violation of this rule, mark the method or type with the SecurityCriticalAttribute attribute.
When to suppress warnings
Do not suppress a warning from this rule.
Code
using System;
using System.Runtime.InteropServices;
using System.Security;
namespace TransparencyWarningsDemo
{
public class SafeNativeMethods
{
// CA2145 violation - transparent method marked SuppressUnmanagedCodeSecurity. This should be fixed by
// marking this method SecurityCritical.
[DllImport("kernel32.dll", SetLastError = true)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool Beep(uint dwFreq, uint dwDuration);
}
}