CA2141:Transparent methods must not satisfy 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 TransparentMethodsMustNotSatisfyLinkDemands
CheckId CA2141
Category Microsoft.Security
Breaking Change Breaking

Cause

A security transparent method calls a method in an assembly that is not marked with the AllowPartiallyTrustedCallersAttribute (APTCA) attribute, or a security transparent method satisfies a SecurityAction.LinkDemand for a type or a method.

Rule Description

Satisfying a LinkDemand is a security sensitive operation which can cause unintentional elevation of privilege. Security transparent code must not satisfy LinkDemands, because it is not subject to the same security audit requirements as security critical code. Transparent methods in security rule set level 1 assemblies will cause all LinkDemands they satisfy to be converted to full demands at run time, which can cause performance problems. In security rule set level 2 assemblies, transparent methods will fail to compile in the just-in-time (JIT) compiler if they attempt to satisfy a LinkDemand.

In assemblies that usee Level 2 security, attempts by a security transparent method to satisfy a LinkDemand or call a method in a non-APTCA assembly raises a MethodAccessException; in Level 1 assemblies the LinkDemand becomes a full Demand.

How to Fix Violations

To fix a violation of this rule, mark the accessing method with the SecurityCriticalAttribute or SecuritySafeCriticalAttribute attribute, or remove the LinkDemand from the accessed method.

When to Suppress Warnings

Do not suppress a warning from this rule.

Example

In this example, a transparent method attempts to call a method that has a LinkDemand. This rule will fire on this code.

using System;
using System.Security.Permissions;


namespace TransparencyWarningsDemo
{

    public class TransparentMethodSatisfiesLinkDemandsClass
    {
        [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
        public void LinkDemandMethod() { }


        public void TransparentMethod()
        {
            // CA2141 violation - transparent method calling a method protected with a link demand.  Any of the
            // following fixes will work here:
            //  1. Make TransparentMethod critical
            //  2. Make TransparentMethod safe critical
            //  3. Remove the LinkDemand from LinkDemandMethod  (In this case, that would be recommended anyway
            //     since it's level 2 -- however you could imagine it in a level 1 assembly)
            LinkDemandMethod();
        }
    }
}