C#idiomatic C#
ca5392fundamentals/code-analysis/quality-rules

Code analysis

CA5392: Use DefaultDllImportSearchPaths attribute for P/Invokes

Provides information about code analysis rule CA5392, including causes, how to fix violations, and when to suppress it.

CA5392 Security enabled by default in .NET 10: No
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

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

Rule description

By default, P/Invoke functions using System.Runtime.InteropServices.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 System.Runtime.InteropServices.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.

csharp
#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.

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

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

Pseudo-code examples

csharp
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

csharp
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