# WriteProcessMemory

WriteProcessMemory는 지정된 프로세스의 메모리 영역에 데이터를 씁니다. 데이터를 작성할 영역 전체에 엑세스 할 수 있어야 하며, 그렇지 않을 경우 작업이 실패합니다.

이 함수는 주로 페이로드 주입에 사용됩니다.

```cpp
BOOL WriteProcessMemory(
  [in]  HANDLE  hProcess,
  [in]  LPVOID  lpBaseAddress,
  [in]  LPCVOID lpBuffer,
  [in]  SIZE_T  nSize,
  [out] SIZE_T  *lpNumberOfBytesWritten
);
```

| 인자                       | 설명          |
| ------------------------ | ----------- |
| hProcess                 | 대상 프로세스 핸들  |
| lpBaseAddress            | 쓸 메모리 주소    |
| lpBuffer                 | 소스 버퍼       |
| nSize                    | 쓸 바이트 크기    |
| \*lpNumberOfBytesWritten | 실제 쓴 바이트 크기 |

## Example

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

BOOL writeRemoteMemory(HANDLE hProc, LPVOID dest, void* data, SIZE_T size) {
    // 쓴 데이터 크기 초기화
    SIZE_T written = 0;
    if (!WriteProcessMemory(hProc, dest, data, size, &written)) {
        wcout << L"Failed to write memory" << endl;
        return FALSE;
    }
    wcout << L"Written " << written << L" bytes" << endl;
    return TRUE;
}

int main() {
    DWORD pid = 1234;
    unsigned char shellcode[] = { 0x90, 0x90, 0x90, 0xCC };

    // OpenProcess를 통해 프로세스 핸들 획득
    HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
    if (hProc) {
        LPVOID mem = VirtualAllocEx(hProc, NULL, sizeof(shellcode),
            MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
        if (mem) {
            // VirtualAllocEx로 획득한 메모리에 쉘코드 삽입
            writeRemoteMemory(hProc, mem, shellcode, sizeof(shellcode));
            VirtualFreeEx(hProc, mem, 0, MEM_RELEASE);
        }
        CloseHandle(hProc);
    }
    return 0;
}
```

## References

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.pentestwiki.com/defense-evasion/windows-api/writeprocessmemory.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
