CA2143: Transparent methods should not use security demands

TypeName

TransparentMethodsShouldNotDemand

CheckId

CA2143

Category

Microsoft.Security

Breaking Change

Breaking

Cause

A tranparent type or method is declaratively marked with a SecurityAction.Demand demand or the method calls the CodeAccessPermission.Demand method.

Rule Description

Security transparent code should not be responsible for verifying the security of an operation, and therefore should not demand permissions. Security transparent code should use full demands to make security decisions and safe-critical code should not rely on transparent code to have made the full demand. Any code that performs security checks, such as security demands, should be safe-critical instead.

How to Fix Violations

In general, to fix a violation of this rule, mark the method with the SecuritySafeCriticalAttribute attribute. You can also remove the demand.

When to Suppress Warnings

Do not suppress a warning from this rule.

Example

The rule files on the following code because a transparent method makes a declarative security demand.

using System;
using System.Security;
using System.Security.Permissions;

namespace TransparencyWarningsDemo
{

    public class TransparentMethodDemandClass
    {
        // CA2142 violation - transparent code using a Demand.  This can be fixed by making the method safe critical.
        [PermissionSet(SecurityAction.Demand, Unrestricted = true)]
        public void TransparentMethod()
        {
        }
    }
}

See Also

Reference

CA2142: Transparent code should not be protected with LinkDemands