Fact-checked by Grok 2 weeks ago

DLL injection

DLL injection is a technique primarily used in Windows environments to execute code within the of a running by forcing it to load a (DLL). This method allows the injected DLL to access the target 's memory, resources, and security context, enabling modifications to the 's behavior without altering its original executable. While DLL injection has legitimate applications in , such as tools that into applications for monitoring and profiling, it is frequently exploited by for evasion and . Common techniques for DLL injection leverage Windows APIs to achieve remote code execution. One standard approach involves obtaining a handle to the target process with OpenProcess, allocating memory using VirtualAllocEx, writing the DLL path into that memory via WriteProcessMemory, and then creating a remote thread with CreateRemoteThread that calls LoadLibrary to load the DLL. Another legitimate method uses SetWindowsHookEx to install a system-wide or thread-specific hook, which injects a DLL into processes handling Windows messages, requiring the DLL to match the target process's bitness (32-bit or 64-bit). More advanced variants, such as reflective DLL injection, load the DLL directly into memory without writing to disk, reducing detectability but increasing complexity. In cybersecurity contexts, DLL injection serves as a injection sub-technique (T1055.001 in the ATT&CK framework) that adversaries use to mask malicious activities under legitimate process names, bypass antivirus detection, and potentially elevate privileges by targeting high-privilege like those in the Windows services. Defenses include monitoring calls like CreateRemoteThread and LoadLibrary, enforcing software restriction policies, and using detection tools to identify anomalous allocations in processes. Despite its risks, controlled DLL injection remains essential for tools in , security research, and application extensibility.

Overview

Definition and Mechanism

DLL injection is a technique used to execute arbitrary code within the address space of another process by forcing it to load a (DLL). This method allows the injected DLL to run in the context of the target process, leveraging its privileges and resources without creating a new executable instance. The basic mechanism of DLL injection generally involves several high-level steps to manipulate the target process remotely. First, the injector allocates memory in the target process's and writes the full path to the DLL into that allocated region. Next, the loading of the DLL is triggered by invoking a —such as one that handles library loading—within the target process, often through remote thread creation or hooking mechanisms. Once loaded, the DLL's executes, enabling the desired code to run seamlessly within the foreign process. Key concepts in DLL injection revolve around remote manipulation, where the injecting gains to the target's and execution despite operating system-enforced . This enables code execution in a foreign , allowing the injected code to interact directly with the target's data structures and while potentially bypassing boundaries designed to prevent inter-process interference. Historically, DLL injection emerged as a debugging tool in early Windows environments, facilitating the injection of threads or modules into running processes to analyze or modify behavior without halting execution. Over time, it has evolved for broader applications in software extension and system modification.

Purposes and Applications

DLL injection serves several legitimate purposes in software development and security. Developers frequently employ it for debugging and profiling tools to monitor and analyze running processes, allowing them to identify bugs or performance issues by hooking into application code. It also enables the extension of application functionality through plugins without modifying the core program. In security testing, antivirus scanners and intrusion detection systems use DLL injection to inject monitoring hooks into processes, enabling real-time threat detection by intercepting system calls like file access or network connections. Illicit applications of DLL injection primarily involve operations that exploit its ability to execute arbitrary code within a target 's without user consent, thereby masking malicious activities under legitimate guises. Attackers leverage it for by injecting code that restarts upon relaunches, ensuring long-term compromise. It facilitates , where low-privilege elevates access by injecting into higher-privilege processes like those running as . integration is another common use, allowing tools to into browsers or applications to steal credentials or monitor user activity stealthily. Beyond these, DLL injection plays a significant role in broader impacts such as , where analysts inject custom DLLs into target executables to log function calls or alter behaviors for vulnerability analysis. In modding communities, particularly for games, it supports the creation of custom modifications by injecting to alter , , or multiplayer features, fostering creative extensions in titles like those built on engines. For enterprise software customization, organizations use it to integrate data loss prevention (DLP) modules into applications like browsers, enforcing policies without native support. The uses of DLL injection have evolved from primarily legitimate debugging aids in the 1990s—facilitated by features like AppInit_DLLs—to prominent cybersecurity threats in the , where it enables evasion of detection. This technique is formally classified under ATT&CK as T1055.001 (Process Injection: Dynamic-link Library Injection), highlighting its role in adversarial tactics like defense evasion and lateral movement.

Background Knowledge

Dynamic-link libraries (DLLs) are executable files that contain code, data, and resources which multiple processes can load and use dynamically at , enabling shared functionality across applications without embedding the code directly into each executable. This design allows programs to reference external modules for common operations, such as graphics rendering or file handling, rather than duplicating them. On systems, the equivalent concept is shared object files (typically with .so extensions), managed by a to provide similar reusability. DLLs on Microsoft Windows follow the (PE) file format, which structures the file with a header for compatibility, followed by a PE header containing metadata like the image base address and section alignment, and multiple sections for (.text), initialized data (.data), and resources. The export table lists functions and symbols available to other modules, while the import table specifies dependencies on external DLLs, and an optional function, such as DllMain, handles initialization when the DLL is loaded or unloaded. This format ensures that DLLs can be mapped efficiently into a process's , with relocations adjusting addresses as needed during loading. The loading process begins when an application calls a function like LoadLibrary on Windows, which invokes the operating system's loader—primarily through ntdll.dll—to search for the DLL via predefined paths, validate its integrity, map it into the process's , and resolve imports by linking to already-loaded dependencies. On systems, the ld.so performs analogous tasks: it interprets the executable's program headers, locates shared objects using environment variables or configuration files, loads them into memory, and applies relocations to fix up symbol references before transferring control to the main program. In both cases, the loader ensures that the DLL's code segments are shared across processes where possible, optimizing resource use. The primary advantages of DLLs include code sharing, which reduces overall by allowing multiple applications to access the same loaded instance, and enhanced modularity that facilitates development by separating reusable components from core application logic. However, a notable disadvantage is "," where conflicting versions of the same DLL can cause compatibility issues, as applications may inadvertently overwrite or fail to locate the required variant during loading.

Process Address Spaces and Execution

In modern operating systems, each operates within its own , which provides an over physical to ensure between processes. This is divided into distinct segments, including the for executable instructions, the for initialized and uninitialized global variables, the for dynamic allocation, and the stack for local variables and function calls. The operating system enforces this by mapping virtual addresses to physical pages through page tables, preventing one from directly accessing another's without explicit permission. The execution of code within a occurs through , which are the basic units of CPU scheduling. A typically begins with a primary that loads and executes the program's , such as main() in C programs; additional can be created to enable concurrent execution within the shared . The manages execution flow via context switching, where the CPU state—including registers, , and stack pointer—of the current is saved, and that of the next scheduled is restored, allowing multitasking without . All in a share the same and resources, but each maintains private execution context to support parallelism. Accessing another process's from a remote process requires elevated permissions to circumvent the kernel's mechanisms. In Windows, operations like writing to remote memory demand specific access rights, such as PROCESS_VM_WRITE and PROCESS_VM_OPERATION, typically granted via a obtained with OpenProcess(); without privileges like SeDebugPrivilege, such attempts fail with access denied errors. Similarly, in systems, cross-process memory manipulation often relies on mechanisms like , which permits a tracer process to attach to a tracee only if they share the same effective user ID or the tracer holds the CAP_SYS_PTRACE capability. These restrictions protect system integrity by limiting unauthorized inter-process interactions. Both Windows (using the Win32/PE format) and systems (using ) employ a comparable process model centered on virtual address spaces for and resource management. In each, the loader maps executable segments into the virtual space at , establishing boundaries for code execution while the kernel handles paging and protection; this shared foundation enables portable concepts like dynamic linking, though implementation details vary.

Injection Methods on Microsoft Windows

CreateRemoteThread with LoadLibrary

The CreateRemoteThread with LoadLibrary method represents one of the earliest and most straightforward techniques for DLL injection on Microsoft Windows, leveraging built-in functions to load a into the of a target . This approach involves creating a remote thread within the target process that executes the LoadLibrary function, which in turn maps the specified DLL into the process's memory and invokes its . It has been a staple for both legitimate tools and malicious software due to its simplicity and reliance on core manipulation APIs. The process begins with obtaining a to the target process using the OpenProcess function, which requires appropriate access rights such as PROCESS_CREATE_THREAD, PROCESS_QUERY_INFORMATION, PROCESS_VM_OPERATION, PROCESS_VM_WRITE, and PROCESS_VM_READ. Next, memory is allocated in the target process's via VirtualAllocEx to store the full path of the DLL to be injected. The DLL path string is then written to this allocated memory using WriteProcessMemory. A remote thread is subsequently created in the target process with CreateRemoteThread, specifying the address of LoadLibraryW (or LoadLibraryA for ANSI) as the thread's starting routine and the address of the DLL path as the ; upon execution, LoadLibrary loads the DLL and returns its as the thread's code, which can be retrieved via GetExitCodeThread. Finally, the allocated memory is freed with VirtualFreeEx, and handles are closed to clean up resources. To perform this injection, the injecting typically requires the SeDebugPrivilege, which enables access to arbitrary regardless of ownership or security descriptors, particularly for system-protected targets like lsass.exe; without it, OpenProcess may fail with ERROR_ACCESS_DENIED. Additionally, bitness compatibility is critical: a 32-bit cannot directly create threads in a 64-bit using standard , as CreateRemoteThread fails across architectures due to instruction set differences, necessitating separate 32-bit and 64-bit binaries or advanced techniques like API redirection for cross-architecture injection. The DLL itself must match the target's bitness to load successfully. This method's advantages include its use of native, well-documented , making it easy to implement without external dependencies, and its applicability to any , including services, without relying on user interfaces or queues. However, it has notable limitations: the DLL must reside on disk, exposing it to file-based detection; the creation of anomalous threads can be monitored by endpoint detection tools via API hooks or event tracing; and on modern Windows versions, enhanced protections like Protected Process Light may block access to sensitive targets. Historically, the technique became prevalent with the availability of CreateRemoteThread in (1996) and was widely adopted in early for persistence and evasion, such as in trojans that injected into explorer.exe to hide activities.

SetWindowsHookEx

SetWindowsHookEx is a function that facilitates DLL injection by installing a hook procedure into the system's message-processing chain, compelling the target process to load the specified DLL when intercepting relevant events. The mechanism involves an injecting application first loading the target DLL— which must export a hook procedure of type HOOKPROC— and obtaining its module handle. The injector then invokes SetWindowsHookEx, passing the hook type identifier, the address of the exported hook function, the DLL's module handle, and the ID of the target thread (set to 0 for global hooks affecting all threads in the desktop). Upon occurrence of a hooked event in the target process, the operating system maps the DLL into that process's if not already present, invokes its DllMain entry point, and executes the hook procedure to handle the message. This process requires the injector to run with sufficient privileges to access the target, and architecture matching is enforced: a 32-bit DLL injects only into 32-bit processes, while a 64-bit DLL targets 64-bit processes, with mismatches resulting in hook execution within the injector's context rather than the target. Various hook types supported by SetWindowsHookEx enable this injection, particularly those requiring DLL-based procedures for cross-process operation. Keyboard hooks (WH_KEYBOARD) monitor keystroke messages sent to target windows, hooks (WH_MOUSE) intercept mouse actions, and hooks (WH_CBT) track window-related events like creation or . Global hooks, such as low-level variants WH_KEYBOARD_LL and WH_MOUSE_LL, extend across all threads but differ in that low-level hooks do not mandate DLLs and operate at a deeper system level without injecting into every process. For effective DLL injection into remote processes, thread-specific or global hooks necessitating a DLL are preferred, as the system automatically loads the DLL into affected processes to invoke the procedure. The hook is installed at the start of the chain, ensuring it processes events before others. This injection method offers advantages in subtlety, as it emulates legitimate event monitoring—such as input handling—allowing malicious or monitoring code to execute within trusted processes while evading basic process-based defenses. It is particularly effective for applications, requiring no direct manipulation and enabling broad coverage by targeting all threads with a global hook. However, drawbacks include performance overhead from the sequential hook chain, where each procedure processes and forwards messages, potentially slowing system responsiveness during high event volumes. Injection is limited to processes handling Windows messages, excluding non- or console applications, and requires explicit uninstallation via UnhookWindowsHookEx to prevent persistent DLL loading and resource exhaustion. Additionally, global hooks impact all desktop applications, raising visibility risks. SetWindowsHookEx-based DLL injection finds legitimate application in tools, where intercept and augment input events across processes to support features like on-screen keyboards, voice-to-text conversion, or software that modifies interactions in . In malicious contexts, it has been prevalent in keyloggers since , exploiting keyboard to capture keystrokes remotely without altering process handles directly, thereby enabling credential theft in targeted applications. Such injections can be detected through monitoring for anomalous installations or chain modifications.

AppInit_DLLs and DLL Search Order Hijacking

AppInit_DLLs is a mechanism that enables the loading of specified dynamic-link libraries (DLLs) into the of at startup. The configuration is stored in the registry key HKEY_LOCAL_MACHINE\SOFTWARE\[Microsoft](/page/Microsoft)\Windows NT\CurrentVersion\Windows\AppInit_DLLs, where the value contains a semicolon-separated list of full paths to the DLLs to be injected. When a initializes and loads user32.dll—a core library for functions—the system automatically loads these DLLs into the before the application's is called, allowing the injected DLLs to execute code early in the lifecycle. This feature was introduced in to facilitate hooking for system-wide modifications, such as those used by or tools. The injection via AppInit_DLLs primarily affects interactive processes that depend on user32.dll, which includes most graphical user interface (GUI) applications but excludes console-only or service processes that do not load this library. To set up the injection, an administrator must edit the registry value and ensure the target DLLs are accessible, often placing them in trusted directories like %SystemRoot%\System32. However, this broad applicability has made it a persistence technique for , as the DLLs gain execution in nearly all user-mode processes without requiring per-process targeting. Due to risks, including system deadlocks and exploitation by threats, deactivated the feature by default in and introduced stricter controls in later versions. In and , DLLs must be digitally signed by a from a trusted authority if the LoadAppInit_DLLs value is enabled, and the feature is further restricted or disabled in and beyond when Secure Boot is active. DLL search order hijacking exploits the predefined sequence in which Windows searches for DLLs when an application calls functions like LoadLibrary without specifying a full path, allowing attackers to substitute malicious DLLs for legitimate ones. The default search order for unpackaged applications, when Safe DLL search mode is disabled, prioritizes the current , the application's , the system (%SystemRoot%\System32), the 16-bit system , the Windows , and finally the directories in the . By placing a malicious DLL with the same name as an expected library in an earlier-searched location—such as the current or application folder—an attacker can ensure it loads instead of the intended system DLL, executing arbitrary code in the target's context. This vulnerability has been recognized in security advisories since at least 2007, with addressing related binary planting issues in updates for and other components. To implement DLL search order hijacking, an attacker with write access to a vulnerable directory copies the malicious DLL there, often naming it to match a library loaded implicitly by the target executable, such as version.dll or rpcrt4.dll. For instance, if an application runs from a user-writable and loads a DLL without qualification, the hijacked file in that folder takes precedence over the system version. Vulnerabilities of this type were highlighted in early analyses around 2000 but gained prominence in research by 2007, leading to widespread patching efforts. A key mitigation is Safe DLL search mode, enabled by default since 2 and controlled via the registry value HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\SafeDllSearchMode set to 1, which reorders the search to deprioritize the current directory (placing it last after PATH) and favor system locations first. Additional protections include using SetDllDirectory to exclude unsafe paths or specifying full paths in load calls, though these require application-level changes.

Reflective DLL Injection

Reflective DLL injection is an advanced technique for loading dynamic-link libraries (DLLs) into a target process on Microsoft Windows without relying on the standard operating system loader or filesystem access. Unlike traditional DLL injection methods that invoke such as LoadLibrary, this approach enables the DLL to load itself entirely in , enhancing evasion against monitoring tools that track calls or disk activity. The technique leverages principles, where the DLL includes its own loader to handle parsing, relocation, and execution independently. The process begins with the injection of the raw DLL image—typically as a Portable Executable (PE) file—directly into the target process's memory space, often via shellcode or remote thread creation. A small bootstrap shellcode is then executed, which transfers control to the DLL's embedded ReflectiveLoader function. This custom PE loader performs several critical steps: it first determines its own position in memory by parsing the PE headers; allocates additional memory regions as needed; copies and maps the DLL's sections into the allocated space; applies base relocations to adjust addresses for the new memory location; and resolves imports by manually processing the import table, calling LoadLibraryA and GetProcAddress only for external dependencies while minimizing system interactions. Finally, the loader invokes the DLL's entry point, DllMain, with the DLL_PROCESS_ATTACH parameter to initialize the library, after which control returns to the original process flow. This self-contained loading avoids registration in the Process Environment Block (PEB), making the DLL invisible to standard enumeration tools. Originating from work by security researcher Stephen Fewer at Harmony Security, reflective DLL injection was first detailed in 2008 as a method to perform library loading without invoking the Windows loader, thereby bypassing hooks on common injection s. The primary benefits include heightened stealth, as no LoadLibrary call is made to alert API monitors, and support for in-memory-only payloads that never touch the disk, reducing forensic footprints compared to filesystem-dependent techniques. These advantages make it particularly useful for post-exploitation scenarios where persistence and evasion are paramount. Despite its strengths, reflective DLL injection presents challenges, particularly in manual handling of PE relocations and import resolution, which require precise to avoid crashes or detection from malformed memory patterns. Variants have emerged to address limitations, such as integrating reflective loading with process hollowing, where the DLL replaces the legitimate code in a suspended , further obfuscating execution. In the 2020s, the technique remains prevalent in advanced malware campaigns, including like NetWalker that employs reflective loading for fileless execution, and is classified as a variant of process injection under ATT&CK technique T1055.001.

Injection Methods on Unix-like Systems

LD_PRELOAD Environment Variable

The LD_PRELOAD environment variable is a feature of the in systems, particularly those using the GNU C Library (), that enables users to specify a list of shared object files (.so) to load before any other libraries during program execution. This mechanism allows the preloaded libraries to override functions from subsequently loaded libraries by providing symbols with higher priority in the symbol resolution process. Introduced as part of the GNU ld.so in the early 1990s alongside the adoption of the binary format, LD_PRELOAD was originally intended for , testing, and extending application behavior without modifying . In operation, a user sets the LD_PRELOAD variable to the absolute or relative path of one or more shared object files, separated by colons or spaces, before launching a target ; the then loads these objects first, applying the standard library search rules to resolve dependencies. For instance, if a malicious .so file is specified, it can intercept calls to standard functions like those in libc by implementing wrappers that execute arbitrary code before or instead of invoking the original implementation. The variable's effect is inherited by child processes spawned by the initial program, propagating the preloading behavior unless explicitly cleared, which requires the or to have permission to modify the . This method's scope is limited to newly launched processes, as it influences the initial loading phase rather than attaching to running ones, making it suitable for local scenarios where an attacker can control the execution environment. Its simplicity—requiring only manipulation—facilitates rapid deployment in exploits, such as library functions to bypass or exfiltrate data, as seen in various campaigns. However, detectability is a key drawback; system administrators can inspect s in process listings or use tools like checks to identify suspicious preloads, and modern systems often ignore LD_PRELOAD in secure-execution modes, such as for set-user-ID binaries, to prevent abuse.

ptrace-based Injection

Ptrace-based injection is a technique employed on Unix-like systems, particularly Linux, to load a shared library (equivalent to a DLL) into the address space of a running process by leveraging the ptrace system call, which enables one process (the tracer) to observe and control another (the tracee). This method is commonly used for debugging, runtime instrumentation, and, in adversarial contexts, for evading detection by executing code within a legitimate process. The ptrace system call originated in Version 6 AT&T UNIX in 1975 and was later incorporated into 4.3BSD in 1986, providing foundational support for process tracing across Unix variants. Variants of ptrace-based injection for loading shared libraries appeared in Linux exploits as early as the early 2000s, such as in privileged process hijacking vulnerabilities targeting kernel versions 2.2.x and 2.4.x. To perform ptrace-based injection, the injecting process requires the CAP_SYS_PTRACE Linux capability or root privileges, as these govern access to ptrace operations; without them, attachment to non-child processes is denied to prevent unauthorized tracing. This technique can handle multi-threaded targets, as ptrace attachments and operations apply per-thread within a process, allowing the tracer to pause and modify execution across threads while maintaining synchronization via signals like SIGSTOP. The process begins with the tracer issuing PTRACE_ATTACH on the target process ID (PID) using the ptrace system call, which stops the tracee and delivers a SIGSTOP signal, effectively pausing its execution for inspection and modification. Once attached, the tracer reads the tracee's registers with PTRACE_GETREGS to preserve state and scans for writable memory regions, often using /proc//maps to identify suitable locations like heap areas allocated via malloc. Subsequent steps involve writing the path to the target into the tracee's using PTRACE_POKEDATA or PTRACE_POKETEXT, which allow byte-granular modifications to or segments, bypassing typical protections since grants elevated access. The tracer then injects a small —such as that calls the dlopen function from libc—to load the library; this is written into executable , and the tracee's pointer (e.g., on ) is altered via PTRACE_SETREGS to redirect execution to the . Upon dlopen invocation, the is mapped into the tracee's , executing its initialization routine (e.g., via constructors); the tracer resumes the tracee with PTRACE_CONT or PTRACE_DETACH, restoring original registers and to minimize disruption. In cases involving signals, the tracer may intercept and modify signal handlers to facilitate cleaner injection without altering the program's observable behavior. A key advantage of -based injection is its ability to target already-running processes without requiring process restarts or environment modifications, making it suitable for dynamic analysis tools like the GNU Debugger (GDB), which relies on ptrace for insertion and code stepping. This contrasts with preload methods by enabling runtime attachment to live processes, including those with elevated privileges, though it introduces overhead from process suspension and potential race conditions in multi-threaded scenarios.

ld.so.preload and Global Preloading

