c++winapiwindows-xpfile-mapping

Access denied on CreateFileMapping when run under different user accounts with runas


This code gives me access denied errors when trying to open previously created file mapping. Help, help, help.

test code:

SECURITY_DESCRIPTOR sd;

if(!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION))
    printf("InitializeSecurityDescriptor failed %d\n", GetLastError());

if(!SetSecurityDescriptorDacl(&sd, true, 0, false))
    printf("SetSecurityDescriptorDacl failed %d\n", GetLastError());

SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = &sd;
sa.bInheritHandle = false;

HANDLE hMap = CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, 0x1000, "Global\\MyMap");
void* pMap = 0;
if(hMap) {
    pMap = MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0x1000);
} else {
    printf("CreateFileMapping failed: %d\n", GetLastError());
    hMap = OpenFileMapping(FILE_MAP_ALL_ACCESS, false, "Global\\MyMap");
    if(hMap) {
        printf("OpenFileMapping sucess!\n");
    } else {
        printf("OpenFileMapping failed: %d\n", GetLastError());
    }
}
if(pMap) {
    printf("Sucess!\n");
    printf("DW: %X", *(DWORD*)pMap);
    *(DWORD*)pMap = 0xDEADBEEF;
} else {
    printf("MapViewOfFile failed: %d\n", GetLastError());
}

cin.ignore();

if(pMap)
    UnmapViewOfFile(pMap);

if(hMap)
    CloseHandle(hMap);

Solution

  • You forgot to pass the SECURITY_ATTRIBUTES struct to CreateFileMapping...