Events
Mar 17, 9 PM - Mar 21, 10 AM
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register nowThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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 |
The DefaultDllImportSearchPathsAttribute is not specified for a Platform Invoke (P/Invoke) function.
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.
Use DefaultDllImportSearchPathsAttribute to specify the DLL search path explicitly for the assembly or the method.
It's safe to suppress this rule if:
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.
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);
}
}
.NET feedback
.NET is an open source project. Select a link to provide feedback:
Events
Mar 17, 9 PM - Mar 21, 10 AM
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register now