Partilhar via


CA2142: Transparent code should not be protected with LinkDemands

Note

This article applies to Visual Studio 2015. 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
TypeName TransparentMethodsShouldNotBeProtectedWithLinkDemands
CheckId CA2142
Category Microsoft.Security
Breaking Change Breaking

Cause

A transparent method requires a SecurityAction or other security demand.

Rule Description

This rule fires on transparent methods which require LinkDemands to access them. Security transparent code should not be responsible for verifying the security of an operation, and therefore should not demand permissions. Because transparent methods are supposed to be security neutral, they should not be making any security decisions. Additionally, safe critical code, which does make security decisions, should not be relying on transparent code to have previously made such a decision.

How to Fix Violations

To fix a violation of this rule, remove the link demand on the transparent method or mark the method with SecuritySafeCriticalAttribute attribute if it is performing security checks, such as security demands.

When to Suppress Warnings

Do not suppress a warning from this rule.

Example

In the following example, the rule fires on the method because the method is transparent and is marked with a LinkDemand PermissionSet that contains an SecurityAction.

using System;
using System.Security.Permissions;

namespace TransparencyWarningsDemo
{

    public class TransparentMethodsProtectedWithLinkDemandsClass
    {
        // CA2142 violation - transparent code using a LinkDemand.  This can be fixed by removing the LinkDemand
        // from the method.
        [PermissionSet(SecurityAction.LinkDemand, Unrestricted = true)]
        public void TransparentMethod()
        {
        }
    }
}

Do not suppress a warning from this rule.