CA2123:重写的链接请求应与基相同

类型名

OverrideLinkDemandsShouldBeIdenticalToBase

CheckId

CA2123

类别

Microsoft.Security

是否重大更改

原因

公共类型中的公共或受保护方法重写方法或实现接口,且没有与该接口或虚方法相同的 链接需求

规则说明

该规则将一个方法与其基方法(该基方法为另一个类型中的接口或虚方法)相匹配,然后比较两者的链接请求。 如果该方法和该基方法中的任何一个具有链接请求,而另一个不具有链接请求,则会报告冲突。

如果与该规则冲突,则恶意调用方只需调用不安全的方法,即可跳过该链接请求。

如何解决冲突

若要修复此规则的冲突,请将同一链接请求应用到重写方法或实现。 如果不可能,则使用完全请求标记该方法或完全移除特性。

何时禁止显示警告

不要禁止显示此规则发出的警告。

示例

下面的示例演示与该规则冲突的各种情况。

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

namespace SecurityRulesLibrary
{
   public interface ITestOverrides
   {  
      [EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted=true)]
      Object GetFormat(Type formatType);
   }

   public class OverridesAndSecurity : ITestOverrides
   {
      // Rule violation: The interface has security, and this implementation does not.
      object ITestOverrides.GetFormat(Type formatType)
      {
         return (formatType == typeof(OverridesAndSecurity) ? this : null);
      }

      // These two methods are overridden by DerivedClass and DoublyDerivedClass.
      [EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted=true)]
      public virtual void DoSomething()
      {
         Console.WriteLine("Doing something.");
      }

      public virtual void DoSomethingElse()
      {
         Console.WriteLine("Doing some other thing.");
      }
   }

   public class DerivedClass : OverridesAndSecurity, ITestOverrides
   {
      //  Rule violation: The interface has security, and this implementation does not.
      public object GetFormat(Type formatType)
      {
         return (formatType == typeof(OverridesAndSecurity) ? this : null);
      }

      // Rule violation: This does not have security, but the base class version does.
      public override void DoSomething()
      {
         Console.WriteLine("Doing some derived thing.");
      }

      // Rule violation: This has security, but the base class version does not.
      [EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted=true)]
      public override void DoSomethingElse()
      {
         Console.WriteLine("Doing some other derived thing.");
      }
   }

   public class DoublyDerivedClass : DerivedClass
   {
      // The OverridesAndSecurity version of this method does not have security. 
      // Base class DerivedClass's version does. 
      // The DoublyDerivedClass version does not violate the rule, but the 
      // DerivedClass version does violate the rule.
      public override void DoSomethingElse()
      {
         Console.WriteLine("Doing some other derived thing.");
      }
   }
}

请参见

概念

代码安全维护指南

链接需求