CA5392: Use DefaultDllImportSearchPaths attribute for P/Invokes

Property Value
Rule ID CA5392
Title Use DefaultDllImportSearchPaths attribute for P/Invokes
Category Security
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 9 No

Cause

The DefaultDllImportSearchPathsAttribute is not specified for a Platform Invoke (P/Invoke) function.

Rule description

By default, P/Invoke functions using DllImportAttribute probe a number of directories, including the current working directory for the library to load. This can be a security issue for certain applications, leading to DLL hijacking.

For example, if a malicious DLL with the same name as the imported one is placed under the current working directory, which will be searched firstly by default, then the malicious DLL could be loaded.

For more information, see Load Library Safely.

How to fix violations

Use DefaultDllImportSearchPathsAttribute to specify the DLL search path explicitly for the assembly or the method.

When to suppress warnings

It's safe to suppress this rule if:

  • You're sure the loaded assembly is what you want. For example, your application runs on a trusted server and you completely trust the files.
  • The imported assembly is a commonly used system assembly, like user32.dll, and the search path strategy follows the Known DLLs mechanism.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

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

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

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

For more information, see How to suppress code analysis warnings.

Pseudo-code examples

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);
    }
}

Solution

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: Do not use unsafe DllImportSearchPath value