Skip to content

Instantly share code, notes, and snippets.

@SavSanta
Forked from khchen/NtAllocateVirtualMemory.nim
Created December 8, 2023 20:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SavSanta/308acda1d7bdd45e5a4f83fd1207c45e to your computer and use it in GitHub Desktop.
Save SavSanta/308acda1d7bdd45e5a4f83fd1207c45e 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