07 Бер, 2023

DLL Injection

Vulnerability Assessment as a Service (VAaaS)

Tests systems and applications for vulnerabilities to address weaknesses.

DLL Injection refers to the technique of inserting a dynamic-link library (DLL) into the address space of a running process, in order to execute malicious code or to modify the behavior of the targeted application. This technique can be used for both legitimate and illegitimate purposes, such as debugging, system monitoring, or malware attacks. When a DLL is injected, it becomes part of the target process and can interact with other components of the system, including system calls and data structures. This technique can be used to bypass security measures, escalate privileges, or steal sensitive information.

Приклад уразливого коду на різних мовах програмування:


в C ++:

				
					#include <windows.h>

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved)
{
    switch (fdwReason)
    {
        case DLL_PROCESS_ATTACH:
            // Allocate memory for a string buffer
            LPSTR lpBuffer = (LPSTR)VirtualAlloc(NULL, 4096, MEM_COMMIT, PAGE_READWRITE);
            // Copy data into the buffer
            strcpy(lpBuffer, "Hello, world!");
            // Call an external function with the buffer as a parameter
            ExternalFunction(lpBuffer);
            break;
        // ...
    }
    return TRUE;
}

				
			


У цьому прикладі DllMain function is used to allocate memory for a string buffer, copy data into the buffer, and then call an external function with the buffer as a parameter. This code is vulnerable to DLL Injection because an attacker could replace the ExternalFunction call with a call to their own malicious function that is injected into the same process.

• в C#:

				
					using System;
using System.Runtime.InteropServices;

public class Program
{
    [DllImport("User32.dll")]
    public static extern int MessageBox(IntPtr h, string m, string c, int type);

    public static void Main()
    {
        // Display a message box
        MessageBox(IntPtr.Zero, "Hello, world!", "Message", 0);
    }
}

				
			


У цьому прикладі Головна function calls the MessageBox функція User32.dll library to display a message box. This code is vulnerable to DLL Injection because an attacker could replace the User32.dll library with their own malicious DLL that exports a function with the same name and parameters as MessageBox.

• в Python:

				
					import ctypes

dllHandle = ctypes.WinDLL("mydll.dll") # Load the malicious DLL
maliciousFunction = dllHandle.maliciousFunction # Get a function pointer from the DLL
maliciousFunction() # Call the function from the DLL to execute malicious code
# ...

				
			


In the this example provided, the ctypes module is used to load and execute a malicious DLL. ctypes is a foreign function library for Python that provides C-compatible data types and allows calling functions in shared libraries (DLLs) on Windows or shared objects (SOs) on Linux and macOS.

Examples of exploitation DLL Injection

Malware propagation:

Attackers can inject a malicious DLL into a legitimate process that is running with high privileges, such as a system service or a security application, in order to bypass security measures and propagate their malware to other systems.

Кейлоггінг:

Attackers can inject a DLL into a user’s browser or other application to monitor keystrokes and steal sensitive information such as passwords and credit card numbers.

Крадіжка облікових даних:

Attackers can inject a DLL into a process that handles authentication or authorization, such as a login or password reset page, to intercept user credentials and gain unauthorized access to sensitive systems.

Виконання коду:

Attackers can inject a DLL into a process and execute arbitrary code, such as downloading and executing additional malware, encrypting or deleting files, or exfiltrating sensitive data.

Підвищення привілеїв:

Attackers can inject a DLL into a process that runs with lower privileges than the attacker’s own process, and use it to elevate their privileges and gain access to sensitive resources that are otherwise unavailable.

Privilege escalation techniques for DLL Injection

Hooking:

Attackers can use a technique called function hooking to modify the behavior of a process and elevate their privileges. Function hooking involves intercepting calls to a function in a target process and redirecting them to a malicious function in a DLL injected by the attacker. By hooking sensitive functions, such as those related to authentication or authorization, attackers can gain elevated privileges and access to protected resources.

Впровадження коду:

Attackers can inject malicious code into a process using DLL Injection and use it to escalate their privileges. This can be done by injecting code into a process that runs with higher privileges than the attacker’s own process, such as a system service or a privileged user account. Once the code is executed, the attacker can use it to gain access to sensitive resources that are otherwise unavailable.

Registry hijacking:

Attackers can modify the Windows registry to inject a malicious DLL into a legitimate process that runs with high privileges. By modifying the registry keys that are responsible for loading DLLs, attackers can cause a legitimate process to load a malicious DLL instead, allowing them to execute arbitrary code and escalate their privileges.

Image file execution options (IFEO) hijacking:

Attackers can use the Image File Execution Options registry key to hijack the execution of a legitimate process and inject a malicious DLL into it. This technique involves adding a registry entry for a legitimate executable and specifying a malicious DLL as the debugger. When the executable is launched, the debugger (i.e. the malicious DLL) is also launched, allowing the attacker to inject their code into the process and escalate their privileges.

Загальна методологія та контрольний список for DLL Injection

Методологія:

  1. Identify potential entry points: The first step in testing for DLL Injection is to identify the processes that are susceptible to this type of attack. This can be done by analyzing the application’s architecture and identifying the points at which DLLs are loaded into memory.

  2. Статичний аналіз: Once the potential entry points have been identified, the next step is to perform static analysis on the application to identify any known vulnerabilities or suspicious code. This can involve analyzing the source code or the executable file using tools such as disassemblers, decompilers, and static code analyzers.

  3. Динамічний аналіз: After the static analysis has been completed, the next step is to perform dynamic analysis on the application to identify any runtime behavior that may indicate DLL Injection. This can involve using tools such as debuggers, memory analysis tools, and dynamic code analyzers.

  4. Test cases: To validate the potential vulnerabilities identified in the static and dynamic analysis, a series of test cases can be developed that attempt to inject a malicious DLL into the target application. These test cases should cover a range of scenarios, including different injection techniques, different DLLs, and different target applications.

  5. Verification: Once the test cases have been completed, the results should be verified to determine whether DLL Injection was successful and whether any security vulnerabilities exist. This can involve verifying that the malicious DLL was successfully injected, that it is able to execute arbitrary code, and that it is able to access sensitive resources.

  6. Звітність: Finally, a report should be generated that summarizes the findings of the testing, including any vulnerabilities that were identified, the severity of those vulnerabilities, and recommendations for remediation. This report can be used to inform the development team and management of the potential risks and to guide the development of a mitigation strategy.

Контрольний список:

  1. Identify the entry points for DLL loading in the application, such as LoadLibrary and CreateProcess.

  2. Check the application’s code for potential vulnerabilities, such as buffer overflows or unvalidated user input, that may allow an attacker to inject a DLL.

  3. Check the system’s DLL search order to determine if it can be manipulated to load a malicious DLL.

  4. Use tools such as debuggers and memory analysis tools to monitor the application’s behavior and detect any suspicious activity, such as DLL injection.

  5. Develop and execute test cases that attempt to inject a malicious DLL into the application using different injection techniques and DLLs.

  6. Verify that the malicious DLL was successfully injected and that it is able to execute arbitrary code and access sensitive resources.

  7. Determine the impact of the vulnerability, such as the level of privilege escalation that can be achieved and the extent of the damage that can be caused.

  8. Assess the likelihood of exploitation, including the level of effort required to exploit the vulnerability and the potential benefits to an attacker.

  9. Prioritize the vulnerabilities based on their severity and likelihood of exploitation.

  10. Generate a report that summarizes the findings of the testing, including any vulnerabilities that were identified, their severity, and recommendations for remediation.

Набір інструментів для експлуатації DLL Injection

Ручні Інструменти:

  1. DLL Injector: This is a simple tool that allows the user to manually inject a DLL into a process. It can be used to test for DLL Injection vulnerabilities and to execute arbitrary code in the context of the target process.

  2. Process Hacker: This is a powerful task manager and system monitoring tool that can be used to analyze running processes and detect suspicious activity, such as DLL Injection.

  3. OllyDbg: This is a popular debugger that can be used to analyze and modify the code of a running process. It can be used to identify potential vulnerabilities and to test for DLL Injection.

  4. Immunity Debugger: This is a powerful debugger that can be used to analyze and modify the code of a running process. It includes a range of tools for analyzing and detecting DLL Injection.

  5. Windbg: This is a debugger that can be used to analyze and debug Windows applications. It includes a range of tools for detecting and analyzing DLL Injection.

  6. API Monitor: This is a tool that allows the user to monitor the API calls made by a process. It can be used to detect and analyze DLL Injection attacks.

  7. Dependency Walker: This is a tool that can be used to analyze the DLL dependencies of a Windows application. It can be used to identify potential vulnerabilities and to test for DLL Injection.

  8. Sysinternals Suite: This is a collection of powerful system utilities that can be used to monitor and analyze Windows systems. It includes a range of tools for detecting and analyzing DLL Injection.

