June 4th, 2004

An easy way to determine whether you have a particular file permission

Sometimes you might want to determine whether you can do something without actually doing it. For example, you might want to know whether you have a particular permission in a directory, say permission to delete files from it.

One way is to retrieve the ACL and then check whether the current user has the desired permission. The AccessCheck function does most of the heavy lifting there.

Or you can realize, “Hey, wait a second, there is an entire security infrastructure whose job it is to decide who can access which files. Why not use it?”

For example, here’s how you can check whether the user has permission to delete files from a directory:

BOOL CanDeleteFilesFromDirectory(LPCTSTR pszPath)
{
  HANDLE h = CreateFile(pszPath, FILE_DELETE_CHILD, FILE_SHARE_READ |
                        FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
                        OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
  if (h != INVALID_HANDLE_VALUE) {
    CloseHandle(h);
  }
  return h != INVALID_HANDLE_VALUE;
}

What we did was open the directory (which requires backup semantics) and ask for FILE_DELETE_CHILD access. If it succeeded, then we have permission to delete files from it. [Corrected 7:52am]

Note, of course, that this information is purely advisory. You shouldn’t be making security decisions based on this, because the permissions might change between the time you check and the time you try.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.

Feedback