int CheckAccess(DWORD DesiredAccess,AnsiString FileName)
{
// Var Decl.
DWORD dwSizeNeeded=0;
PSECURITY_DESCRIPTOR pSecDescriptorBuf;
HANDLE ClientToken=NULL;
DWORD AccessMask;
GENERIC_MAPPING GenericFileMapping= { FILE_GENERIC_READ,FILE_GENERIC_WRITE,FILE_GENERIC_EXECUTE,FILE_ALL_ACCESS};
PRIVILEGE_SET PrivilegeSet;
DWORD PrivilegeSetLength;
DWORD GrantedAccess;
BOOL AccessStatus;
bool result;
// Get needed size
pSecDescriptorBuf = new BYTE[1];
DWORD LastError=GetLastError();
GetFileSecurity(FileName.c_str(),
DACL_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
pSecDescriptorBuf,
1,
&dwSizeNeeded);
SetLastError(LastError);
delete[] pSecDescriptorBuf;
// Get Security_Descriptor
pSecDescriptorBuf = new BYTE[dwSizeNeeded];
if(!GetFileSecurity(FileName.c_str(),
DACL_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
pSecDescriptorBuf,
dwSizeNeeded,
&dwSizeNeeded))
{
delete[] pSecDescriptorBuf;
return -1;
}
if (!ImpersonateSelf(SecurityImpersonation))
{
delete[] pSecDescriptorBuf;
return -2;
}
if (!OpenThreadToken(GetCurrentThread(),
TOKEN_QUERY | TOKEN_IMPERSONATE | TOKEN_DUPLICATE |TOKEN_ADJUST_PRIVILEGES,
False,
&ClientToken))
{
RevertToSelf();
delete[] pSecDescriptorBuf;
return -3;
}
// Get debug priv.
// SE_DEBUG_NAME / SeDebugPrivilege
TOKEN_PRIVILEGES
tp;
LUID luid;
if (!LookupPrivilegeValue(NULL,"SeDebugPrivilege",&luid))
{
RevertToSelf();
delete[] pSecDescriptorBuf;
return -4;
}
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if ( !AdjustTokenPrivileges(
ClientToken,
FALSE,
&
tp,
sizeof(TOKEN_PRIVILEGES),
(PTOKEN_PRIVILEGES) NULL,
(PDWORD) NULL) )
{
RevertToSelf();
delete[] pSecDescriptorBuf;
return -5;
}
AccessMask=DesiredAccess;
MapGenericMask(&AccessMask,&GenericFileMapping);
PrivilegeSetLength = sizeof(PRIVILEGE_SET);
if (!AccessCheck(pSecDescriptorBuf,
ClientToken,
AccessMask,
&GenericFileMapping,
&PrivilegeSet,
&PrivilegeSetLength,
&GrantedAccess,
&AccessStatus))
{
CloseHandle(ClientToken);
RevertToSelf();
delete[] pSecDescriptorBuf;
return -6;
}
// Clean up
result=AccessStatus;
CloseHandle(ClientToken);
RevertToSelf();
delete[] pSecDescriptorBuf;
if (result)
return 1;
else
return 0;
}