I want to take file ownership using win32 api, and I want my code to work on both xp and win7
anyway, here is what i came up with
Function that changes the ownership of the file
int ChangeFileOwner()
{
HANDLE token;
char *filename = "c:\\file1.txt"; //(not owned by the current user)
DWORD len;
PSECURITY_DESCRIPTOR security = NULL;
int retValue = 1;
PSID sid;
// Get the privileges you need
if (OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &token)) {
if(!SetPrivilege("SeTakeOwnershipPrivilege", 1))retValue=0;
if(!SetPrivilege("SeSecurityPrivilege", 1))retValue=0;
if(!SetPrivilege("SeBackupPrivilege", 1))retValue=0;
if(!SetPrivilege("SeRestorePrivilege", 1))retValue=0;
} else retValue = 0;
// Create the security descriptor
if (retValue) {
GetFileSecurity(filename, OWNER_SECURITY_INFORMATION, security, 0, &len);
security = (PSECURITY_DESCRIPTOR)malloc(len);
if (!InitializeSecurityDescriptor(security,SECURITY_DESCRIPTOR_REVISION))
retValue = 0;
}
// Get the sid for the username
if (retValue) {
GetLogonSID(token, &sid) ;
}
// Set the sid to be the new owner
if (retValue && !SetSecurityDescriptorOwner(security, sid, 0))
retValue = 0;
// Save the security descriptor
if (retValue)
retValue = SetFileSecurity(filename, OWNER_SECURITY_INFORMATION, security);
if (security) free(security);
return retValue;
}
Function to get the current user SID
BOOL GetLogonSID (HANDLE hToken, PSID *ppsid)
{
BOOL bSuccess = FALSE;
DWORD dwIndex;
DWORD dwLength = 0;
PTOKEN_GROUPS ptg = NULL;
// Get required buffer size and allocate the TOKEN_GROUPS buffer.
GetTokenInformation(hToken,TokenGroups,(LPVOID) ptg,0,&dwLength) ;
ptg = (PTOKEN_GROUPS)HeapAlloc(GetProcessHeap(),
HEAP_ZERO_MEMORY, dwLength);
// Get the token group information from the access token.
GetTokenInformation(hToken,TokenGroups,(LPVOID) ptg,dwLength,&dwLength) ;
// Loop through the groups to find the logon SID.
for (dwIndex = 0; dwIndex < ptg->GroupCount; dwIndex++)
if ((ptg->Groups[dwIndex].Attributes & SE_GROUP_LOGON_ID)
== SE_GROUP_LOGON_ID)
{
// Found the logon SID; make a copy of it.
dwLength = GetLengthSid(ptg->Groups[dwIndex].Sid);
*ppsid = (PSID) HeapAlloc(GetProcessHeap(),
HEAP_ZERO_MEMORY, dwLength);
CopySid(dwLength, *ppsid, ptg->Groups[dwIndex].Sid);
break;
}
return TRUE;
}
Code To Set Privilege
int SetPrivilege(char *privilege, int enable)
{
TOKEN_PRIVILEGES tp;
LUID luid;
HANDLE token;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token)) return 0;
if (!LookupPrivilegeValue(NULL, privilege, &luid)) return 0;
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
if (enable) tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
else tp.Privileges[0].Attributes = 0;
// Enable the privilege or disable all privileges.
return AdjustTokenPrivileges(token, 0, &tp, NULL, NULL, NULL);
}