77 lines
2.6 KiB
Nim
77 lines
2.6 KiB
Nim
# _____ ___ ____ ____ _____ ____ ____ _____ _____
|
||
# |_ _/ _ \| _ \ / ___|| ____/ ___| _ \| ____|_ _|
|
||
# | || | | | |_) | \___ \| _|| | | |_) | _| | |
|
||
# | || |_| | __/ ___) | |__| |___| _ <| |___ | |
|
||
# |_| \___/|_| |____/|_____\____|_| \_\_____| |_|
|
||
|
||
|
||
# see https://github.com/byt3bl33d3r/OffensiveNim/blob/master/src/pop_bin.nim
|
||
# see https://github.com/byt3bl33d3r/OffensiveNim/blob/master/src/shellcode_bin.nim
|
||
import os
|
||
import system
|
||
|
||
const
|
||
MEM_COMMIT = 0x1000
|
||
MEM_RESERVE = 0x2000
|
||
PAGE_EXECUTE_READWRITE = 0x40
|
||
|
||
type
|
||
HANDLE* = int
|
||
HWND* = HANDLE
|
||
UINT* = int32
|
||
LPCSTR* = cstring
|
||
|
||
proc MessageBox*(hWnd: HWND, lpText: LPCSTR, lpCaption: LPCSTR, uType: UINT): int32
|
||
{.discardable, stdcall, dynlib: "user32", importc: "MessageBoxA".}
|
||
|
||
MessageBox(0, "Hello, world !", "Nim is Powerful", 0)
|
||
|
||
|
||
|
||
# LPVOID VirtualAllocEx(
|
||
# [in] HANDLE hProcess,
|
||
# [in, optional] LPVOID lpAddress, BUT IF NULL: automatically calculated
|
||
# [in] SIZE_T dwSize, is an int? size in bytes of memory region. "The size of the region of memory to allocate, in bytes."
|
||
# [in] DWORD flAllocationType, see https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualallocex
|
||
# [in] DWORD flProtect
|
||
# );
|
||
|
||
# proc NimVirtualAllocEx*(hWnd: HWND, lpAddress: pointer, dwSize: LPCSTR, uType: UINT): int32
|
||
# {.discardable, stdcall, dynlib: "user32", importc: "VirtualAllocEx".}
|
||
|
||
|
||
# Declare the VirtualAlloc function from Windows API
|
||
proc VirtualAlloc*(addr: pointer void, size: csize_t, allocType: cuint, protect: cuint): pointer cvoid {.importwinapi: "VirtualAlloc".}
|
||
|
||
# Declare a simple function that will be loaded into the allocated memory
|
||
proc helloWorld() =
|
||
echo "Hello, World from allocated memory!"
|
||
|
||
# Main procedure
|
||
proc main(): int =
|
||
# Calculate the size needed for the function
|
||
let codeSize = procSize(helloWorld)
|
||
|
||
# Allocate memory using VirtualAlloc
|
||
let allocatedMemory = VirtualAlloc(nil, codeSize, MEM_COMMIT or MEM_RESERVE, PAGE_EXECUTE_READWRITE)
|
||
if allocatedMemory == nil:
|
||
echo "Failed to allocate memory."
|
||
return 1 # Return an error code
|
||
|
||
# Copy the function code to the allocated memory
|
||
memcpy(allocatedMemory, addr(helloWorld), codeSize)
|
||
|
||
# Cast the allocated memory to a function pointer
|
||
let funcPointer: proc() {.cdecl.} = cast[proc()](allocatedMemory)
|
||
|
||
# Execute the function in the allocated memory
|
||
funcPointer()
|
||
|
||
# Deallocate the memory (optional)
|
||
os.free(allocatedMemory)
|
||
|
||
return 0 # Return 0 to indicate successful execution
|
||
|
||
when isMainModule:
|
||
main()
|