A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca5392 below:

CA5392: Use DefaultDllImportSearchPaths attribute for P/Invokes (code analysis) - .NET

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:

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


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4