CA5393:请勿使用不安全的 DllImportSearchPath 值

属性
规则 ID CA5393
标题 请勿使用不安全的 DllImportSearchPath 值
类别 安全性
修复是中断修复还是非中断修复 非中断
在 .NET 8 中默认启用

原因

使用 <xref:System.Runtime.InteropServices.DllImportSearchPath?displayProperty=fullName 的其中一个不安全值:

  • AssemblyDirectory
  • UseDllDirectoryForDependencies
  • ApplicationDirectory
  • LegacyBehavior

规则说明

默认的 DLL 搜索目录和程序集目录中可能存在恶意 DLL。 或者根据应用程序运行的位置,应用程序的目录中可能存在恶意 DLL。

有关详细信息,请参阅安全加载库

如何解决冲突

改为使用 DllImportSearchPath 的安全值来指定显式搜索路径:

  • SafeDirectories
  • System32
  • UserDirectories

何时禁止显示警告

在以下情况下,可禁止显示此规则的警告:

  • 确定已加载的程序集是所需的程序集。
  • 导入的程序集是常用的系统程序集(如 user32.dll),并且搜索路径策略遵循已知的 DLL 机制

抑制警告

如果只想抑制单个冲突,请将预处理器指令添加到源文件以禁用该规则,然后重新启用该规则。

#pragma warning disable CA5393
// The code that's violating the rule is on this line.
#pragma warning restore CA5393

若要对文件、文件夹或项目禁用该规则,请在配置文件中将其严重性设置为 none

[*.{cs,vb}]
dotnet_diagnostic.CA5393.severity = none

有关详细信息,请参阅如何禁止显示代码分析警告

配置代码以进行分析

使用下面的选项来配置代码库的哪些部分要运行此规则。

可以仅为此规则、为适用的所有规则或为适用的此类别(安全性)中的所有规则配置此选项。 有关详细信息,请参阅代码质量规则配置选项

不安全的 DllImportSearchPath 位

你可以配置 DllImportSearchPath 的哪个值对于分析是不安全的。 例如,若要指定代码不应使用 AssemblyDirectoryUseDllDirectoryForDependenciesApplicationDirectory,请将以下键值对添加到项目中的 .editorconfig 文件:

dotnet_code_quality.CA5393.unsafe_DllImportSearchPath_bits = 770

应指定枚举值的按位组合的整数值。

伪代码示例

using System;
using System.Runtime.InteropServices;

class ExampleClass
{
    [DllImport("The3rdAssembly.dll")]
    [DefaultDllImportSearchPaths(DllImportSearchPath.AssemblyDirectory)]
    public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);

    public void ExampleMethod()
    {
        MessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0);
    }
}

解决方案

using System;
using System.Runtime.InteropServices;

class ExampleClass
{
    [DllImport("The3rdAssembly.dll")]
    [DefaultDllImportSearchPaths(DllImportSearchPath.UserDirectories)]
    public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);

    public void ExampleMethod()
    {
        MessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0);
    }
}

CA5392:对 P/Invoke 使用 DefaultDllImportSearchPaths 属性