Search code examples
c++cfiledirectorydirectory-structure

How do we use SECURITY_ATTRIBUTES with SHCreateDirectoryEx()?


My requirements are as follows:

  1. Creation of a directory at a specified location.
  2. Setting its attributes such that the folder is "READ ONLY". In other words, user accounts should not be able to create a folder/file inside this folder.

Now, I am able to create directory as follows:

SHCreateDirectoryEx( NULL, <path>.c_str(), NULL );

I would now like to set appropriate security attributes. Any help/code example would be appreciated.

Platform: Win7 (Lang: C++/C)


Solution

  • The first thing you'd do is create a SECURITY_ATTRIBUTES struct, and set it's members.

    SECURITY_ATTRIBUTES SecAttr;
    
    SecAttr.size = sizeof(SECURITY_ATTRIBUTES); //Set size of structure
    

    The next member is a type of SECURITY_DESCRIPTOR which actually contains all the data needed to manage security access to this object.

    You cannot directly create this structure, as per MSDN documentation, but you would use the functions provided in the documentation to create such a struct, set all it's necessary flags as required and then get a pointer to it to pass to SecAttr.

    An example on how to create such a SECURITY_DESCRIPTOR struct can be found here. In this example it's done for a registry key, but the principle is the same.

    Essentially you're filling in an DACL (Discretionary Security Access Control List) or SACL (System Access Control List with the right properties of what access (read/write/read-only) etc, you want the object to have.

    Having filled out the entire SECURITY_ATTRIBUTES struct you can pass it to your SHCreateDirectoryEx function.