gpt4 book ai didi

windows - 在Windows的内存区域上设置PAGE_NOACCESS和VirtualLock

转载 作者:行者123 更新时间:2023-12-03 11:10:47 28 4
gpt4 key购买 nike

关于virtualLock的documentation page上的以下说明:

Memory protected with PAGE_NOACCESS cannot be locked.

有什么办法解决吗?在UNIX系统上可以实现这一壮举,但Windows上存在此限制。目的是防止将内存分页到磁盘,同时阻止对磁盘的任何访问。

最佳答案

当我们使用ZwProtectVirtualMemoryPAGE_NOACCESS在锁定的内存区域上调用 PAGE_GUARD|* 时,返回的状态为STATUS_WAS_UNLOCKED:

{Page Unlocked}

The page protection of a locked page was changed to 'No Access' and the page was unlocked from memory and from the process.



这里重要的是准确调用 ZwProtectVirtualMemory而不是 VirtualProtect[Ex],因为此win32 api不能区分不同的 NT_SUCCESS 值,只需对其中的任何值返回true并放弃原始状态即可。但是 STATUS_WAS_UNLOCKED被定义为 0x40000017L也是 NT_SUCCESS值-因此 VirtualProtect[Ex] 在这种情况下会丢失重要信息。

因此将 PAGE_NOACCESSPAGE_GUARD|*设置为副作用,从内存中解锁页面

但是在页面上设置 PAGE_NOACCESS有什么意义?为防止有人从页面读取数据?但是如果该代理有权访问您的进程-他也可以并删除此 PAGE_NOACCESS,如果没有访问权-则不需要执行保护。在这两种情况下-毫无意义地设置 PAGE_NOACCESS-是否需要或可以将其删除。

防止页面交换到页面文件存在意义,因为理论上可以在系统关闭后从中读取页面文件(如果此时此刻),但是将其设置为“无访问权限”(此操作将从该页面的PTE条目中删除有效位)感觉

只需编写测试代码
void PrintNtStatus(PCSTR prefix, NTSTATUS status)
{
static HMODULE hmod = 0;

if (!hmod)
{
hmod = GetModuleHandle(L"ntdll");
}

PWSTR msg;
if (FormatMessageW(FORMAT_MESSAGE_FROM_HMODULE|FORMAT_MESSAGE_ALLOCATE_BUFFER, hmod, status, 0, (PWSTR)&msg, 0, 0))
{
DbgPrint("%s = %x(%S)\n", prefix, status, msg);
LocalFree(msg);
}
}

void LockTest()
{
if (PVOID pv = VirtualAlloc(0, 1, MEM_COMMIT, PAGE_READWRITE))
{
if (VirtualLock(pv, 1))
{
ULONG op;
SIZE_T size = 1;
PVOID BaseAddress = pv;
//STATUS_WAS_UNLOCKED
PrintNtStatus("ProtectVirtualMemory",
ZwProtectVirtualMemory(NtCurrentProcess(), &BaseAddress, &size, PAGE_NOACCESS, &op));
PrintNtStatus("ProtectVirtualMemory",
ZwProtectVirtualMemory(NtCurrentProcess(), &BaseAddress, &size, op, &op));
PrintNtStatus("VirtualUnlock", VirtualUnlock(pv, 1) ? STATUS_SUCCESS : RtlGetLastNtStatus());
}
VirtualFree(pv, 0, MEM_RELEASE);
}
}

关于windows - 在Windows的内存区域上设置PAGE_NOACCESS和VirtualLock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48797932/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com