Автоматизовані інструменти:

  1. Process Monitor: This is a powerful tool that can be used to monitor and analyze the behavior of running processes. It can be used to detect and analyze DLL Injection attacks.

  2. Sysmon: This is a system monitoring tool that can be used to monitor and analyze the behavior of Windows systems. It includes a range of tools for detecting and analyzing DLL Injection.

  3. Process Explorer: This is a powerful task manager and system monitoring tool that can be used to analyze running processes and detect suspicious activity, such as DLL Injection.

  4. AppGuard: This is a security tool that can be used to protect Windows systems against DLL Injection attacks. It includes a range of features for detecting and blocking malicious code execution.

  5. EMET: This is a security tool that can be used to protect Windows systems against DLL Injection attacks. It includes a range of features for detecting and blocking malicious code execution.

  6. Cuckoo Sandbox: This is an automated malware analysis tool that can be used to detect and analyze DLL Injection attacks. It includes a range of tools for analyzing the behavior of malware and detecting malicious activity.

  7. Metasploit: This is a penetration testing tool that includes a range of exploits and payloads for testing and exploiting DLL Injection vulnerabilities.

  8. PowerSploit: This is a collection of PowerShell scripts that can be used to automate the detection and exploitation of DLL Injection vulnerabilities.

Плагіни для браузера:

  1. Injection Helper: This is a browser plugin that can be used to test for DLL Injection vulnerabilities in web applications. It includes a range of tools for analyzing and detecting malicious activity.

  2. ChromeDLL: This is a browser plugin that can be used to test for DLL Injection vulnerabilities in Google Chrome. It includes a range of tools for analyzing and detecting malicious activity.

Середній бал CVSS stack DLL Injection

The Common Vulnerability Scoring System (CVSS) is a standard method used to assess the severity of software vulnerabilities. The score is based on a number of factors, including the impact of the vulnerability, the ease of exploitation, and the level of access required to exploit it.

The CVSS score for a stack DLL Injection vulnerability can vary depending on the specific details of the vulnerability. However, in general, stack DLL Injection vulnerabilities are considered to be high-severity vulnerabilities due to the potential impact of an attacker being able to execute arbitrary code in the context of the vulnerable process.

The CVSS score for a stack DLL Injection vulnerability can range from 7.5 to 9.0, depending on the specifics of the vulnerability. However, it’s important to note that the CVSS score is just one metric for assessing the severity of a vulnerability, and other factors should also be considered, such as the impact on the organization, the likelihood of exploitation, and the availability of mitigations.

Загальна перерахування слабких місць (CWE)

• CWE-78: Improper Neutralization of Special Elements used in an OS Command: This CWE category relates to vulnerabilities where an attacker can inject malicious DLLs into an application, leading to the execution of arbitrary code.

• CWE-119: Improper Restriction of Operations within the Bounds of a Memory Buffer: This category relates to buffer overflow vulnerabilities that can be exploited to inject malicious DLLs into a process.

• CWE-120: Buffer Copy without Checking Size of Input: This category relates to vulnerabilities where an attacker can inject a DLL by exploiting a buffer overflow vulnerability in a program.

• CWE-129: Improper Validation of Array Index: This category relates to vulnerabilities where an attacker can exploit an array index error to inject a malicious DLL into a process.

• CWE-134: Uncontrolled Format String: This category relates to vulnerabilities where an attacker can exploit a format string vulnerability to inject a malicious DLL into a process.

• CWE-352: Підробка міжсайтових запитів (CSRF): This category relates to vulnerabilities where an attacker can inject a malicious DLL into a process by tricking a user into making a request to a vulnerable application.

• CWE-400: Неконтрольоване споживання ресурсів: This category relates to vulnerabilities where an attacker can inject a malicious DLL into a process by exploiting a resource consumption vulnerability.

• CWE-416: Використовуйте після безкоштовного: This category relates to vulnerabilities where an attacker can exploit a use-after-free vulnerability to inject a malicious DLL into a process.

• CWE-434: Необмежена завантаження файлу з небезпечним типом: This category relates to vulnerabilities where an attacker can upload a malicious DLL to a vulnerable application.

• CWE-476: NULL Pointer Dereference: This category relates to vulnerabilities where an attacker can exploit a NULL pointer dereference vulnerability to inject a malicious DLL into a process.

Top 10 CVES related to DLL Injection

• CVE-2022-34396 – Dell OpenManage Server Administrator (OMSA) version 10.3.0.0 and earlier contains a DLL Injection Vulnerability. A local low privileged authenticated attacker could potentially exploit this vulnerability, leading to the execution of arbitrary executable on the operating system with elevated privileges. Exploitation may lead to a complete system compromise.

• CVE-2022-32972 – Infoblox BloxOne Endpoint for Windows through 2.2.7 allows DLL injection that can result in local privilege escalation.

• CVE-2022-29505 – Due to build misconfiguration in openssl dependency, LINE for Windows before 7.8 is vulnerable to DLL injection that could lead to privilege escalation.

• CVE-2022-28766 – Windows 32-bit versions of the Zoom Client for Meetings before 5.12.6 and Zoom Rooms for Conference Room before version 5.12.6 are susceptible to a DLL injection vulnerability. A local low-privileged user could exploit this vulnerability to run arbitrary code in the context of the Zoom client.

• CVE-2022-24077 – Naver Cloud Explorer Beta allows the attacker to execute arbitrary code as System privilege via malicious DLL injection.

• CVE-2022-22788 – The Zoom Opener installer is downloaded by a user from the Launch meeting page, when attempting to join a meeting without having the Zoom Meeting Client installed. The Zoom Opener installer for Zoom Client for Meetings before version 5.10.3 and Zoom Rooms for Conference Room for Windows before version 5.10.3 are susceptible to a DLL injection attack. This vulnerability could be used to run arbitrary code on the victims host.

• CVE-2021-43037 – An issue was discovered in Kaseya Unitrends Backup Appliance before 10.5.5. The Unitrends Windows agent was vulnerable to DLL injection and binary planting due to insecure default permissions. This allowed privilege escalation from an unprivileged user to SYSTEM.

• CVE-2021-36216 – LINE for Windows 6.2.1.2289 and before allows arbitrary code execution via malicious DLL injection.

• CVE-2021-27971 – Alps Alpine Touchpad Driver 10.3201.101.215 is vulnerable to DLL Injection.

• CVE-2021-21518 – Dell SupportAssist Client for Consumer PCs versions 3.7.x, 3.6.x, 3.4.x, 3.3.x, Dell SupportAssist Client for Business PCs versions 2.0.x, 2.1.x, 2.2.x, and Dell SupportAssist Client ProManage 1.x contain a DLL injection vulnerability in the Costura Fody plugin. A local user with low privileges could potentially exploit this vulnerability, leading to the execution of arbitrary executable on the operating system with SYSTEM privileges.

DLL Injection подвиги

  • Meterpreter: A tool used in the Metasploit Framework that provides a powerful shell to remotely access and control compromised systems. Meterpreter uses DLL Injection to load its code into a remote process.

  • Cobalt Strike: A commercially available penetration testing tool that is often used by red teams and advanced threat actors. Cobalt Strike includes a DLL Injection capability that allows attackers to inject malicious code into a target process.

  • Reflective DLL Injection: A technique that allows attackers to load a DLL into a process without using the standard Windows API functions. Reflective DLL Injection can be used to bypass security measures that rely on monitoring API calls.

  • DLL Hijacking: A technique that involves tricking a program into loading a malicious DLL by placing the DLL in a location where the program expects to find a legitimate DLL.

  • PowerSploit: A collection of PowerShell modules that can be used for offensive purposes, including DLL Injection. PowerSploit’s DLL Injection module can be used to inject a PowerShell payload into a remote process.

  • Process Hacker: A free and open-source process viewer and debugger that includes a DLL Injection feature. Process Hacker’s DLL Injection capability can be used to load a DLL into a target process.

  • NinjaCopy: A tool that can be used to copy files to a remote system by injecting a DLL into a legitimate process and then using that process to write the file to disk.

  • Seth: A tool that can be used to hijack user sessions on Windows systems. Seth uses DLL Injection to load a malicious DLL into the Winlogon process, allowing the attacker to steal user credentials.

  • Beacon: A tool used in the Cobalt Strike framework that provides a stealthy, persistent backdoor on a compromised system. Beacon uses DLL Injection to load its code into a remote process.

  • RedLeaves: A malware family that uses DLL Injection to inject malicious code into legitimate processes on infected systems. RedLeaves is often used in targeted attacks against organizations in the financial sector.

