| 1 | #include <stdio.h> |
|---|
| 2 | #include <windows.h> |
|---|
| 3 | |
|---|
| 4 | int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { |
|---|
| 5 | char * ptr; |
|---|
| 6 | void (*x_ptr)(); |
|---|
| 7 | |
|---|
| 8 | BOOL protected; |
|---|
| 9 | DWORD last_error; |
|---|
| 10 | char last_error_msg[4096]; |
|---|
| 11 | DWORD old_protect; |
|---|
| 12 | int i; |
|---|
| 13 | |
|---|
| 14 | // allocate non-executable memory |
|---|
| 15 | ptr = VirtualAlloc(NULL, 1, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); |
|---|
| 16 | *ptr = 0xc3; /* RET */ |
|---|
| 17 | |
|---|
| 18 | x_ptr = ptr; |
|---|
| 19 | /* x_ptr(); */ /* generate DEP exception */ |
|---|
| 20 | |
|---|
| 21 | // convert it to executable read-write memory |
|---|
| 22 | protected = VirtualProtect(ptr, 1, PAGE_EXECUTE_READWRITE, &old_protect); |
|---|
| 23 | last_error = GetLastError(); |
|---|
| 24 | FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, last_error, 0, &last_error_msg, 4096, NULL); |
|---|
| 25 | printf("%d %d %s\n", protected, last_error, last_error_msg); |
|---|
| 26 | |
|---|
| 27 | x_ptr(); /* works fine */ |
|---|
| 28 | |
|---|
| 29 | // allocate non-executable memory |
|---|
| 30 | ptr = VirtualAlloc(NULL, 1, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); |
|---|
| 31 | *ptr = 0xc3; /* RET */ |
|---|
| 32 | |
|---|
| 33 | x_ptr = ptr; |
|---|
| 34 | /* x_ptr(); */ /* generate DEP exception */ |
|---|
| 35 | |
|---|
| 36 | // convert it to execute-only memory */ |
|---|
| 37 | protected = VirtualProtect(ptr, 1, PAGE_EXECUTE, &old_protect); |
|---|
| 38 | FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, last_error, 0, &last_error_msg, 4096, NULL); |
|---|
| 39 | printf("%d %d %s\n", protected, last_error, last_error_msg); |
|---|
| 40 | |
|---|
| 41 | x_ptr(); /* works fine */ |
|---|
| 42 | |
|---|
| 43 | return 0; |
|---|
| 44 | } |
|---|