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:
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);
}
The CreateFile function can create a new file or open an existing file. You must specify the file name, creation instructions, and other attributes.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With