Summary
Dynamic Link Library files hold procedures that Windows applications can call during execution. DLLs allow multiple programs to reference them simultaneously, saving memory, and allowing for easier modification of multiple applications.
Unless explicitly defined in the application, Microsoft Windows, by default, searches for DLL files in the following order:
- HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\KnownDLLs
- Application Directory
- C:\Windows\System32
- C:\Windows\System
- C:\Windows
- Current Directory
- PATH variables directory
DLL Search Order Hijacking works by placing a DLL with the same name in a directory that is higher in the hierarchy or removing the legitimate DLL and replacing it with another, malicious DLL. This malicious DLL can trick some analysts by appearing to be a legitimate file.
Simple Example
In this example, I wrote a simple Windows executable that calls a DLL file (HelloWorld.dll). In this case, the legitimate DLL would be located in C:\Windows\System32.
Reviewing the search order, there are two possibilities for hijacking the malicious DLL. The first would be to place a malicious DLL higher in the hierarchy (the KnownDLLs registry or the application’s directory). The other possibility is to delete the legitimate DLL and place the malicious file lower in the hierarchy (C:\Windows\System folder or C:\Windows).
The images below show a simple DLL file that prints a statement when an executable call it.
In the image below, we can see that HelloWorldRunner.exe is located in the C:\Users\SANSDFIR\Desktop\DLLSearch directory alone.
When we run HelloWorldRunner.exe, we receive the following output:
Now we will create a malicious DLL file and name it HelloWorld.dll. This will be stored in the same directory that the executable is located in:
We will place this DLL file higher up in the search order:
Now when we run the same executable, it will reference this "malicious" DLL first.
Detection
The first way to monitor for DLL Search Order Hijacking may be to identify DLLs in each of the directories to identify duplicate DLLs. If a DLL is found with the same name in C:\Windows\System32 and C:\Windows, this may indicate malicious activity. In addition, when an application is run, the application’s directory may also need to be searched.
A flaw in the method above is that it will not detect DLL Hijacking when the legitimate DLL is deleted. One solution to this may be to log the location (and name) of DLLs along with the applications that are using those DLLs. If the location of a DLL changes, additional analysis can be performed or action can be taken. Due to the large number of DLLs and files, it may be possible (and necessary) to only log applications that are using the Search Order and ignore those applications that are using the fully qualified path name of the DLL.