Wednesday, November 11, 2009

Example: Reading File Permissions









Example: Reading File Permissions


Program 15-4 is the function ReadFilePermissions, which is used by Programs 15-1 and 15-2. This program methodically uses the preceding functions to extract the information. Its correct operation depends on the fact that the ACL was created by Program 15-3. The function is in the same source module as Program 15-3, so the definitions are not repeated.


Program 15-4. ReadFilePermissions: Reading Security Attributes



DWORD ReadFilePermissions (LPCTSTR lpFileName,
LPTSTR UsrNm, LPTSTR GrpNm)
/* Return the UNIX-style permissions for a file. */
{
PSECURITY_DESCRIPTOR pSD = NULL;
DWORD LenNeeded, PBits, iAce;
BOOL DaclF, AclDefF, OwnerDefF, GroupDefF;
BYTE DAcl [ACL_SIZE];
PACL pAcl = (PACL) &DAcl;
ACL_SIZE_INFORMATION ASizeInfo;
PACCESS_ALLOWED_ACE pAce;
BYTE AType;
HANDLE ProcHeap = GetProcessHeap ();
PSID pOwnerSid, pGroupSid;
TCHAR RefDomain [2] [DOM_SIZE];
DWORD RefDomCnt [] = {DOM_SIZE, DOM_SIZE};
DWORD AcctSize [] = {ACCT_NAME_SIZE, ACCT_NAME_SIZE};
SID_NAME_USE sNamUse [] = {SidTypeUser, SidTypeGroup};

/* Get the required size for the security descriptor. */
GetFileSecurity (lpFileName,
OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
DACL_SECURITY_INFORMATION, pSD, 0, &LenNeeded);
pSD = HeapAlloc (ProcHeap, HEAP_GENERATE_EXCEPTIONS, LenNeeded);
GetFileSecurity (lpFileName, OWNER_SECURITY_INFORMATION |
GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
pSD, LenNeeded, &LenNeeded);
GetSecurityDescriptorDacl (pSD, &DaclF, &pAcl, &AclDefF);
GetAclInformation (pAcl, &ASizeInfo,
sizeof (ACL_SIZE_INFORMATION), AclSizeInformation);
PBits = 0; /* Compute the permissions from the ACL. */
for (iAce = 0; iAce < ASizeInfo.AceCount; iAce++) {
GetAce (pAcl, iAce, &pAce);
AType = pAce->Header.AceType;
if (AType == ACCESS_ALLOWED_ACE_TYPE)
PBits |= (0x1 << (8-iAce));
}
/* Find the name of the owner and owning group. */
GetSecurityDescriptorOwner (pSD, &pOwnerSid, &OwnerDefF);
GetSecurityDescriptorGroup (pSD, &pGroupSid, &GroupDefF);
LookupAccountSid (NULL, pOwnerSid, UsrNm, &AcctSize [0],
RefDomain [0], &RefDomCnt [0], &sNamUse [0]);
LookupAccountSid (NULL, pGroupSid, GrpNm, &AcctSize [1],
RefDomain [1], &RefDomCnt [1], &sNamUse [1]);
return PBits;
}










    No comments: