Monday, January 21, 2008

How to set folder permissions in C++ for Vista

Burhan, one of our customers requested this and here it is:

const char* g_
strFSXPath = "g:\fsx";

void SetPathPermissions(const char* path)
{
// Set permissions for the folder
PACL pDacl,pNewDACL;
EXPLICIT_ACCESS ExplicitAccess;
PSECURITY_DESCRIPTOR ppSecurityDescriptor;
PSID psid;

// Get the current Security Info for the path
char szFileName[MAX_PATH];
sprintf(szFileName, "%s%s", g_strFSXPath, path);
GetNamedSecurityInfo(szFileName, SE_FILE_OBJECT,DACL_SECURITY_INFORMATION, NULL, NULL, &pDacl, NULL, &ppSecurityDescriptor);

//BuildExplicitAccessWithName(&ExplicitAccess, "Users", GENERIC_WRITE, SET_ACCESS, CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE);

ConvertStringSidToSid("S-1-5-32-545", &psid);

ExplicitAccess.grfAccessMode = SET_ACCESS;
ExplicitAccess.grfAccessPermissions = GENERIC_WRITE;
ExplicitAccess.grfInheritance = CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE;
ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
ExplicitAccess.Trustee.pMultipleTrustee = NULL;
ExplicitAccess.Trustee.ptstrName = (LPTSTR) psid;
ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;

SetEntriesInAcl(1, &ExplicitAccess, pDacl, &pNewDACL);
SetNamedSecurityInfo(szFileName,SE_FILE_OBJECT,DACL_SECURITY_INFORMATION,NULL,NULL,pNewDACL,NULL);

LocalFree(pNewDACL);
LocalFree(psid);

fileOut << endl;
fileOut << "User reset folder and Subfolders permissions." << endl;
fileOut.flush();

}

5 comments:

Mats J said...

Now I remember why I never bothered to learn C and company...

Cheers,
Mats J

Lefteris said...

Heheh. That's the easy part ;-).

Unknown said...

Cheers :) Thanks for the snippet.

Anonymous said...

This didn't work for me (running Win7). GetLastError() on the funtions say that the commands worked ok. But the permissions don't change on the folder.

I am intending on trying this for Server 2008.

Any ideas would be awesome.

Lefteris said...

The account you're running this under should have the appropriate rights to be allowed to make the changes, otherwise it goes without saying that the code will fail...

Are you running this under administrator rights?