修改文件的所有者和访问权限

时间:2021-11-20 10:01:33

 

原文链接: http://www.pfmboy.com/post/100.html

下面代码修改文件的所有者为当前用户并添加everyone完全控制权限。注意一定要先设置一下所有者(owner),然后再进行权限设置,二者一起执行是不会成功的。

 

BOOL AdjustPrivileges(LPWSTR lpName)
{
HANDLE hToken = NULL;
TOKEN_PRIVILEGES tp = {0};
TOKEN_PRIVILEGES oldtp = {0};
DWORD dwSize = sizeof(TOKEN_PRIVILEGES);
LUID luid = {0};

if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) {
if (GetLastError()==ERROR_CALL_NOT_IMPLEMENTED)
return TRUE;
else
return FALSE;
}
if (!LookupPrivilegeValueW(NULL, lpName, &luid)) {
CloseHandle(hToken);
return FALSE;
}

tp.PrivilegeCount=1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

/* Adjust Token Privileges */
if (!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), &oldtp, &dwSize)) {
CloseHandle(hToken);
return FALSE;
}

// close handles
CloseHandle(hToken);
return TRUE;
}

 

BOOL TakeOwner(char *FilePath)
{
CHAR UserName[36];
DWORD cbUserName = sizeof(UserName);
CHAR Sid[1024] = {0};
DWORD cbSid = sizeof(Sid);
CHAR DomainBuffer[128] = {0};
DWORD cbDomainBuffer = sizeof(DomainBuffer);
SID_NAME_USE eUse;
PACL Dacl = NULL,OldDacl = NULL;
EXPLICIT_ACCESS Ea;
PSECURITY_DESCRIPTOR Sd = NULL;
BOOL Ret = FALSE;

if (AdjustPrivileges(SE_TAKE_OWNERSHIP_NAME) && AdjustPrivileges(SE_RESTORE_NAME))
{
GetUserNameA(UserName,&cbUserName);
if (LookupAccountNameA(NULL,UserName,&Sid,&cbSid,DomainBuffer,&cbDomainBuffer,&eUse))
{

ZeroMemory(&Ea,sizeof(EXPLICIT_ACCESS));
GetNamedSecurityInfoA(FilePath,SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,NULL, NULL, &OldDacl, NULL, &Sd);
BuildExplicitAccessWithNameW(&Ea,L"everyone",GENERIC_ALL,GRANT_ACCESS,SUB_CONTAINERS_AND_OBJECTS_INHERIT);
if (SetEntriesInAclW(1,&Ea,OldDacl,&Dacl) == ERROR_SUCCESS)
{
SetNamedSecurityInfoA(FilePath,SE_FILE_OBJECT,OWNER_SECURITY_INFORMATION ,&Sid,NULL,NULL,NULL);
if (SetNamedSecurityInfoA(FilePath,SE_FILE_OBJECT,OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,&Sid,NULL,Dacl,NULL) == ERROR_SUCCESS)
{
Ret = TRUE;
}
}

}
}
return Ret;
}