CA5392:請對 P/Invokes 使用 DefaultDllImportSearchPaths 屬性

屬性
規則識別碼 CA5392
標題 請對 P/Invokes 使用 DefaultDllImportSearchPaths 屬性
類別 安全性
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 No

原因

DefaultDllImportSearchPathsAttribute平台呼叫 (P/Invoke) 函式未指定

檔案描述

根據預設,P/Invoke 函式會使用 DllImportAttribute 探查數個目錄,包括程式庫要載入的目前工作目錄。 這可以是特定應用程式的安全性問題,進而導致 DLL 攔截。

例如,如果名稱與匯入的 DLL 同名的惡意 DLL 會放在目前的工作目錄中,依預設會先搜尋該目錄,則可能會載入惡意 DLL。

如需詳細資訊,請參閱 保管庫 載入連結庫。

如何修正違規

使用 DefaultDllImportSearchPathsAttribute 來明確指定元件或方法的 DLL 搜尋路徑。

隱藏警告的時機

如果:

  • 您確定載入的元件是您想要的元件。 例如,您的應用程式會在信任的伺服器上執行,而且您完全信任檔案。
  • 匯入的元件是常用的系統元件,例如 user32.dll,而搜尋路徑策略遵循 已知的 DLL 機制

隱藏警告

如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。

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

若要停用檔案、資料夾或項目的規則,請在組態檔中將其嚴重性設定為 。none

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

如需詳細資訊,請參閱 如何隱藏程式代碼分析警告

虛擬程式代碼範例

using System;
using System.Runtime.InteropServices;

class ExampleClass
{
    [DllImport("The3rdAssembly.dll")]
    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);
    }
}

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