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

Copy
   using System;
   using System.Text;
   using System.Runtime.InteropServices;
   
   namespace CS.UNSAFE.PRELOAD
   {
       class Program
       {
           [DllImport("CoreDLL.dll")];
          public static extern void SimulateGameDLL(int a, int b);
      }
  }

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

Copy
   using System;
   using System.Text;
   using System.Runtime.InteropServices;
   
   namespace CS.UNSAFE.PRELOAD
   {
       class Program
       {
           [DllImport("C:\\space\\user32.dll", CharSet = CharSet.Unicode)]
          public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);
      }
  }

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

Related checkers

Security training

Application security training materials provided by Secure Code Warrior.