> For the complete documentation index, see [llms.txt](https://www.pentestwiki.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.pentestwiki.com/defense-evasion/windows-api/virtualallocex.md).

# VirtualAllocEx

VirtualAllocEx는 다른 프로세스 내에서 메모리를 할당하는 함수이며, 이 함수에 의해 할당된 메모리는 자동으로 0으로 초기화됩니다.

이 함수는 주로 인젝션 시 페이로드를 저장할 공간 확보에 사용됩니다.

```cpp
LPVOID VirtualAllocEx(
  [in]           HANDLE hProcess,
  [in, optional] LPVOID lpAddress,
  [in]           SIZE_T dwSize,
  [in]           DWORD  flAllocationType,
  [in]           DWORD  flProtect
);
```

| 인자               | 설명         | 보편적인 값                      |
| ---------------- | ---------- | --------------------------- |
| hProcess         | 대상 프로세스 핸들 |                             |
| lpAddress        | 할당할 주소     | NULL(OS가 자동 선택)             |
| dwSize           | 할당 크기      |                             |
| flAllocationType | 할당 타입      | `MEM_COMMIT \| MEM_RESERVE` |
| flProtect        | 메모리 보호 속성  | `PAGE_EXECUTE_READWRITE`    |

## Example

```cpp
#include <windows.h>
#include <tlhelp32.h>
#include <iostream>
using namespace std;

LPVOID allocRemoteMemory(HANDLE hProc, SIZE_T dataSize) {
    LPVOID exec = VirtualAllocEx(
        hProc, NULL, dataSize,
        MEM_COMMIT | MEM_RESERVE,
        PAGE_EXECUTE_READWRITE
    );
    if (!exec) {
        wcout << L"Failed to get Memory buffer" << endl;
    }
    return exec;
}

HANDLE openProcessByPid(DWORD processId) {
    HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId);
    if (!hProc) {
        wcout << L"Failed to get Process handle" << endl;
    }
    return hProc;
}

int main() {
    int pid = 1234;
    SIZE_T 
    HANDLE hProc = openProcessByPid(pid);
    LPVOID exec = allocRemoteMemory(hProc, dataSize);
    CloseHandle(hProc);
    return 0;
}
```

## References

{% embed url="<https://learn.microsoft.com/ko-kr/windows/win32/api/memoryapi/nf-memoryapi-virtualallocex>" %}
