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
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • You are not doing any error handling on GetMappedFileNameA, and what makes you think a memory mapping is using a file path as its name to begin with? What are you ultimately trying to accomplish? – Remy Lebeau Aug 10 '19 at 03:29
  • I want edit memory at this region,but it's MEM_MAPPED region and I want to open mapped file at this location for changing page protection – SomeNickName Aug 10 '19 at 08:03
  • I think you have a fundamental misunderstanding of what MEM_MAPPED refers to. The memory being queried has already been mapped into memory, so just access the mapped data directly as needed, no need to open a new handle to the mapping object. Besides, you can't change the protection on the existing mapping anyway. The protection is set when the mapping object is first created and mapped into memory. Opening a new handle to the mapping object won't let you change its protection. So again, what are you REALLY trying to accomplish? This sounds like a possible XY problem. – Remy Lebeau Aug 10 '19 at 08:27
  • I want to edit memory at this location,but it's have PAGE_READONLY protection – SomeNickName Aug 10 '19 at 08:34
  • you can't use OpenFileMapping() to change the protection of an existing mapping object. Did you try VirtualProtect/Ex() instead? If that doesn't work, you are SOL – Remy Lebeau Aug 10 '19 at 16:27
  • VirtualProtect I tried it's doesn't work.VirtualProtect call VirtualProtectEx so try VirtualProtectEx have no sence – SomeNickName Aug 11 '19 at 11:49
  • I can use MapViewOfFile but i need HANDLE of file which i can't get – SomeNickName Aug 17 '19 at 06:27

1 Answers1

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);
GuidedHacking
  • 3,628
  • 1
  • 9
  • 59