Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix 'MemoryReadSafe' not restoring original memory protection correctly #16

Merged
merged 1 commit into from
Oct 28, 2023

Conversation

shocoman
Copy link
Contributor

@shocoman shocoman commented Oct 1, 2023

Run this script:

alloc 5000;
addr = $res;

memset addr,90,5000;
setpagerights addr+3000, "GExecuteReadWrite";
cip = addr+2ff0;
getpagerights addr+3000;

sti
sti

getpagerights addr+3000;

The expected output should be something like this (because we didn't touch the page):

Page: 018E3000, Rights: ERW-G  
Page: 018E3000, Rights: ERW-G

But it's actually this:

Page: 018E3000, Rights: ERW-G  
Page: 018E3000, Rights: ERW--

The reason for this behavior is that before single stepping, the debugger reads the next 16 bytes to check if the following instruction is pushfd or push ss. To do this, it calls the MemoryReadSafe function, which initially tries to use ReadProcessMemory and fails because there is a guarded page. Then it sets a more permissible page protection (PAGE_EXECUTE_READ) on the whole range. After the job is done, it will try to restore the original protection from the initial call to VirtualProtectEx. The problem is that if the original page contains several different types of protection (like one page is PAGE_READWRITE and another is PAGE_READWRITE | PAGE_GUARD), it'll simply overwrite the whole page range with the first page protection (e.g. PAGE_READWRITE).
The solution is to save and restore each page individually.

GleeBug doesn't have this problem because it just fails to read memory entirely, without changing memory protection

@shocoman shocoman force-pushed the memory-read-safe-page-bug branch 3 times, most recently from 6bf25be to 631e3ad Compare October 13, 2023 03:53
@shocoman shocoman force-pushed the memory-read-safe-page-bug branch from 631e3ad to 4bac132 Compare October 20, 2023 13:58
@mrexodia mrexodia merged commit 49f5978 into x64dbg:x64dbg Oct 28, 2023
1 check passed
@mrexodia
Copy link
Member

🤝

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants