While creating a malware, in-order to run they payload in the memory of the process, we need to create a memory buffer for the payload. For this purpose, we need to make use of the VirtualAlloc function.
As per the windows documentation, a VirtualAlloc function reserves, commits or changes the state of a region of pages in the virtual address space of the calling process.
Lets dig deep on this function and its parameters,
The syntax for the function usage is,
LPVOID VirtualAlloc(
[in, optional] LPVOID lpAddress,
[in] SIZE_T dwSize,
[in] DWORD flAllocationType,
[in] DWORD flProtect
);
lpAddress : This field is optional. It is the starting address of the region to allocate.
dwSize : The size of the region in bytes. This si usually the size of the payload we have, not less than that.
flAllocationType : Type of memory allocation. The commonly used parameters are MEM_COMMIT and MEM_RESERVE,
MEM_COMMIT : Allocates memory charges (from the overall size of memory and the paging files on disk) for the specified reserved memory pages. The function also guarantees that when the caller later initially accesses the memory, the contents will be zero. Actual physical pages are not allocated unless/until the virtual addresses are actually accessed.
MEM_RESERVE: Reserves a range of the process's virtual address space without allocating any actual physical storage in memory or in the paging file on disk.
Couple of other parameters used are MEM_RESET,MEM_RESET_UNDO.
flProtect : The memory protection for the region of pages to be allocated.The options are PAGE_EXECUTE,PAGE_EXECUTE_READ,PAGE_EXECUTE_READWRITE,PAGE_READONLY,PAGE_READWRITE. This means what type of access allowed within that memory space. You can execute the payload, or read or just write or combination of all.
Example :
lets assume we have a payload
char payload[] ={0x90,0x90};
int payload_size=2;
Now use the VirtualAlloc function to allocate a memory buffer.
VirtualAlloc(0,payload_size,MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
In the above function, we mentioned that the starting address is zero/null. dwSize, the size of the payload. flAllocationType as MEM_COMMIT and MEM_RESERVE and finally the flProtect, memory region as readable and writable (PAGE_READWRITE).
Next : Malware Analysis : RtlMoveMemory function and its usage.
References :
https://docs.microsoft.com/en-us/windows/win32/memory/memory-protection-constants
https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc