Example: Initializing Security Attributes
Program 15-1.
Program 15-3. InitUnFp: Initializing Security Attributes
/* Set UNIX-style permissions as ACEs in a
SECURITY_ATTRIBUTES structure. */
#include "EvryThng.h"
#define ACL_SIZE 1024
#define INIT_EXCEPTION 0x3
#define CHANGE_EXCEPTION 0x4
#define SID_SIZE LUSIZE
#define DOM_SIZE LUSIZE
LPSECURITY_ATTRIBUTES InitializeUnixSA (DWORD UnixPerms,
LPCTSTR UsrNam, LPCTSTR GrpNam, LPDWORD AceMasks,
LPHANDLE pHeap)
{
HANDLE SAHeap = HeapCreate (HEAP_GENERATE_EXCEPTIONS, 0, 0);
LPSECURITY_ATTRIBUTES pSA = NULL;
PSECURITY_DESCRIPTOR pSD = NULL;
PACL pAcl = NULL;
BOOL Success;
DWORD iBit, iSid, UsrCnt = ACCT_NAME_SIZE;
/* Tables of User, Group, and Everyone Names, SIDs,
etc. for LookupAccountName and SID creation. */
LPCTSTR pGrpNms [3] = {EMPTY, EMPTY, _T ("Everyone")};
PSID pSidTable [3] = {NULL, NULL, NULL};
SID_NAME_USE sNamUse [3] =
{SidTypeUser, SidTypeGroup, SidTypeWellKnownGroup};
TCHAR RefDomain [3] [DOM_SIZE];
DWORD RefDomCnt [3] = {DOM_SIZE, DOM_SIZE, DOM_SIZE};
DWORD SidCnt [3] = {SID_SIZE, SID_SIZE, SID_SIZE};
__try { /* Try-except block for memory allocation failures. */
*pHeap = SAHeap;
pSA = HeapAlloc (SAHeap, 0, sizeof (SECURITY_ATTRIBUTES));
pSA->nLength = sizeof (SECURITY_ATTRIBUTES);
pSA->bInheritHandle = FALSE;
/* Programmer can set this later. */
pSD = HeapAlloc (SAHeap, 0, sizeof (SECURITY_DESCRIPTOR));
pSA->lpSecurityDescriptor = pSD;
InitializeSecurityDescriptor (pSD,
SECURITY_DESCRIPTOR_REVISION);
/* Get a SID for User, Group, and Everyone.
* See the Web site for additional important details. */
pGrpNms [0] = UsrNam; pGrpNms [1] = GrpNam;
for (iSid = 0; iSid < 3; iSid++) {
pSidTable [iSid] = HeapAlloc (SAHeap, 0, SID_SIZE);
LookupAccountName (NULL, pGrpNms [iSid],
pSidTable [iSid], &SidCnt [iSid],
RefDomain [iSid], &RefDomCnt [iSid],
&sNamUse [iSid]);
}
SetSecurityDescriptorOwner (pSD, pSidTable [0], FALSE);
SetSecurityDescriptorGroup (pSD, pSidTable [1], FALSE);
pAcl = HeapAlloc (ProcHeap, HEAP_GENERATE_EXCEPTIONS, ACL_SIZE);
InitializeAcl (pAcl, ACL_SIZE, ACL_REVISION);
/* Add all the access allowed/denied ACEs. */
for (iBit = 0; iBit < 9; iBit++) {
if ((UnixPerms >> (8 - iBit) & 0x1) != 0 &&
AceMasks[iBit%3] != 0)
AddAccessAllowedAce (pAcl, ACL_REVISION,
AceMasks [iBit%3], pSidTable [iBit/3]);
else if (AceMasks[iBit%3] != 0)
AddAccessDeniedAce (pAcl, ACL_REVISION,
AceMasks [iBit%3], pSidTable [iBit/3]);
}
/* Add a final deny all to Everyone ACE. */
Success = Success && AddAccessDeniedAce (pAcl, ACL_REVISION,
STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL, pSidTable [2]);
/* Associate ACL with the security descriptor. */
SetSecurityDescriptorDacl (pSD, TRUE, pAcl, FALSE);
return pSA;
} /* End of try-except block. */
__except (EXCEPTION_EXECUTE_HANDLER) { /* Free all resources. */
if (SAHeap != NULL)
HeapDestroy (SAHeap);
pSA = NULL;
}
return pSA;
}
Comments on
(Program 15-3Chapter 11). Program 15-4 shows how to integrate the security attributes with a file.