Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Windows's CreateFile(<no share access>) lying to me?

I'm trying to prevent a third-party DLL in my process from reading a file I've opened, and I've found it to be... well, impossible.

No matter what I do, no matter what share flags I specify, their call always seems to succeed!

Here is the screenshot from Process Monitor -- the first CreateFile call is mine, and the rest are theirs:

Screenshot

How is this even possible? Why is the "Share Mode: None" lying to me, and how can I prevent this?


This code below is an example that reproduces the problem:

#include <stdio.h>
#include <Windows.h>

int main()
{
    LPCTSTR file = TEXT("C:\\Test1234.xml");
    HANDLE hFile1 =
        CreateFile(file, FILE_READ_ATTRIBUTES, 0, NULL, OPEN_ALWAYS, 0, NULL);
    HANDLE hFile2 =
        CreateFile(file, FILE_READ_DATA, 0, NULL, OPEN_ALWAYS, 0, NULL);
    DWORD n;
    BYTE buf[1];
    printf("%d\n", ReadFile(hFile2, buf, sizeof(buf), &n, NULL));
    CloseHandle(hFile1);
    CloseHandle(hFile2);
    DeleteFile(file);
}
like image 400
user541686 Avatar asked Dec 21 '12 03:12

user541686


People also ask

What is CreateFile?

The CreateFile function can create a new file or open an existing file. You must specify the file name, creation instructions, and other attributes.

Can CreateFile return null?

Since there is a single function to dispose of handles, CloseHandle , it follows that NULL is not a valid HANDLE value. Hence CreateFile cannot ever return NULL .


1 Answers

Share modes are enforced for actually reading and writing the DATA of the file. Attributes (like file size, timestamps, etc) are not covered by the sharing rules and there is no way to prevent their access short of ACLs.

The best you can to is open the file for R/W/D access and not specify SHARE_READ|WRITE|DELETE.

Weird, but true.

like image 61
MJZ Avatar answered Oct 09 '22 02:10

MJZ