// ConsoleApplication4.cpp : Defines the entry point for the console application.
//
http://www.2cto.com/kf/201206/137531.html
#include "stdafx.h"
#include <windows.h>
#include <atlstr.h>
#include <iostream>
#define AllocMem(x) (HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,x))
#define FreeMem(x) (HeapFree(GetProcessHeap(),HEAP_ZERO_MEMORY,x))
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
BOOL bRs = FALSE;
DWORD dwSizeNeeded = 0;
PSECURITY_DESCRIPTOR psd = NULL;
SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION;
bRs = GetFileSecurity(L"D:\\ww",si,psd,0,&dwSizeNeeded);
//第一次调用获得SD实际大小
if(!bRs){
if(GetLastError() == ERROR_INSUFFICIENT_BUFFER){
psd = (PSECURITY_DESCRIPTOR)AllocMem(dwSizeNeeded);
//根据获取到的大小对psd分配内存
}
else{
printf("\n[-]Get SD failed:%d",GetLastError());
return bRs;
}
}
if(!GetFileSecurity(L"D:\\ww",si,psd,dwSizeNeeded,&dwSizeNeeded)){
printf("\n[-]Get SD failed:%d",GetLastError());
return bRs;
}
HANDLE hToken;
if(!OpenProcessToken(GetCurrentProcess(),TOKEN_ALL_ACCESS,&hToken)){
return bRs;
}
HANDLE hImpersonatedToken = NULL;
if(DuplicateToken(hToken, SecurityImpersonation, &hImpersonatedToken)){
DWORD dwGenericAccessMask = GENERIC_READ|GENERIC_WRITE;
GENERIC_MAPPING genMap ;
PRIVILEGE_SET privileges = {0};
DWORD grantAccess = 0;
DWORD privLength = sizeof(privileges);
BOOL bGrantAccess = FALSE;
//将通用权限控制标志和特定类型对象权限控制标志挂钩
genMap.GenericRead = FILE_GENERIC_READ;
genMap.GenericWrite = FILE_GENERIC_WRITE;
genMap.GenericExecute = FILE_GENERIC_EXECUTE;
genMap.GenericAll = FILE_ALL_ACCESS;
MapGenericMask(&dwGenericAccessMask,&genMap);
//映射通用权限控制标志
if(AccessCheck(psd,hImpersonatedToken, dwGenericAccessMask, &genMap,&privileges,&privLength,&grantAccess,&bGrantAccess)){
bRs = bGrantAccess;
return bRs;
}
else{
printf("\n[-]Access check failed:%d",GetLastError());
return bRs;
}
}
return 0;
}