Skip to content

Instantly share code, notes, and snippets.

@khchen
Last active December 8, 2023 20:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save khchen/0aa8b758753e7bbde65505ec86b26103 to your computer and use it in GitHub Desktop.
Save khchen/0aa8b758753e7bbde65505ec86b26103 to your computer and use it in GitHub Desktop.
#[
Author: Ward
Example of NtAllocateVirtualMemory, NtReadVirtualMemory, NtFreeVirtualMemory
References:
https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntallocatevirtualmemory
]#
import winim/lean
# There are no definitions for these APIs in winim yet, define them at first.
proc NtAllocateVirtualMemory(processHandle: HANDLE, baseAddress: PVOID,
zeroBits: ULONG_PTR, regionSize: PSIZE_T, allocationType: ULONG,
Protect: ULONG): NTSTATUS {.stdcall, dynlib: "ntdll", importc, discardable.}
proc NtReadVirtualMemory(processHandle: HANDLE, baseAddress: PVOID,
buffer: PVOID, bufferSize: ULONG, numberOfBytesRead: PULONG): NTSTATUS
{.stdcall, dynlib: "ntdll", importc, discardable.}
proc NtFreeVirtualMemory(processHandle: HANDLE, baseAddress: PVOID,
regionSize: PSIZE_T, freeType: ULONG): NTSTATUS
{.stdcall, dynlib: "ntdll", importc, discardable.}
var
address: PVOID
size: SIZE_T = 1024
if NtAllocateVirtualMemory(-1, &address, 0, &size, MEM_COMMIT, PAGE_READWRITE).NT_SUCCESS:
# Write something at the address
cast[LPSTR](address) << "This is a message."
var
buffer = newString(1024)
bytesRead: ULONG
# Read the message via API
if NtReadVirtualMemory(-1, address, &buffer, cint buffer.len, &bytesRead).NT_SUCCESS:
buffer.nullTerminate()
echo buffer
NtFreeVirtualMemory(-1, &address, &size, MEM_RELEASE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment