Что такое reflective dll
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
1 contributor
Users who have contributed to this file
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Reflective DLL Injection
Reflective DLL injection is a technique that allows an attacker to inject a DLL's into a victim process from memory rather than disk.
The purpose of this lab is to:
- Test reflective DLL injection capability in metasploit
- Goof around with basic memory forensics
- Implement a simple reflective DLL injection POC by myself
- Execution is passed, either via CreateRemoteThread() or a tiny bootstrap shellcode, to the library's ReflectiveLoader function which is an exported function found in the library's export table.
- As the library's image will currently exists in an arbitrary location in memory the ReflectiveLoader will first calculate its own image's current location in memory so as to be able to parse its own headers for use later on.
- The ReflectiveLoader will then parse the host processes kernel32.dll export table in order to calculate the addresses of three functions required by the loader, namely LoadLibraryA, GetProcAddress and VirtualAlloc.
- The ReflectiveLoader will now allocate a continuous region of memory into which it will proceed to load its own image. The location is not important as the loader will correctly relocate the image later on.
- The library's headers and sections are loaded into their new locations in memory.
- The ReflectiveLoader will then process the newly loaded copy of its image's import table, loading any additional library's and resolving their respective imported function addresses.
- The ReflectiveLoader will then process the newly loaded copy of its image's relocation table.
- The ReflectiveLoader will then call its newly loaded image's entry point function, DllMain with DLL_PROCESS_ATTACH. The library has now been successfully loaded into memory.
- Finally the ReflectiveLoader will return execution to the initial bootstrap shellcode which called it, or if it was called via CreateRemoteThread, the thread will terminate.
This lab assumes that the attacker has already gained a meterpreter shell from the victim system and will now attempt to perform a reflective DLL injection into a remote process on a compromised victim system, more specifically into a notepad.exe process with PID 6156
Metasploit's post-exploitation module windows/manage/reflective_dll_inject configured:
Reflective_dll.x64.dll is the DLL compiled from Steven Fewer's reflective dll injection project on github.
After executing the post exploitation module, the below graphic shows how the notepad.exe executes the malicious payload that came from a reflective DLL that was sent over the wire from the attacker's system:
Once the metasploit's post-exploitation module is run, the procmon accurately registers that notepad created a new thread:
Let's see if we can locate where the contents of reflective_dll.x64.dll are injected into the victim process when the metasploit's post-exploitation module executes.
For that, lets debug notepad in WinDBG and set up a breakpoint for MessageBoxA as shown below and run the post-exploitation module again:
The breakpoint is hit:
- return address the code will jump to after the USER32!MessageBoxA finishes is 00000000031e103e
- inspecting assembly instructions around 00000000031e103e , we see a call instruction call qword ptr [00000000031e9208]
- inspecting bytes stored in 00000000031e9208 , ( dd 00000000031e9208 L1 ) we can see they look like a memory address 0000000077331304 (note this address)
- inspecting the EIP pointer ( r eip ) where the code execution is paused at the moment, we see that it is the same 0000000077331304 address, which means that the earlier mentioned instruction call qword ptr [00000000031e9208] is the actual call to USER32!MessageBoxA
- This means that prior to the above mentioned instruction, there must be references to the variables that are passed to the MessageBoxA function:
If we inspect the 00000000031e103e 0x30 bytes earlier, we can see some suspect memory addresses and the call instruction almost immediatley after that:
Upon inspecting those two addresses - they are indeed holding the values the MessageBoxA prints out upon successful DLL injection into the victim process:
Looking at the output of the !address function and correlating it with the addresses the variables are stored at, it can be derived that the memory region allocated for the evil dll is located in the range 031e0000 - 031f7000 :
Indeed, if we look at the 031e0000 , we can see the executable header (MZ) and the strings fed into the MessageBoxA API can be also found further into the binary:
Detecting Reflective DLL Injection with Volatility
Malfind is the Volatility's pluging responsible for finding various types of code injection and reflective DLL injection can usually be detected with the help of this plugin.
The plugin, at a high level will scan through various memory regions described by Virtual Address Descriptors (VADs) and look for any regions with PAGE_EXECUTE_READWRITE memory protection and then check for the magic bytes 4d5a (MZ in ASCII) at the very beginning of those regions as those bytes signify the start of a Windows executable (i.e exe, dll):
Note how in our case, volatility discovered the reflective dll injection we inspected manually above with WindDBG:
Implementing Reflective DLL Injection
I wanted to program a simplified Reflective DLL Injection POC to make sure I understood its internals, so this is my attempt and its high level workflow of how I've implemented it:
- Read raw DLL bytes into a memory buffer
- Parse DLL headers and get the SizeOfImage
- Allocate new memory space for the DLL of size SizeOfImage
- Copy over DLL headers and PE sections to the memory space allocated in step 3
- Perform image base relocations
- Load DLL imported libraries
- Resolve Import Address Table (IAT)
- Invoke the DLL with DLL_PROCESS_ATTACH reason
Steps 1-4 are pretty straight-forward as seen from the code below. For step 5 related to image base relocations, see my notes T1093: Process Hollowing and Portable Executable Relocations
Resolving Import Address Table
Portable Executables (PE) use Import Address Table (IAT) to lookup function names and their memory addresses when they need to be called during runtime.
When dealing with reflective DLLs, we need to load all the dependent libraries of the DLL into the current process and fix up the IAT to make sure that the functions that the DLL imports point to correct function addresses in the current process memory space.
In order to load the depending libraries, we need to parse the DLL headers and:
- Get a pointer to the first Import Descriptor
- From the descriptor, get a pointer to the imported library name
- Load the library into the current process with LoadLibrary
- Repeat process until all Import Descriptos have been walked through and all depending libraries loaded
Before proceeding, note that my test DLL I will be using for this POC is just a simple MessageBox that gets called once the DLL is loaded into the process:
Below shows the first Import Descriptor of my test DLL. The first descriptor suggests that the DLL imports User32.dll and its function MessageBoxA. On the left, we can see a correctly resolved library name that is about to be loaded into the memory process with LoadLibrary :
Below shows that the user32.dll gets loaded successfully:
After the Import Descriptor is read and its corresponding library is loaded, we need to loop through all the thunks (data structures describing functions the library imports), resolve their addresses using GetProcAddress and put them into the IAT so that the DLL can reference them when needed:
Once we have looped through all the Import Decriptors and their thunks, the IAT is considered resolved and we can now execute the DLL. Below shows a successfully loaded and executed DLL that pops a message box:
Вы используете устаревший браузер. Этот и другие сайты могут отображаться в нём некорректно.
Вам необходимо обновить браузер или попробовать использовать другой.
d0ppl4r
Старшина
Разбираем Reflective DLL Injection — технику, которую используют злоумышленники для скрытой загрузки DLL-библиотеки.
Обычно для загрузки DLL-библиотеки в Windows мы вызываем функцию LoadLibrary, которая принимает в качестве аргумента путь к библиотеке. Для этого нужно, чтобы библиотека была на диске, с которого и производится загрузка.
Но злоумышленники загружают код другим, более интересным путем.
Их техника Reflective DLL Injection позволяет внедрить код DLL-библиотеки в процесс из памяти. Основное преимущество такого подхода заключается в том, что библиотека не регистрируется в системе. В результате ее практически невозможно обнаружить ни на уровне системы, ни на уровне процесса.
Reflective DLL Injection по шагам
1. Некоторый исполняемый файл считывает DLL-библиотеку с диска в адресное пространство своего процесса и передает управление на ее экспортируемую функцию ReflectiveLoader.
2. Поскольку теперь библиотека существует в произвольном месте в памяти, ReflectiveLoader вычисляет текущее местоположение самой DLL-библиотеки в памяти. Для этого ReflectiveLoader получает адрес текущей инструкции и, двигаясь в обратном направлении, ищет байты 4D5A, соответствующие MZ-сигнатуре. Это нужно, чтобы дать библиотеке возможность анализировать свои собственные заголовки для дальнейшего запуска.
3. ReflectiveLoader определяет адрес библиотеки kernel32.dll в текущем процессе, после чего анализирует таблицу ее экспорта и находит функции LoadLibrary, GetProcAddress и VirtualAlloc, необходимые для дальнейшей загрузки.
Теперь ReflectiveLoader выделяет непрерывный участок памяти (VirtualAlloc), где и размещает код DLL-библиотеки (заголовки и секции) в соответствии с виртуальными адресами. Затем ReflectiveLoader обрабатывает свою вновь загруженную таблицу импорта: загружает необходимые библиотеки (LoadLibrary) и импортируемые из них функции (GetProcAddress).
Reflective DLL injection is a library injection technique in which the concept of reflective programming is employed to perform the loading of a library from memory into a host process. As such the library is responsible for loading itself by implementing a minimal Portable Executable (PE) file loader. It can then govern, with minimal interaction with the host system and process, how it will load and interact with the host.
Injection works from Windows NT4 up to and including Windows 8, running on x86, x64 and ARM where applicable.
The process of remotely injecting a library into a process is two fold. Firstly, the library you wish to inject must be written into the address space of the target process (Herein referred to as the host process). Secondly the library must be loaded into that host process in such a way that the library's run time expectations are met, such as resolving its imports or relocating it to a suitable location in memory.
Assuming we have code execution in the host process and the library we wish to inject has been written into an arbitrary location of memory in the host process, Reflective DLL Injection works as follows.
- Execution is passed, either via CreateRemoteThread() or a tiny bootstrap shellcode, to the library's ReflectiveLoader function which is an exported function found in the library's export table.
- As the library's image will currently exists in an arbitrary location in memory the ReflectiveLoader will first calculate its own image's current location in memory so as to be able to parse its own headers for use later on.
- The ReflectiveLoader will then parse the host processes kernel32.dll export table in order to calculate the addresses of three functions required by the loader, namely LoadLibraryA, GetProcAddress and VirtualAlloc.
- The ReflectiveLoader will now allocate a continuous region of memory into which it will proceed to load its own image. The location is not important as the loader will correctly relocate the image later on.
- The library's headers and sections are loaded into their new locations in memory.
- The ReflectiveLoader will then process the newly loaded copy of its image's import table, loading any additional library's and resolving their respective imported function addresses.
- The ReflectiveLoader will then process the newly loaded copy of its image's relocation table.
- The ReflectiveLoader will then call its newly loaded image's entry point function, DllMain with DLL_PROCESS_ATTACH. The library has now been successfully loaded into memory.
- Finally the ReflectiveLoader will return execution to the initial bootstrap shellcode which called it, or if it was called via CreateRemoteThread, the thread will terminate.
Open the 'rdi.sln' file in Visual Studio C++ and build the solution in Release mode to make inject.exe and reflective_dll.dll
To test use the inject.exe to inject reflective_dll.dll into a host process via a process id, e.g.:
Licensed under a 3 clause BSD license, please see LICENSE.txt for details.
It can be detected or mitigated?
Limiting access to specific API calls will likely have unintended side effects, such as preventing legitimate software from operating properly.
A possible mitigation could be identify or block potentially malicious software that may contain DLL injection functionality by using whitelisting tools or Software Restriction Policies.
Also, monitoring API calls indicative of the various types of code injection may generate a significant amount of data and may not be directly useful for defense, since benign use of API functions may be common and difficult to distinguish from malicious behavior.
And finally, Reflective DLL Injection uses custom function that can easily avoid detection.
The PoC has been released open-source by Andrew on GitHub, but also a closed-source tool has been released by the Mert Sarica, Antimeter Tool:
I created a small tool called antimeter which scans memory for detecting and also killing Metasploit’s meterpreter. I did not expect that much interest from the community therefore I did not implement core features like logging and autokill but suddenly antimeter got nice feedbacks so I have decided to implement these features and more for the community.
Reflective?
Reflective DLL loading refers to loading a DLL from memory rather than from disk.
Windows doesn’t have a LoadLibrary function that supports this, so to get the functionality you have to write your own, omitting some of the things Windows normally does, such as registering the DLL as a loaded module in the process , potentially bypassing DLL load monitoring.
The process of reflective DLL injection is as follows:
- Open target process with read-write-execute permissions and allocate memory large enough for the DLL.
- Copy the DLL into the allocated memory space.
- Calculate the memory offset within the DLL to the export used for doing reflective loading.
- Call CreateRemoteThread (or an equivalent undocumented API function like RtlCreateUserThread ) to start execution in the remote process, using the offset address of the reflective loader function as the entry point.
- The reflective loader function finds the Process Environment Block of the target process using the appropriate CPU register, and uses that to find the address in memory of kernel32.dll and any other required libraries.
- Parse the exports directory of kernel32 to find the memory addresses of required API functions such as LoadLibraryA , GetProcAddress , and VirtualAlloc .
- Use these functions to then properly load the DLL (itself) into memory and call its entry point, DllMain.
More information and PoC code can be reviewed on this GitHub repo by Stephen Fewer:
The process of remotely injecting a library into a process is two fold. Firstly, the library you wish to inject must be written into the address space of the target process (Herein referred to as the host process). Secondly the library must be loaded into that host process in such a way that the library's run time expectations are met, such as resolving its imports or relocating it to a suitable location in memory.
And here a video demo of a reflective injection using metacploit module:
Another technique for reflecting DLL injection is the usage of SetThreadContext() and NtContinue(), made by zerosum0x0:
In the attempt to evade AV, attackers go to great lengths to avoid the common reflective injection code execution function, CreateRemoteThread(). Alternative techniques include native API (ntdll) thread creation and user APCs (necessary for SysWow64->x64), etc.
This technique uses SetThreadContext() to change a selected thread's registers, and performs a restoration process with NtContinue(). This means the hijacked thread can keep doing whatever it was doing, which may be a critical function of the injected application.
(a PoC is available here)
About
Reflective DLL injection is a library injection technique in which the concept of reflective programming is employed to perform the loading of a library from memory into a host process.
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Reflective DLL injection is a library injection technique in which the concept of reflective programming is employed to perform the loading of a library from memory into a host process. As such the library is responsible for loading itself by implementing a minimal Portable Executable (PE) file loader. It can then govern, with minimal interaction with the host system and process, how it will load and interact with the host.
Injection works from Windows NT4 up to and including Windows 8, running on x86, x64 and ARM where applicable.
The process of remotely injecting a library into a process is two fold. Firstly, the library you wish to inject must be written into the address space of the target process (Herein referred to as the host process). Secondly the library must be loaded into that host process in such a way that the library's run time expectations are met, such as resolving its imports or relocating it to a suitable location in memory.
Assuming we have code execution in the host process and the library we wish to inject has been written into an arbitrary location of memory in the host process, Reflective DLL Injection works as follows.
- Execution is passed, either via CreateRemoteThread() or a tiny bootstrap shellcode, to the library's ReflectiveLoader function which is an exported function found in the library's export table.
- As the library's image will currently exists in an arbitrary location in memory the ReflectiveLoader will first calculate its own image's current location in memory so as to be able to parse its own headers for use later on.
- The ReflectiveLoader will then parse the host processes kernel32.dll export table in order to calculate the addresses of three functions required by the loader, namely LoadLibraryA, GetProcAddress and VirtualAlloc.
- The ReflectiveLoader will now allocate a continuous region of memory into which it will proceed to load its own image. The location is not important as the loader will correctly relocate the image later on.
- The library's headers and sections are loaded into their new locations in memory.
- The ReflectiveLoader will then process the newly loaded copy of its image's import table, loading any additional library's and resolving their respective imported function addresses.
- The ReflectiveLoader will then process the newly loaded copy of its image's relocation table.
- The ReflectiveLoader will then call its newly loaded image's entry point function, DllMain with DLL_PROCESS_ATTACH. The library has now been successfully loaded into memory.
- Finally the ReflectiveLoader will return execution to the initial bootstrap shellcode which called it, or if it was called via CreateRemoteThread, the thread will terminate.
Open the 'rdi.sln' file in Visual Studio C++ and build the solution in Release mode to make inject.exe and reflective_dll.dll
To test use the inject.exe to inject reflective_dll.dll into a host process via a process id, e.g.:
Licensed under a 3 clause BSD license, please see LICENSE.txt for details.
DLL (Dynamic-link library) are the Microsoft's implementation of the shared library concept and provide a mechanism for shared code and data, allowing a developer of shared code/data to upgrade functionality without requiring applications to be re-linked or re-compiled.
DLLs may be explicitly loaded at run-time, a process referred to simply as run-time dynamic linking by Microsoft, and its code is usually shared among all the processes that use the same DLL.
When you need to load a DLL in Windows, you need to call LoadLibrary, that takes the file path of a DLL and loads it in to memory.
This method can also used to perform a DLL injection, that inserts code in the context of another process by causing the other process to load and execute code.
The code is inserted in the form of a DLL, since DLLs are meant to be loaded at run time.
Running code in the context of another process provides adversaries many benefits, such as access to the process's memory and permissions.
It also allows adversaries to mask their actions under a legitimate process.
Users who have contributed to this file
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Reflective DLL Injection
Reflective DLL injection is a technique that allows an attacker to inject a DLL's into a victim process from memory rather than disk.
The purpose of this lab is to:
- Test reflective DLL injection capability in metasploit
- Goof around with basic memory forensics
- Implement a simple reflective DLL injection POC by myself
- Execution is passed, either via CreateRemoteThread() or a tiny bootstrap shellcode, to the library's ReflectiveLoader function which is an exported function found in the library's export table.
- As the library's image will currently exists in an arbitrary location in memory the ReflectiveLoader will first calculate its own image's current location in memory so as to be able to parse its own headers for use later on.
- The ReflectiveLoader will then parse the host processes kernel32.dll export table in order to calculate the addresses of three functions required by the loader, namely LoadLibraryA, GetProcAddress and VirtualAlloc.
- The ReflectiveLoader will now allocate a continuous region of memory into which it will proceed to load its own image. The location is not important as the loader will correctly relocate the image later on.
- The library's headers and sections are loaded into their new locations in memory.
- The ReflectiveLoader will then process the newly loaded copy of its image's import table, loading any additional library's and resolving their respective imported function addresses.
- The ReflectiveLoader will then process the newly loaded copy of its image's relocation table.
- The ReflectiveLoader will then call its newly loaded image's entry point function, DllMain with DLL_PROCESS_ATTACH. The library has now been successfully loaded into memory.
- Finally the ReflectiveLoader will return execution to the initial bootstrap shellcode which called it, or if it was called via CreateRemoteThread, the thread will terminate.
This lab assumes that the attacker has already gained a meterpreter shell from the victim system and will now attempt to perform a reflective DLL injection into a remote process on a compromised victim system, more specifically into a notepad.exe process with PID 6156
Metasploit's post-exploitation module windows/manage/reflective_dll_inject configured:
Reflective_dll.x64.dll is the DLL compiled from Steven Fewer's reflective dll injection project on github.
After executing the post exploitation module, the below graphic shows how the notepad.exe executes the malicious payload that came from a reflective DLL that was sent over the wire from the attacker's system:
Once the metasploit's post-exploitation module is run, the procmon accurately registers that notepad created a new thread:
Let's see if we can locate where the contents of reflective_dll.x64.dll are injected into the victim process when the metasploit's post-exploitation module executes.
For that, lets debug notepad in WinDBG and set up a breakpoint for MessageBoxA as shown below and run the post-exploitation module again:
The breakpoint is hit:
- return address the code will jump to after the USER32!MessageBoxA finishes is 00000000031e103e
- inspecting assembly instructions around 00000000031e103e , we see a call instruction call qword ptr [00000000031e9208]
- inspecting bytes stored in 00000000031e9208 , ( dd 00000000031e9208 L1 ) we can see they look like a memory address 0000000077331304 (note this address)
- inspecting the EIP pointer ( r eip ) where the code execution is paused at the moment, we see that it is the same 0000000077331304 address, which means that the earlier mentioned instruction call qword ptr [00000000031e9208] is the actual call to USER32!MessageBoxA
- This means that prior to the above mentioned instruction, there must be references to the variables that are passed to the MessageBoxA function:
If we inspect the 00000000031e103e 0x30 bytes earlier, we can see some suspect memory addresses and the call instruction almost immediatley after that:
Upon inspecting those two addresses - they are indeed holding the values the MessageBoxA prints out upon successful DLL injection into the victim process:
Looking at the output of the !address function and correlating it with the addresses the variables are stored at, it can be derived that the memory region allocated for the evil dll is located in the range 031e0000 - 031f7000 :
Indeed, if we look at the 031e0000 , we can see the executable header (MZ) and the strings fed into the MessageBoxA API can be also found further into the binary:
Detecting Reflective DLL Injection with Volatility
Malfind is the Volatility's pluging responsible for finding various types of code injection and reflective DLL injection can usually be detected with the help of this plugin.
The plugin, at a high level will scan through various memory regions described by Virtual Address Descriptors (VADs) and look for any regions with PAGE_EXECUTE_READWRITE memory protection and then check for the magic bytes 4d5a (MZ in ASCII) at the very beginning of those regions as those bytes signify the start of a Windows executable (i.e exe, dll):
Note how in our case, volatility discovered the reflective dll injection we inspected manually above with WindDBG:
Implementing Reflective DLL Injection
I wanted to program a simplified Reflective DLL Injection POC to make sure I understood its internals, so this is my attempt and its high level workflow of how I've implemented it:
- Read raw DLL bytes into a memory buffer
- Parse DLL headers and get the SizeOfImage
- Allocate new memory space for the DLL of size SizeOfImage
- Copy over DLL headers and PE sections to the memory space allocated in step 3
- Perform image base relocations
- Load DLL imported libraries
- Resolve Import Address Table (IAT)
- Invoke the DLL with DLL_PROCESS_ATTACH reason
Steps 1-4 are pretty straight-forward as seen from the code below. For step 5 related to image base relocations, see my notes T1093: Process Hollowing and Portable Executable Relocations
Resolving Import Address Table
Portable Executables (PE) use Import Address Table (IAT) to lookup function names and their memory addresses when they need to be called during runtime.
When dealing with reflective DLLs, we need to load all the dependent libraries of the DLL into the current process and fix up the IAT to make sure that the functions that the DLL imports point to correct function addresses in the current process memory space.
In order to load the depending libraries, we need to parse the DLL headers and:
- Get a pointer to the first Import Descriptor
- From the descriptor, get a pointer to the imported library name
- Load the library into the current process with LoadLibrary
- Repeat process until all Import Descriptos have been walked through and all depending libraries loaded
Before proceeding, note that my test DLL I will be using for this POC is just a simple MessageBox that gets called once the DLL is loaded into the process:
Below shows the first Import Descriptor of my test DLL. The first descriptor suggests that the DLL imports User32.dll and its function MessageBoxA. On the left, we can see a correctly resolved library name that is about to be loaded into the memory process with LoadLibrary :
Below shows that the user32.dll gets loaded successfully:
After the Import Descriptor is read and its corresponding library is loaded, we need to loop through all the thunks (data structures describing functions the library imports), resolve their addresses using GetProcAddress and put them into the IAT so that the DLL can reference them when needed:
Once we have looped through all the Import Decriptors and their thunks, the IAT is considered resolved and we can now execute the DLL. Below shows a successfully loaded and executed DLL that pops a message box:
Вы используете устаревший браузер. Этот и другие сайты могут отображаться в нём некорректно.
Вам необходимо обновить браузер или попробовать использовать другой.
d0ppl4r
Старшина
Разбираем Reflective DLL Injection — технику, которую используют злоумышленники для скрытой загрузки DLL-библиотеки.
Обычно для загрузки DLL-библиотеки в Windows мы вызываем функцию LoadLibrary, которая принимает в качестве аргумента путь к библиотеке. Для этого нужно, чтобы библиотека была на диске, с которого и производится загрузка.
Но злоумышленники загружают код другим, более интересным путем.
Их техника Reflective DLL Injection позволяет внедрить код DLL-библиотеки в процесс из памяти. Основное преимущество такого подхода заключается в том, что библиотека не регистрируется в системе. В результате ее практически невозможно обнаружить ни на уровне системы, ни на уровне процесса.
Reflective DLL Injection по шагам
1. Некоторый исполняемый файл считывает DLL-библиотеку с диска в адресное пространство своего процесса и передает управление на ее экспортируемую функцию ReflectiveLoader.
2. Поскольку теперь библиотека существует в произвольном месте в памяти, ReflectiveLoader вычисляет текущее местоположение самой DLL-библиотеки в памяти. Для этого ReflectiveLoader получает адрес текущей инструкции и, двигаясь в обратном направлении, ищет байты 4D5A, соответствующие MZ-сигнатуре. Это нужно, чтобы дать библиотеке возможность анализировать свои собственные заголовки для дальнейшего запуска.
3. ReflectiveLoader определяет адрес библиотеки kernel32.dll в текущем процессе, после чего анализирует таблицу ее экспорта и находит функции LoadLibrary, GetProcAddress и VirtualAlloc, необходимые для дальнейшей загрузки.
Теперь ReflectiveLoader выделяет непрерывный участок памяти (VirtualAlloc), где и размещает код DLL-библиотеки (заголовки и секции) в соответствии с виртуальными адресами. Затем ReflectiveLoader обрабатывает свою вновь загруженную таблицу импорта: загружает необходимые библиотеки (LoadLibrary) и импортируемые из них функции (GetProcAddress).
Reflective DLL injection is a library injection technique in which the concept of reflective programming is employed to perform the loading of a library from memory into a host process. As such the library is responsible for loading itself by implementing a minimal Portable Executable (PE) file loader. It can then govern, with minimal interaction with the host system and process, how it will load and interact with the host.
Injection works from Windows NT4 up to and including Windows 8, running on x86, x64 and ARM where applicable.
The process of remotely injecting a library into a process is two fold. Firstly, the library you wish to inject must be written into the address space of the target process (Herein referred to as the host process). Secondly the library must be loaded into that host process in such a way that the library's run time expectations are met, such as resolving its imports or relocating it to a suitable location in memory.
Assuming we have code execution in the host process and the library we wish to inject has been written into an arbitrary location of memory in the host process, Reflective DLL Injection works as follows.
- Execution is passed, either via CreateRemoteThread() or a tiny bootstrap shellcode, to the library's ReflectiveLoader function which is an exported function found in the library's export table.
- As the library's image will currently exists in an arbitrary location in memory the ReflectiveLoader will first calculate its own image's current location in memory so as to be able to parse its own headers for use later on.
- The ReflectiveLoader will then parse the host processes kernel32.dll export table in order to calculate the addresses of three functions required by the loader, namely LoadLibraryA, GetProcAddress and VirtualAlloc.
- The ReflectiveLoader will now allocate a continuous region of memory into which it will proceed to load its own image. The location is not important as the loader will correctly relocate the image later on.
- The library's headers and sections are loaded into their new locations in memory.
- The ReflectiveLoader will then process the newly loaded copy of its image's import table, loading any additional library's and resolving their respective imported function addresses.
- The ReflectiveLoader will then process the newly loaded copy of its image's relocation table.
- The ReflectiveLoader will then call its newly loaded image's entry point function, DllMain with DLL_PROCESS_ATTACH. The library has now been successfully loaded into memory.
- Finally the ReflectiveLoader will return execution to the initial bootstrap shellcode which called it, or if it was called via CreateRemoteThread, the thread will terminate.
Open the 'rdi.sln' file in Visual Studio C++ and build the solution in Release mode to make inject.exe and reflective_dll.dll
To test use the inject.exe to inject reflective_dll.dll into a host process via a process id, e.g.:
Licensed under a 3 clause BSD license, please see LICENSE.txt for details.
Читайте также: