All rules
CA5392Security Enabled by default: No

Use DefaultDllImportSearchPaths attribute for P/Invokes

Use DefaultDllImportSearchPaths attribute for P/Invokes

Microsoft docs

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.

Cause

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

How to fix violations

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

Example

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

When to suppress

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.
Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0