VirtualProtect

VirtualProtect는 호출 프로세스의 가상 주소 공간에 커밋된 페이지의 영역에 대한 보호를 변경합니다.

이 함수는 주로 코드 후킹이나 메모리 패치에 사용됩니다.

BOOL VirtualProtect(
  [in]  LPVOID lpAddress,
  [in]  SIZE_T dwSize,
  [in]  DWORD  flNewProtect,
  [out] PDWORD lpflOldProtect
);
인자
설명
보편적인 값

lpAddress

메모리 주소

dwSize

크기

flNewProtect

새 보호 속성

PAGE_EXECUTE_READWRITE

lpflOldProtect

이전 보호 속성을 받을 포인터

Example

#include <windows.h>
#include <iostream>

int main() {
    DWORD oldProtect = 0;
    unsigned char* buffer = (unsigned char*)VirtualAlloc(NULL, 0x1000, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);

    buffer[0] = 0x41;

    std::wcout << "----- Before memory protection -----" << std::endl;
    std::cout << "buffer[0] : " << buffer[0] << std::endl;
    __try {
        unsigned char v1 = 0x42;
        RtlMoveMemory(buffer, &v1, sizeof(v1));
        std::cout << "[+] memory change success" << std::endl;
    }
    __except (EXCEPTION_EXECUTE_HANDLER){
        std::cout << "[-] memory change failed\n";
    }

    std::cout << "buffer[0] : " << buffer[0] << std::endl;
    std::wcout << "\n\n----- After memory protection -----" << std::endl;
    VirtualProtect(buffer, 0x1000, PAGE_READONLY, &oldProtect);
    std::cout << "[*] Writing after protect change...\n";

    __try {
        unsigned char v2 = 0x43;
        RtlMoveMemory(buffer, &v2, sizeof(v2));
        std::cout << "[-] Unexpected: write succeeded\n";
    }
    __except (EXCEPTION_EXECUTE_HANDLER) {
        std::cout << "[+] Access violation caught -> VirtualProtect works\n";
    }

    return 0;
}

References

Last updated