CreateDirectory and SECURITY_ATTRIBUTES


Problem:
In my application,  I created a directory with CreateDirectory( m_strDestinationDir, NULL )

the directory is created well. the problem is, when i want to Copy files to it (via CopyFile) GetLastError says 5 (access denied).

Solution 1:
If lpSecurityAttributes is NULL, the directory gets a default security descriptor. The ACLs in the default security descriptor for a directory are inherited from its parent directory.

try do the following:

SECURITY_ATTRIBUTES sa;
SECURITY_DESCRIPTOR sd;

InitializeSecurityDescriptor(&sd,SECURITY_DESCRIPTOR_REVISION);
SetSecurityDescriptorDacl(&sd,TRUE,NULL,FALSE);
SetSecurityDescriptorGroup(&sd,NULL, FALSE );
SetSecurityDescriptorSacl(&sd, FALSE, NULL, FALSE );

sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = &sd;
sa.bInheritHandle = TRUE;

CreateDirectory( m_strDestinationDir, &sa );

issues with solution 1:
code sets the security to allow full access to everyone.

Solution 2:

get the current owner of the process.
DWORD CreateDirWithSecurity(LPCTSTR lpPath)
{
SECURITY_ATTRIBUTES sa;
SECURITY_DESCRIPTOR sd;
PACL pAcl = NULL;
DWORD cbAcl = 0,dwNeeded = 0,dwError = 0;
HANDLE hToken;
PTOKEN_USER ptu = NULL;

if(!OpenProcessToken( GetCurrentProcess(), TOKEN_QUERY, &hToken))
return GetLastError();

GetTokenInformation( hToken, TokenUser, NULL, 0, &dwNeeded);
if(GetLastError() != ERROR_INSUFFICIENT_BUFFER)
{
dwError = GetLastError();
goto cleanup;
}

ptu = (TOKEN_USER*)malloc(dwNeeded);
if (!GetTokenInformation(hToken, TokenUser, ptu, dwNeeded, &dwNeeded))
{
dwError = GetLastError();
goto cleanup;
}

cbAcl = sizeof(ACL) + ((sizeof(ACCESS_ALLOWED_ACE) – sizeof(DWORD)) + GetLengthSid(ptu->User.Sid));
pAcl = (ACL*) malloc (cbAcl);

if(!InitializeAcl(pAcl, cbAcl, ACL_REVISION))
{
dwError = GetLastError();
goto cleanup;
}

if(!AddAccessAllowedAce(pAcl,ACL_REVISION,GENERIC_ALL|STANDARD_RIGHTS_ALL|SPECIFIC_RIGHTS_ALL,ptu->User.Sid))
{
dwError = GetLastError();
goto cleanup;
}

InitializeSecurityDescriptor(&sd,SECURITY_DESCRIPTOR_REVISION);

SetSecurityDescriptorDacl(&sd,TRUE,pAcl,FALSE);
SetSecurityDescriptorOwner(&sd,ptu->User.Sid,FALSE);
SetSecurityDescriptorGroup(&sd,NULL,FALSE);
SetSecurityDescriptorSacl(&sd, FALSE,NULL,FALSE);

sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = &sd;
sa.bInheritHandle = TRUE;

CreateDirectory(lpPath, &sa);

dwError = GetLastError();

cleanup:
if(ptu) free(ptu);
if(pAcl) free(pAcl);

CloseHandle(hToken);
return dwError;
}