CS.UNSAFE.DLLPRELOAD

Potential DLL-preload hijack vector

When an application loads an external library, it's important for the code to use a fully qualified path. If an insufficiently qualified path is specified, a malicious attacker can gain control of the search path and use it as a vector for remotely executing arbitrary code. This type of threat is known as binary planting or a DLL-preloading attack.

The CS.UNSAFE.DLLPRELOAD checker flags code instances in which absolute path names are not used with a DllImport attribute.

Vulnerability and risk

An attacker can use relative paths to read, modify, or overwrite critical files, bypassing security mechanisms. Failure to use a fully qualified path can allow your application to load a DLL other than that intended. An exploiter can use this vulnerability to gain user rights, achieve elevated privileges, and even take control of the system.

Mitigation and prevention

To avoid relative path problems:
  • Ensure that external libraries are loaded securely by using fully qualified path names whenever possible.
  • Store library, include, and utility files in separate directories where they can't be easily accessed.
  • Ensure error messages don't disclose path information.

Vulnerable code example

1   using System;
2   using System.Text;
3   using System.Runtime.InteropServices;
4   
5   namespace CS.UNSAFE.PRELOAD
6   {
7       class Program
8       {
9           [DllImport("CoreDLL.dll")];
10          public static extern void SimulateGameDLL(int a, int b);
11      }
12  }

In this example, the DllImport path is not absolute and is therefore susceptible to a malicious input. Klocwork reports this issue as a CS.UNSAFE.DLLPRELOAD defect at line 10.

Fixed code example

1   using System;
2   using System.Text;
3   using System.Runtime.InteropServices;
4   
5   namespace CS.UNSAFE.PRELOAD
6   {
7       class Program
8       {
9           [DllImport("C:\\space\\user32.dll", CharSet = CharSet.Unicode)]
10          public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);
11      }
12  } 

In the fixed code example, a fully qualified path has been provided with DllImport, eliminating the possibility of malicious access.

Related checkers

External guidance

Security training

Application security training materials provided by Secure Code Warrior.