Практикуючись в тестуванні на DLL Injection

  1. Familiarize yourself with the Windows API functions related to DLL loading and unloading. This will help you understand how DLL Injection works and the different methods that can be used.

  2. Set up a lab environment using a virtual machine or a sandboxed environment where you can safely test DLL Injection techniques without risking damage to your production system.

  3. Identify applications that are vulnerable to DLL Injection. This can be done by analyzing the code or through the use of automated vulnerability scanners.

  4. Use a variety of tools and techniques to test for DLL Injection vulnerabilities, including manual techniques such as code analysis and automated tools such as DLL injection scanners.

  5. Once you’ve identified a vulnerability, attempt to exploit it using one of the popular DLL Injection exploits mentioned earlier.

  6. Implement appropriate mitigations to address any vulnerabilities that you find. This may include modifying application code, implementing access controls, or using security software to detect and prevent DLL Injection attacks.

  7. Repeat the process and continue testing until you’ve identified and addressed all vulnerabilities.

For study DLL Injection

DLL Injection Wiki: This wiki page provides a comprehensive overview of DLL Injection, including common techniques, tools, and mitigations.

DLL Injection Techniques: This article provides an in-depth look at several DLL Injection techniques, including standard injection, reflective injection, and process hollowing.

DLL Injection Attacks: This article from Microsoft provides an overview of DLL Injection attacks and how to defend against them.

Process Hacker: Process Hacker is a free and open-source process viewer and debugger that includes a DLL Injection feature. It can be used to practice DLL Injection in a safe environment.

Metasploit Framework: The Metasploit Framework is a popular penetration testing tool that includes several DLL Injection exploits. It can be used to practice exploiting DLL Injection vulnerabilities.

Cobalt Strike: Cobalt Strike is a commercial penetration testing tool that includes a DLL Injection capability. It can be used to practice DLL Injection in a realistic scenario.

Hack The Box: Hack The Box is a platform that provides realistic simulation of real-world security challenges, including DLL Injection. It can be used to practice DLL Injection in a safe and controlled environment.

Онлайн-курси та навчальні посібники: There are several online courses and tutorials available that cover DLL Injection, including those offered by Cybrary and Pluralsight.

Books with review of DLL Injection

Практичний аналіз шкідливих програм: практичне керівництво з аналізу шкідливого програмного забезпечення by Michael Sikorski and Andrew Honig: This book provides a practical introduction to malware analysis, including a chapter on DLL Injection.

Злом сірої капелюхи: керівництво етичного хакера by Daniel Regalado, Shon Harris, and Allen Harper: This comprehensive guide to ethical hacking includes a chapter on DLL Injection.

Windows Internals, Part 1: System architecture, processes, threads, memory management, and more by Mark E. Russinovich, David A. Solomon, and Alex Ionescu: This book provides an in-depth look at the internals of the Windows operating system, including a chapter on DLL Injection.

Rootkits and Bootkits: Reversing Modern Malware and Next Generation Threats by Alex Matrosov, Eugene Rodionov, and Sergey Bratus: This book covers advanced topics in malware analysis, including rootkits, bootkits, and DLL Injection.

Windows Forensic Analysis Toolkit, Fourth Edition: Advanced Analysis Techniques for Windows 8 by Harlan Carvey: This book provides an in-depth look at Windows forensic analysis, including a chapter on DLL Injection.

Кулінарна книга і DVD-диск аналітика шкідливих програм: Інструменти і методи боротьби з шкідливим кодом by Michael Ligh, Steven Adair, Blake Hartstein, and Matthew Richard: This book provides practical recipes for analyzing and fighting malware, including a section on DLL Injection.

Black Hat Python: Програмування на Python для хакерів і пентестеров by Justin Seitz: This book teaches how to use Python for security testing and includes a chapter on DLL Injection.

The IDA Pro Book: The Unofficial Guide to the World’s Most Popular Disassembler by Chris Eagle: This book provides an in-depth guide to using IDA Pro, a popular disassembler, and includes a chapter on DLL Injection.

Розширене тестування на проникнення: злом найбільш захищених мереж в світі by Wil Allsopp: This book covers advanced topics in penetration testing, including a chapter on DLL Injection.

Практичний реверс-інжиніринг: x86, x64, ARM, ядро Windows, інструменти реверсування і заплутування by Bruce Dang, Alexandre Gazet, and Elias Bachaalany: This book provides an in-depth look at reverse engineering, including a chapter on DLL Injection.

List of payloads DLL Injection

  • Зворотна оболонка: This payload can be used to establish a reverse shell to a remote attacker, allowing them to execute commands on the victim’s system.

  • Keylogger: A keylogger payload can be used to capture keystrokes on the victim’s system, allowing an attacker to steal sensitive information like usernames and passwords.

  • Credential harvester: This payload can be used to harvest credentials from various sources on the victim’s system, such as web browsers, email clients, and FTP clients.

  • Remote Access Trojan (RAT): A RAT payload can be used to provide a remote attacker with complete control over the victim’s system, including the ability to steal files, install additional malware, and execute commands.

  • DDoS bot: A DDoS bot payload can be used to turn the victim’s system into a bot that can be used to launch Distributed Denial of Service (DDoS) attacks against a target.

  • Bitcoin miner: A Bitcoin miner payload can be used to mine cryptocurrency on the victim’s system, using the victim’s resources to generate income for the attacker.

  • File downloader: This payload can be used to download additional malware or tools onto the victim’s system, allowing the attacker to execute more advanced attacks.

  • Screen capture: A screen capture payload can be used to capture screenshots of the victim’s system, allowing an attacker to monitor their activities.

  • Audio recorder: An audio recorder payload can be used to record audio from the victim’s system, allowing an attacker to eavesdrop on their conversations.

  • Browser hijacker: A browser hijacker payload can be used to modify the victim’s web browser settings, redirecting them to malicious websites or injecting unwanted advertisements.

How to be protected from DLL Injection

  1. Install security updates and patches as soon as they become available to ensure that your system is protected against known vulnerabilities.

  2. Use reputable security software to scan your system regularly for malware and other threats.

  3. Only download software from reputable sources and verify that the software is authentic before installing it on your system.

  4. Turn off any services or applications that are not needed, as they may provide a vector for attack.

  5. Use the principle of least privilege, giving users and processes only the access they need to carry out their tasks.

  6. Use strong passwords and enable multi-factor authentication wherever possible to reduce the risk of unauthorized access.

  7. Enable Windows Defender Application Control to prevent the loading of unsigned DLLs.

  8. Sign your DLLs using code signing certificates to ensure that they have not been tampered with or modified.

  9. Monitor your system for suspicious activity and investigate any anomalies that you detect.

  10. Educate yourself and your users about the risks of DLL Injection and how to stay safe from these types of attacks.

Висновок

DLL Injection is a type of attack that allows an attacker to execute arbitrary code within the context of a running process by injecting malicious code into a legitimate DLL. DLL Injection attacks can be used for a variety of purposes, including stealing sensitive data, installing malware, and taking control of a system.

To prevent DLL Injection attacks, it is important to implement security best practices such as keeping software up to date, using anti-virus and anti-malware software, using least privilege access, and monitoring your system for suspicious activity. Additionally, using mitigations such as Windows Defender Application Control, whitelisting, code signing, ASLR, DEP, and CFG can help protect against DLL Injection attacks.

It is important for individuals and organizations to be aware of the risks associated with DLL Injection and to take proactive steps to protect against these types of attacks. By implementing best practices and mitigations, it is possible to reduce the risk of DLL Injection and maintain a secure computing environment.

Інші Послуги

Готові до безпеки?

зв'язатися з нами