Can't open mapped file from address

0

I can't open mapped memory. When I use OpenFileMappingA() it returns NULL and GetLastError() returns 161 (ERROR_BAD_PATHNAME). I use the following code:

MEMORY_BASIC_INFORMATION mbi = { 0 };
VirtualQuery(image->raw_data, &mbi, sizeof(mbi));

if (mbi.Protect & PAGE_EXECUTE_READWRITE)
    ZeroMemory(image->raw_data, sizeof(IMAGE_DOS_HEADER) +  sizeof(IMAGE_NT_HEADERS)  + sizeof(IMAGE_SECTION_HEADER)* nt_header->FileHeader.NumberOfSections);
else if (mbi.Type & MEM_MAPPED)
{
    char buffer[500];
    size_t count = GetMappedFileNameA(GetCurrentProcess(), image->raw_data, buffer, sizeof(buffer));    
    HANDLE hMap = OpenFileMappingA(FILE_MAP_ALL_ACCESS, false, buffer);
    std::cout << hMap << std::endl; //0x00000000 
    std::cout << GetLastError() << std::endl; //161
}
c++
mapped-memory
asked on Stack Overflow Aug 9, 2019 by Adolf • edited Aug 10, 2019 by Remy Lebeau

1 Answer

0

"I want to edit memory at this location, but it's have PAGE_READONLY protection"

OpenFileMappingA doesn't have anything to do with protection.

You need to use VirtualProtect() to change the protection of that memory region to PAGE_READWRITE (0x04)

DWORD  curProtection = 0;
VirtualProtect(addr, len, PAGE_READWRITE, &curProtection);

//change the memory

//then restore old protection
VirtualProtect(toHook, len, curProtection, &curProtection);
answered on Stack Overflow Apr 21, 2020 by GuidedHacking

User contributions licensed under CC BY-SA 3.0