The /etc/ld.so.preload file provides a system-wide mechanism for preloading shared libraries into all dynamically linked processes on systems, particularly , at startup. This file contains a whitespace- or colon-separated list of paths to shared object files (.so) that the (ld.so or ld-linux.so) loads before the program's standard dependencies. The reads /etc/ld.so.preload during process initialization for every , injecting the specified libraries early in the loading sequence to allow them to override or extend functions from standard libraries like libc. Editing this file requires privileges, as it resides in the /etc directory and affects all users and processes system-wide; changes take effect for newly launched processes immediately after editing the file; existing processes continue using the previous configuration until restarted, but the file must be valid to avoid loading errors. This approach contrasts with per-process environment variables like LD_PRELOAD, offering global persistence but at higher visibility. A related , /etc/ld.so.conf, specifies directories for the to search for libraries, which ldconfig uses to build the /etc/ld.so.cache for efficient resolution; while it enables path-based risks, it differs from /etc/ld.so.preload by focusing on search paths rather than mandatory preloading of specific objects. Misconfiguration of /etc/ld.so.preload can lead to system instability, such as failed library resolutions or crashes in critical processes, making it suitable only for temporary fixes like library patches rather than routine use. Although visible and thus rarely chosen for malicious purposes, /etc/ld.so.preload has been exploited in rootkits since the on Unix variants, including , to hook system calls for persistence and evasion; for instance, the Rocke group modified it to intercept libc functions and conceal mining activities.

Security Implications

Malicious Uses in Malware

DLL injection serves as a core technique for authors to execute malicious code within the of legitimate processes, thereby concealing activities and leveraging the trust associated with system binaries such as explorer.exe or . This approach allows adversaries to perform actions like , keylogging, or further deployment without spawning suspicious new processes, as the injected code inherits the parent process's privileges and context. Historically, like has employed DLL sideloading to inject payloads into trusted applications, exploiting legitimate DLL loading paths to maintain persistence and propagate via campaigns. On systems, similar persistence is achieved through LD_PRELOAD, where prepends malicious libraries to the dynamic linker's search path, function calls in processes like sshd for credential theft or backdoor access. For instance, the TeamTNT group has utilized LD_PRELOAD in containerized environments to evade detection while mining and exfiltrating data from infrastructures. This technique enables code execution in trusted daemons, mirroring Windows DLL injection by blending malicious behavior with normal system operations. Malware leverages DLL injection for , particularly by targeting high-privilege processes to bypass (UAC) on Windows, allowing unprompted elevation to administrative rights. Adversaries inject into processes like consent.exe to execute commands with elevated tokens, facilitating deeper system compromise such as kernel-mode access for rootkits. For evasion, injected DLLs often masquerade as legitimate modules by mimicking known library names or using reflective loading to avoid disk writes, thereby sidestepping signature-based antivirus and process tools. According to the 2025 Picus Red Report, process injection techniques like T1055.001 account for a significant portion of observed adversarial actions, comprising part of the top 10 methods responsible for 93% of malicious activities across analyzed campaigns. Recent case studies highlight the ongoing prevalence of DLL injection in sophisticated threats. In early 2025, ValleyRAT, a multi-stage remote access trojan attributed to Chinese actors, used DLL injection via sideloaded libraries to persist in enterprise networks, enabling lateral movement and data theft while evading detection. Similarly, the SmashJacker hijacker, reported in March 2024, exploited AppInit_DLLs for injection into processes, establishing long-term over sessions and redirecting for financial gain. These incidents underscore how DLL injection remains a high-impact vector for both initial access and sustained operations in targeted attacks.

Detection Methods

Detection of DLL injection involves a combination of behavioral monitoring, static analysis, and advanced heuristics to identify unauthorized code execution in process address spaces across Windows and systems. These methods focus on observing runtime activities, examining loaded modules, and analyzing memory artifacts for anomalies indicative of injection attempts. Behavioral detection techniques emphasize real-time monitoring of system calls and process behaviors associated with common injection vectors. On Windows, tools like Sysmon can log Event ID 8, which captures remote thread creation via APIs such as CreateRemoteThread, often used to invoke LoadLibrary for DLL loading in another process. Event Tracing for Windows (ETW) further enables auditing of these API calls, allowing defenders to correlate thread injections with suspicious parent-child process relationships. (ProcMon), a utility, tracks anomalous thread starts and memory mappings in real time, flagging unexpected executable regions or file accesses during injection. On systems, similar behavioral analysis uses tools like to trace system calls such as or dlopen, revealing deviations from normal library loading patterns. Static analysis complements behavioral methods by inspecting the state of loaded libraries without requiring active execution. On Windows, the ListDLLs utility enumerates all DLLs loaded into a by PID or name, enabling identification of unexpected or unsigned modules through options like -u for unsigned DLLs or -d to search for specific libraries. mismatches can be verified by comparing loaded DLL hashes against known good values using tools like Sigcheck, highlighting tampered or injected binaries. On , commands such as list open shared libraries per process, while examining /proc//maps reveals memory-mapped files; discrepancies in expected library paths or anonymous mappings signal potential injections. Additionally, ldd outputs trees, allowing checks for non-contiguous or extraneous DT_NEEDED entries in binaries via readelf. Advanced detection employs heuristics tailored to stealthier techniques like reflective DLL injection, which avoids disk artifacts by loading directly into . Windows Defender ATP uses instrumentation on like VirtualAlloc and VirtualProtect to model normal memory allocation patterns in processes such as browsers or applications, alerting on deviations like unusual RWX (read-write-execute) regions or oversized allocations without corresponding drops. (EDR) solutions enhance this by integrating behavioral analytics; for instance, Falcon detects DLL injection through monitoring and memory scanning for fileless threats, while employs to identify process hollowing and reflective loading via anomalous code execution flows. Cross-platform memory forensics tools like provide post-incident analysis capabilities, updated in recent versions to handle 2024-era threats including advanced injections. The malfind plugin scans process memory dumps for injected code by detecting executable regions in non-executable sections or hidden DLLs unlinked from the Process Environment Block (PEB), applicable to both Windows PE files and ELF binaries. On , Volatility plugins examine /proc maps equivalents in memory images to spot shared object injections, such as those via LD_PRELOAD, by validating against structures.

Prevention and Mitigation

Built-in System Protections

Modern operating systems incorporate several built-in mechanisms to thwart DLL injection attempts by enforcing memory protections, restricting process access, and randomizing load addresses. On Windows, Protected Process Light (), introduced in , designates certain processes with elevated protection levels that prevent lower-privilege code, including injected DLLs, from accessing or modifying their memory space. Address Space Layout Randomization () randomizes the base addresses of modules, including DLLs, making it difficult for attackers to predict memory locations for injection payloads. Control Flow Guard (CFG), available since , validates indirect control flow transfers to block execution of injected code that alters program flow. Additionally, the AppInit_DLLs registry mechanism, which allowed DLL loading into all processes, was disabled by default starting in to reduce injection vectors. On systems, such as , seccomp filters restrict the system calls available to processes, limiting capabilities like memory mapping or process attachment that could facilitate DLL injection. The Linux Security Module enforces restrictions via the kernel.yama.ptrace_scope parameter, which by default (value 1) allows ptrace attachment only to descendant processes or those with the same user ID, preventing arbitrary injection into unrelated processes. RELRO (Relocation Read-Only) hardens the dynamic loader by marking sections like the Global Offset Table (GOT) and Procedure Linkage Table (PLT) as read-only after relocation, protecting against modifications that could redirect control to injected code. Additionally, the mseal(2) , introduced in 6.10 (July 2024), allows sealing of memory regions to prevent future modifications, further mitigating injection attempts that rely on altering process memory. These protections have evolved significantly over time. ASLR originated in the Linux kernel patch, with its first implementation published in 2001 to randomize stack, heap, and library mappings against buffer overflow exploits. Windows integrated ASLR in (2007) and enhanced it in (2015) with features like bottom-up randomization and forced ASLR for system DLLs to cover more entropy bits. adopted ASLR in kernel 2.6.12 (2005) and improved it in the 3.x series (starting 2011) with position-independent executables (PIE) support and full randomization for mmap allocations. By 2025, stricter (Write XOR Execute) policies have been reinforced in both Windows and kernels, enforcing non-executable memory pages by default via enhanced Data Execution Prevention (DEP) and NX bits. Despite these defenses, built-in protections are not impervious and can be bypassed with elevated privileges, such as through kernel-mode driver exploits that grant arbitrary memory write access, allowing attackers to disable ASLR or PPL checks.

Developer and Administrator Best Practices

Developers can mitigate risks associated with DLL injection by validating the digital signatures of DLLs prior to loading them into a process, ensuring that only trusted and unmodified libraries are executed. Implementing code signing for all custom DLLs further enforces integrity checks, allowing applications to reject unsigned or tampered modules during runtime. To prevent hijacking via search order vulnerabilities, developers should always specify fully qualified explicit paths when calling APIs such as LoadLibrary, avoiding reliance on the system's default search paths that could include untrusted directories. Additionally, avoiding unsafe APIs like SearchPath for locating DLLs reduces exposure, as these functions follow a different and less secure search order compared to standard loading mechanisms. Administrators play a crucial role in hardening systems against DLL injection by restricting the SeDebugPrivilege, which limits the ability of processes to access and manipulate remote process memory necessary for techniques like CreateRemoteThread-based injection. On Windows systems, deploying policies to whitelist only signed and approved executables and DLLs helps enforce code integrity, though administrators must audit rules regularly to account for potential bypasses using flags like LOAD_IGNORE_CODE_AUTHZ_LEVEL. For systems, implementing SELinux policies confines processes to prevent unauthorized loading, such as restricting access to shared objects that could enable ptrace-based or LD_PRELOAD injections. Auditing environment variables, particularly LD_PRELOAD and LD_LIBRARY_PATH, during process launches ensures that no malicious preloading occurs, with tools like setenv or custom scripts used to sanitize inputs in privileged contexts. Enabling SafeDLLSearchMode via prioritizes system directories in the DLL search order, reducing the risk of loading malicious libraries from the current or untrusted paths; this setting is controlled through the registry key HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\SafeDllSearchMode and applies domain-wide for consistent enforcement. Administrators should also monitor for injection risks using auditing features to log calls like VirtualAllocEx and WriteProcessMemory, enabling proactive threat hunting. Providing targeted training on DLL injection risks, including recognition of vectors and safe configuration practices, equips teams to identify and respond to potential compromises early. As of 2025, integrating Software Bill of Materials (SBOM) into development pipelines allows developers and administrators to track all components, including third-party DLLs, for vulnerabilities or malicious insertions in the , aligning with updated CISA guidelines for enhanced visibility and rapid remediation. Adopting zero-trust models per NIST SP 800-207 recommendations, such as application sandboxing and micro-segmentation, further prevents DLL injection by isolating processes and enforcing continuous verification of resource access, assuming no implicit trust in any component.

Code Examples

Windows Implementation

DLL injection on Windows commonly employs the CreateRemoteThread function to execute LoadLibraryA in the context of a target process, thereby loading the specified DLL into its address space. This approach requires appropriate privileges, such as SeDebugPrivilege, to access the target process. The following C++ code snippet demonstrates the full implementation, including error handling for each step and proper resource cleanup.
cpp
#include <windows.h>
#include <tlhelp32.h>
#include <iostream>
#include <string>

// Function to find process ID by name
DWORD GetProcessIdByName(const std::wstring& processName) {
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hSnapshot == INVALID_HANDLE_VALUE) return 0;

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

    if (Process32FirstW(hSnapshot, &pe32)) {
        do {
            if (processName == pe32.szExeFile) {
                CloseHandle(hSnapshot);
                return pe32.th32ProcessID;
            }
        } while (Process32NextW(hSnapshot, &pe32));
    }

    CloseHandle(hSnapshot);
    return 0;
}

// Function to inject DLL using CreateRemoteThread
bool InjectDLL(DWORD processId, const char* dllPath) {
    // Open handle to target process with full access
    HANDLE hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | 
                                  PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, 
                                  FALSE, processId);
    if (!hProcess) {
        std::cerr << "Failed to open process. Error: " << GetLastError() << std::endl;
        return false;
    }

    // Allocate memory in target process for DLL path
    SIZE_T pathSize = strlen(dllPath) + 1;
    void* pDllPath = VirtualAllocEx(hProcess, NULL, pathSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
    if (!pDllPath) {
        std::cerr << "Failed to allocate memory. Error: " << GetLastError() << std::endl;
        CloseHandle(hProcess);
        return false;
    }

    // Write DLL path to allocated memory
    if (!WriteProcessMemory(hProcess, pDllPath, dllPath, pathSize, NULL)) {
        std::cerr << "Failed to write to process memory. Error: " << GetLastError() << std::endl;
        VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    // Get address of LoadLibraryA in kernel32.dll
    HMODULE hKernel32 = GetModuleHandleA("kernel32.dll");
    if (!hKernel32) {
        std::cerr << "Failed to get kernel32 module handle." << std::endl;
        VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }
    LPTHREAD_START_ROUTINE pLoadLibrary = (LPTHREAD_START_ROUTINE)GetProcAddress(hKernel32, "LoadLibraryA");
    if (!pLoadLibrary) {
        std::cerr << "Failed to get LoadLibraryA address. Error: " << GetLastError() << std::endl;
        VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    // Create remote thread to execute LoadLibraryA
    HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, pLoadLibrary, pDllPath, 0, NULL);
    if (!hThread) {
        std::cerr << "Failed to create remote thread. Error: " << GetLastError() << std::endl;
        VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    // Wait for thread completion
    WaitForSingleObject(hThread, INFINITE);

    // Optional: Retrieve HMODULE returned by LoadLibraryA
    DWORD exitCode = 0;
    GetExitCodeThread(hThread, &exitCode);
    // exitCode now holds the HMODULE of the injected DLL if successful (non-zero)

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

    std::cout << "DLL injection completed. HMODULE: " << exitCode << std::endl;
    return true;
}

int main() {
    // Example: Inject into notepad.exe
    std::wstring targetProcess = L"notepad.exe";
    DWORD pid = GetProcessIdByName(targetProcess);
    if (pid == 0) {
        std::cerr << "Target process not found." << std::endl;
        return 1;
    }

    const char* dllPath = "C:\\path\\to\\your\\inject.dll";  // Full path to your DLL
    if (InjectDLL(pid, dllPath)) {
        std::cout << "Injection successful!" << std::endl;
    } else {
        std::cout << "Injection failed." << std::endl;
    }

    return 0;
}
This code begins by opening a handle to the target process using OpenProcess, requesting permissions for thread creation, memory operations, and querying, which are essential for subsequent API calls. If successful, VirtualAllocEx reserves and commits a readable/writable memory region in the target process's address space to hold the DLL file path string. WriteProcessMemory then copies the DLL path into this allocated memory, ensuring the target process can access it. Next, the code retrieves the address of from using and , as requires the entry point function's address within the target process. is invoked to start a new thread in the target process, passing the address as the start routine and the allocated DLL path as its parameter; upon execution, loads the DLL and returns its HMODULE via the thread's exit code. The main thread waits for completion with , retrieves the exit code using to verify success (a non-zero value indicates the HMODULE), and finally frees the allocated memory with before closing handles. All error paths include appropriate cleanup to prevent resource leaks. To compile this code in Visual Studio, create a new Console App project targeting x64 (to match common process architectures), include the Windows SDK (version 10.0 or later), and link against kernel32.lib and user32.lib implicitly via the default Win32 subsystem; no additional flags are typically needed beyond /EHsc for exception handling. For testing, launch a simple target process such as via the Windows Run dialog (Win+R, type "notepad"), then execute the injector with administrator privileges to ensure access rights; verify injection by checking if the DLL's DllMain is called (e.g., via logging to a file from the DLL). This technique should only be used in controlled, ethical environments for security research or debugging purposes on processes you own, as unauthorized injection violates system integrity and may trigger antivirus detection or legal issues. This CreateRemoteThread-based method is foundational and can be adapted to variants like asynchronous procedure calls (APCs) or inline hooking by modifying the remote execution strategy.

Unix-like Implementation

In Unix-like systems, particularly Linux, DLL injection is commonly achieved through the LD_PRELOAD environment variable, which instructs the dynamic linker (ld.so) to load specified shared objects before others, allowing them to override functions from the standard C library or other dependencies. This method is particularly useful for runtime interposition, such as debugging or extending program behavior without modifying the source code. The following example demonstrates overriding the malloc and free functions to log allocations, using a shared library compiled for this purpose.

Shared Library Code (mymalloc.c)

The shared library intercepts malloc and free calls by providing wrapper functions that log activity and delegate to the originals via dlsym with RTLD_NEXT, which resolves the next implementation in the load order.
c
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <malloc.h>  // For malloc hooks, optional for basic override

// Original functions
static void* (*real_malloc)(size_t) = NULL;
static void (*real_free)(void*) = NULL;

// Wrapper for malloc
void* malloc(size_t size) {
    if (!real_malloc) {
        real_malloc = dlsym(RTLD_NEXT, "malloc");
    }
    void* ptr = real_malloc(size);
    printf("[mymalloc] Allocated %zu bytes at %p\n", size, ptr);
    return ptr;
}

// Wrapper for free
void free(void* ptr) {
    if (!real_free) {
        real_free = dlsym(RTLD_NEXT, "free");
    }
    printf("[myfree] Freeing %p\n", ptr);
    real_free(ptr);
}
To initialize the wrappers early, a constructor function can be added using GCC's __attribute__((constructor)), which executes upon library loading before main program execution. For example, append this to the code:
c
__attribute__((constructor))
static void init(void) {
    printf("[mymalloc init] Library loaded via LD_PRELOAD\n");
}
Compile the shared library with GCC using position-independent code (-fPIC) and shared object flags (-shared), linking against libdl for dlsym: gcc -Wall -shared -fPIC -o mymalloc.so mymalloc.c -ldl.

Test Program (test.c)

Create a simple binary that allocates and frees memory to demonstrate the override:
c
#include <stdio.h>
#include <stdlib.h>

int main() {
    printf("Test program starting\n");
    void* ptr1 = malloc(1024);
    void* ptr2 = malloc(512);
    free(ptr1);
    free(ptr2);
    printf("Test program ending\n");
    return 0;
}
Compile it normally: gcc -o test test.c.

Usage Script

Use a shell script to set LD_PRELOAD and execute the test program. The variable specifies the path to the shared library, loading it before libc.so.
bash
#!/bin/bash
export LD_PRELOAD=./mymalloc.so
./test
unset LD_PRELOAD  # Clean up after execution
Running the script outputs logs from the wrappers, confirming the override, such as allocation details and initialization message if a constructor is used.

Breakdown

The dlsym from <dlfcn.h> retrieves the original malloc and symbols lazily on first call, ensuring the wrapper chains to the system's implementation without recursion. No explicit dlopen or dlclose is needed here, as LD_PRELOAD handles loading; however, for more complex scenarios, dlopen could load additional libraries dynamically. The constructor attribute places the init in the .ctors section, executed by the during preload. Compilation requires -ldl only if using dlsym; omit for pure overrides without delegation.

Testing

To verify injection, run the test with strace to trace dynamic linker calls: strace -e trace=dlopen LD_PRELOAD=./mymalloc.so ./test 2>&1 | grep mymalloc.so, which shows the preload loading before libc functions. ldd ./test lists dependencies but omits preloads, as they are runtime-only; use ldd on the library itself to confirm its ELF format. Expected output includes preload logs interleaved with program execution.

Caveats

LD_PRELOAD works for non-root users on standard binaries but is ignored in secure-execution mode for set-user-ID or set-group-ID programs to prevent privilege escalation. Non-root limitations include inability to preload into privileged processes without capabilities like CAP_SYS_PTRACE. Distribution differences arise from security policies: Ubuntu (Debian-based) allows broad use by default, while CentOS (RHEL-based) may enforce restrictions via SELinux, requiring policy adjustments for preloads in confined contexts. Always test on the target distribution, as glibc versions may affect symbol resolution.

References

  1. [1]
    What is DLL Injection? - JumpCloud
    Sep 10, 2025 · The injected DLL gains complete access to the target process's memory space, resources, and security context. Process Address Space refers to ...Missing: explanation | Show results with:explanation
  2. [2]
    Dynamic Link Library Injection (DLL Injection) - Zimperium
    Learn about dynamic link library injection (DLL injection) -- a method malicious actors use to insert malicious code into running processes.
  3. [3]
    Ten process injection techniques: A technical survey of common and ...
    Jul 18, 2017 · Although there are numerous process injection techniques, in this blog I present ten techniques seen in the wild that run malware code on behalf of another ...
  4. [4]
    SetWindowsHookExA function (winuser.h) - Win32 - Microsoft Learn
    Feb 8, 2023 · SetWindowsHookEx can be used to inject a DLL into another process. A 32-bit DLL cannot be injected into a 64-bit process, and a 64-bit DLL ...
  5. [5]
    Dynamic-link Library Injection, Sub-technique T1055.001 - Enterprise
    Adversaries may inject dynamic-link libraries (DLLs) into processes in order to evade process-based defenses as well as possibly elevate privileges.
  6. [6]
    [PDF] An Empirical Study of DLL Injection Bugs in the Firefox Ecosystem
    How- ever, injecting arbitrary code, while it is a very powerful technique, can easily cause severe bugs, such as crashes, in the host software. As can be seen ...
  7. [7]
    Debugging and DLL-Injection - Information Security Stack Exchange
    Jan 28, 2013 · A common use of this function is to inject a thread into a process that is being debugged to issue a break. However, this use is not recommended.Detecting reflective DLL injectionScyllaHide DLL Injection - Information Security Stack ExchangeMore results from security.stackexchange.com
  8. [8]
    DLL Injection: Part One - LRQA
    Feb 25, 2015 · DLL injection is a technique that can be used by legitimate software to add functionality, aid with debugging, or reverse engineer software ...Missing: origins | Show results with:origins
  9. [9]
    Mitigate DLL Injection Attacks - Apriorit
    Feb 8, 2024 · Ensure robust protection of your Windows software from DLL injection attacks. Discover practical examples of how to detect and prevent DLL ...<|separator|>
  10. [10]
    Suspicious DLL Loaded for Persistence or Privilege Escalation
    Identifies the loading of a non Microsoft signed DLL that is missing on a default Windows install (phantom DLL) or one ...
  11. [11]
    4 Ways Adversaries Hijack DLLs | CrowdStrike
    Dec 30, 2022 · DLL hijacking is a technique used to load malicious code for the purposes of defense evasion, persistence and privilege escalation.
  12. [12]
    How mods are made for Unity games. Chapter 1: Inject mods into a ...
    May 21, 2020 · How to inject mods into a Unity game using game and engine libraries modification, DLL input address table hooking, DLL proxying, ...
  13. [13]
    Improving Firefox Stability in the Enterprise by Reducing DLL Injection
    Mar 25, 2025 · Beginning in version 138, Firefox will offer an alternative to DLL injection for Data Loss Prevention (DLP) deployments in enterprise environments.
  14. [14]
    Dynamic-Link Libraries (Dynamic-Link Libraries) - Win32 apps
    May 31, 2022 · A dynamic-link library (DLL) is a module that contains functions and data that can be used by another module (application or DLL).
  15. [15]
    About Dynamic-Link Libraries - Win32 apps | Microsoft Learn
    Jan 7, 2021 · Dynamic linking allows a module to include only the information needed to locate an exported DLL function at load time or run time.
  16. [16]
    ld.so(8) - Linux manual page - man7.org
    The programs ld.so and ld-linux.so* find and load the shared objects (shared libraries) needed by a program, prepare the program to run, and then run it.
  17. [17]
    PE Format - Win32 apps - Microsoft Learn
    Jul 14, 2025 · This document specifies the structure of executable (image) files and object files under the Microsoft Windows family of operating systems.
  18. [18]
    Inside Windows: Win32 Portable Executable File Format in Detail
    Within a PE file, there's an array of data structures, one per imported DLL. Each of these structures gives the name of the imported DLL and points to an ...
  19. [19]
    An In-Depth Look into the Win32 Portable Executable File Format ...
    The Win32 PE format is a standard executable format. This article covers exports, debug, thread local storage, resources, and more. It is well-structured and ...
  20. [20]
    LoadLibraryA function (libloaderapi.h) - Win32 apps - Microsoft Learn
    Feb 9, 2023 · Loads the specified module into the address space of the calling process. The specified module may cause other modules to be loaded.Missing: injection | Show results with:injection<|separator|>
  21. [21]
    Avoiding DLL Hell: Introducing Application Metadata in the Microsoft ...
    Oct 24, 2019 · In this article, I'll present you with a 5000-foot overview of metadata. I'll look at the major features and important details of this key .NET innovation.
  22. [22]
    Virtual Address Spaces - Windows drivers | Microsoft Learn
    Jun 28, 2024 · The virtual addresses used by different processes are isolated. The code in one process can't alter the physical memory that is being used by ...
  23. [23]
    About Processes and Threads - Win32 apps | Microsoft Learn
    Jul 14, 2025 · A thread is the entity within a process that can be scheduled for execution. All threads of a process share its virtual address space and system resources.
  24. [24]
    Process Security and Access Rights - Win32 apps | Microsoft Learn
    Jul 14, 2025 · Process Security and Access Rights. Feedback. Summarize this article for me. In this article. The Microsoft Windows security model enables you ...
  25. [25]
    ptrace(2) - Linux manual page - man7.org
    The ptrace() system call provides a means by which one process (the "tracer") may observe and control the execution of another process (the "tracee"), and ...
  26. [26]
    CreateRemoteThread function (processthreadsapi.h) - Win32 apps
    Nov 1, 2022 · The CreateRemoteThread function causes a new thread of execution to begin in the address space of the specified process.
  27. [27]
    Three Ways to Inject Your Code into Another Process - CodeProject
    So, to use the CreateRemoteThread & LoadLibrary technique , follow these steps: Retrieve a HANDLE to the remote process ( OpenProcess ). Allocate memory for the ...
  28. [28]
    OpenProcess function (processthreadsapi.h) - Win32 apps
    Nov 1, 2022 · If the caller has enabled the SeDebugPrivilege privilege, the requested access is granted regardless of the contents of the security descriptor.
  29. [29]
    DLL Injection and WoW64 - corsix.org
    Apr 20, 2010 · For an x86 process interacting with an x64 process, CreateRemoteThread always fails, even if the given start address points to x64 code and the ...
  30. [30]
    Hooks Overview - Win32 apps - Microsoft Learn
    Sep 15, 2025 · The SetWindowsHookEx function always installs a hook procedure at the beginning of a hook chain. ... DLL module. A thread-specific hook ...Missing: injection | Show results with:injection
  31. [31]
    Using SetWindowsHookEx for DLL injection on windows
    Jun 3, 2013 · Dive into DLL injections using SetWindowsHookEx with our detailed guide. Access all code examples on our Github profile!
  32. [32]
    3 Effective DLL Injection Techniques for Setting API Hooks - Apriorit
    May 21, 2020 · Explore three different DLL injection techniques and learn how to modify the flow of Windows-based systems and applications with API hooks.DLL injection with the... · Injecting DLL with the... · Injecting DLL with remote...Missing: implications | Show results with:implications
  33. [33]
    Keystroke Logging - Stanford Computer Science
    In Windows, this is accomplished by using the publicly available Windows function SetWindowsHookEx() to monitor all keystrokes. Since these are at the top ...
  34. [34]
    AppInit DLLs and Secure Boot - Win32 apps | Microsoft Learn
    Sep 29, 2022 · The AppInit_DLLs infrastructure provides an easy way to hook system APIs by allowing custom DLLs to be loaded into the address space of every interactive ...About AppInit_DLLs · AppInit_DLLs and secure boot
  35. [35]
    Dynamic-link library search order - Win32 apps | Microsoft Learn
    Feb 8, 2023 · The standard DLL search order used by the system depends on whether or not safe DLL search mode is enabled.Factors That Affect... · Search Order For Packaged... · Search Order For Unpackaged...
  36. [36]
    Dynamic-Link Library Security - Win32 apps | Microsoft Learn
    Jan 7, 2021 · If an attacker gains control of one of the directories on the DLL search path, it can place a malicious copy of the DLL in that directory.
  37. [37]
    Dynamic Linker Hijacking, Sub-technique T1574.006 - Enterprise
    When Ebury is running as an OpenSSH server, it uses LD_PRELOAD to inject its malicious shared module in to programs launched by SSH sessions. ... history.Procedure Examples · Mitigations · Detection Strategy<|control11|><|separator|>
  38. [38]
    Linux rootkits explained – Part 1: Dynamic linker hijacking | Wiz Blog
    Jul 5, 2023 · Dynamic linker hijacking via LD_PRELOAD is a Linux rootkit technique utilized by different threat actors in the wild.
  39. [39]
    Process Injection: Ptrace System Calls, Sub-technique T1055.008
    The ptrace system call enables a debugging process to observe and control another process (and each individual thread), including changing memory and register ...
  40. [40]
    Linux Kernel 2.2.x/2.4.x - Privileged Process Hijacking ... - Exploit-DB
    Apr 10, 2003 · Linux Kernel 2.2.x/2.4.x - Privileged Process Hijacking Privilege Escalation (2). CVE-2003-0127CVE-4565 . local exploit for Linux platform.
  41. [41]
    Ptrace documentation, draft #6 - LWN.net
    Jun 8, 2011 · Attachment and subsequent commands are per-thread: in multi-threaded process ... ), where pid is a TID of the corresponding Linux thread.
  42. [42]
    The Definitive Guide to Linux Process Injection - Akamai
    Nov 14, 2024 · ptrace is a system call used to debug remote processes. The initiating process is able to inspect and modify the debugged process memory and ...
  43. [43]
    Linux ptrace introduction AKA injecting into sshd for fun - XPN Blog
    Apr 19, 2017 · I wanted to tackle some Linux process injection, with the aim of loading a shared object into another process address space without having to resort to LD_ ...
  44. [44]
    How-To: Linux Process Injection – GreyNoise Labs
    Jan 28, 2025 · In this post, I'll show you how I developed a tool to load an arbitrary shared library ( .so ) file into another process's memory space.
  45. [45]
    Reloading /etc/ld.so.preload without starting a new shell - Server Fault
    Feb 6, 2023 · To force the dynamic linker to reload the libraries specified in /etc/ld.so.preload, you can use the command: sudo ldconfig -v -n /etc/ld.so.preload.
  46. [46]
    ldconfig(8) - Linux manual page - man7.org
    ldconfig configures dynamic linker run-time bindings by creating links and a cache to shared libraries found in specified directories.
  47. [47]
    UNIX and Linux based Rootkits Techniques and Countermeasures
    In the early 1990s, the first rootkit techniques for Unix systems were ... One well-known user space hooking technique is the abuse of the LD PRELOAD ...
  48. [48]
    MITRE ATT&CK T1055.001 Process Injection: DLL Injection
    Mar 11, 2025 · DLL Injection is a process injection technique that allows adversaries to execute malicious code by forcing a legitimate process to load a dynamic-link library ...
  49. [49]
    Attack Chain Overview: Emotet in December 2020 and January 2021
    Mar 8, 2021 · Unit 42 researchers have identified and analyzed a new update of Emotet, the notorious banking Trojan, that has been active in the wild since December 2020.
  50. [50]
    TeamTNT evades detection with new malware using ld_preload ...
    Apr 21, 2021 · HelloKitty: The ransomware affecting CD Projekt Red and Cyberpunk 2077 · DreamBus Botnet: An analysis · Kobalos malware: A complex Linux threat.
  51. [51]
    Exploring Windows UAC Bypasses: Techniques and Detection ...
    May 14, 2023 · In this research article, we will take a look at a collection of UAC bypasses, investigate some of the key primitives they depend on, ...
  52. [52]
    Bypass User Account Control, Sub-technique T1548.002 - Enterprise
    Adversaries may bypass UAC mechanisms to elevate process privileges on system. Windows User Account Control (UAC) allows a program to elevate its privileges.
  53. [53]
    Red Report 2025 - Picus Security
    Rating 4.9 (214) The top 10 techniques covered 93% of the total malicious activities in 2025 and are headed by T1055 Process Injection, closely followed by T1059 Command and ...Methodology · 93% Of Malicious Actions... · 14 Malicious Actions Per...
  54. [54]
    Rat Race: ValleyRAT Malware Targets Organizations with New ...
    Feb 3, 2025 · This blog provides a full threat analysis of ValleyRAT, a complex multi-stage malware capable of evading detection and response solutions.Valleyrat Infection Chain · Tier0. Dll · Valleyrat As Payload
  55. [55]
    Process Injection Detection with Sysmon - LetsDefend
    Nov 22, 2020 · In this article, we will explain what the process injection technique is and how it can be detected with Sysmon.
  56. [56]
    Detecting Process Injection - by Adeem Mawani
    Jul 16, 2024 · In this article, we will explore the Windows logging mechanisms available for defenders to detect and prevent process injection, as well as the evasion ...
  57. [57]
    Tracking down library injections on Linux | Network World
    Jun 26, 2019 · Library injections are less common on Linux than they are on Windows, but they're still a problem. Here's a look at how they work and how to identify them.Missing: lsmod lsof
  58. [58]
    ListDLLs - Sysinternals - Microsoft Learn
    Jul 4, 2016 · ListDLLs is a utility that reports the DLLs loaded into processes. You can use it to list all DLLs loaded into all processes, into a specific process, or to ...
  59. [59]
    ELF shared library injection forensics - Backtrace Engineering
    Apr 22, 2016 · The focus of this blog post is going to be centered around how to identify legitimate shared library objects vs. suspicious and potentially malicious ones.Missing: lsmod lsof<|separator|>
  60. [60]
    Detecting reflective DLL loading with Windows Defender ATP
    Nov 13, 2017 · In 2008, Stephen Fewer of Harmony Security introduced the reflective DLL loading process that loads a DLL into a process without being ...
  61. [61]
    4 Popular Defensive Evasion Techniques in 2021 - CrowdStrike
    Sep 17, 2021 · The DLL injection technique enables adversaries to inject code from a malicious DLL and execute it under the context of a target process. With ...
  62. [62]
    What is Process Injection​​​? Techniques & Preventions
    Jul 22, 2025 · Process injection is one of the most important techniques in cyber security. This technique works by dropping code into another already running process address ...
  63. [63]
    How to Use Volatility for Memory Forensics and Analysis - Varonis
    Using Volatility to look for injected code is done by using the 'malfind' feature. This displays a list of processes that Volatility suspects may contain ...Pslist · Pstree · Netscan
  64. [64]
    Advanced Memory Forensics - Detecting Code Injection Techniques ...
    Jul 9, 2024 · Process Hollowing: Replacing the legitimate code of a process with malicious code. Reflective DLL Injection: Injecting and executing a DLL ...
  65. [65]
    seccomp(2) - Linux manual page - man7.org
    seccomp() returns 0. On error, if SECCOMP_FILTER_FLAG_TSYNC was used, the return value is the ID of the thread that caused the synchronization failure.<|separator|>
  66. [66]
    Hackers exploit gaping Windows loophole to give their malware ...
    Jul 11, 2023 · Hackers are using open source software that's popular with video game cheaters to allow their Windows-based malware to bypass restrictions Microsoft put in ...
  67. [67]
    Secure loading of libraries to prevent DLL preloading attacks
    To prevent this attack, applications can remove the current working directory (CWD) from the DLL search path by calling the SetDllDirectory API by using an ...
  68. [68]
    Security considerations for AppLocker | Microsoft Learn
    Oct 1, 2024 · This article for the IT professional describes the security considerations you need to address when implementing AppLocker.
  69. [69]
    How can SELinux Enforcing mode protect against vulnerabilities ...
    Jun 3, 2024 · SELinux Mitigation: SELinux can confine the sudo process to restrict its access to sensitive files and directories. This would limit the damage ...
  70. [70]
    Is there any way to block LD_PRELOAD and LD_LIBRARY_PATH ...
    Jul 21, 2014 · Yes, there is a way: don't let that user run arbitrary code. Give them a restricted shell, or better, only a predefined set of commands.Why isn't LD_PRELOAD disabled by default in Linux?Controlling uninitialized memory with LD_PRELOADMore results from security.stackexchange.com
  71. [71]
    2025 Minimum Elements for a Software Bill of Materials (SBOM) - CISA
    Aug 22, 2025 · Building on the 2021 NTIA SBOM Minimum Elements, this update aims to help agencies and organizations to manage software risk more effectively.Missing: DLL injection
  72. [72]
    [PDF] Zero Trust Architecture - NIST Technical Series Publications
    Zero trust focuses on protecting resources (assets, services, workflows, network accounts, etc.), not network segments, as the network location is no longer.
  73. [73]
    VirtualAllocEx function (memoryapi.h) - Win32 apps | Microsoft Learn
    Jul 27, 2022 · Reserves, commits, or changes the state of a region of memory within the virtual address space of a specified process.
  74. [74]
    WriteProcessMemory function (memoryapi.h) - Win32 apps
    May 14, 2022 · Writes data to an area of memory in a specified process. The entire area to be written to must be accessible or the operation fails.
  75. [75]
    mymalloc.c - andrew.cmu.ed
    ... LD_PRELOAD mechanism * * Example (Assume a.out calls malloc and free): * linux> gcc -Wall -DRUNTIME -shared -fpic -o mymalloc.so mymalloc.c -ldl * * bash ...