root/trunk/Utilities/Miscellaneous/SetFileOwner/SetFileOwner.cpp

Revision 121, 2.3 KB (checked in by roman, 2 years ago)
  • Property svn:keywords set to Id
Line 
1////////////////////////////////////////////////////////////
2// Copyright (C) Roman Ryltsov, 2012
3// Created by Roman Ryltsov roman@alax.info
4//
5// $Id$
6
7#include "stdafx.h"
8#include <atlpath.h>
9#include <atlsecurity.h>
10#include <atlfile.h>
11
12VOID EnablePrivilege(LPCTSTR pszPrivilege)
13{
14        CAccessToken Token;
15        if(!Token.GetThreadToken(TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES))
16        {
17                const HRESULT nResult = AtlHresultFromLastError();
18                ATLENSURE_THROW(nResult == HRESULT_FROM_WIN32(ERROR_NO_TOKEN), nResult);
19                ATLENSURE_THROW(Token.GetProcessToken(TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES), AtlHresultFromLastError());
20        }
21        ATLENSURE_THROW(Token.EnablePrivilege(pszPrivilege), AtlHresultFromLastError());
22}
23VOID PrintOwner(LPCTSTR pszPath)
24{
25        PSID pSecurityIdentifer = NULL;
26        CSecurityDesc SecurityDescriptor;
27        ATLENSURE_SUCCEEDED(HRESULT_FROM_WIN32(GetNamedSecurityInfo(const_cast<LPTSTR>(pszPath), SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, &pSecurityIdentifer, NULL, NULL, NULL, reinterpret_cast<PSECURITY_DESCRIPTOR*>(&SecurityDescriptor))));
28        CSid SecurityIdentifer((const SID*) pSecurityIdentifer);
29        _tprintf(_T("Owner: %s\\%s\n"), SecurityIdentifer.Domain(), SecurityIdentifer.AccountName());
30}
31VOID SetOwner(LPCTSTR pszPath, const CSid& SecurityIdentifer)
32{
33        ATLENSURE_SUCCEEDED(HRESULT_FROM_WIN32(SetNamedSecurityInfo(const_cast<LPTSTR>(pszPath), SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, const_cast<SID*>((const SID*) SecurityIdentifer), NULL, NULL, NULL)));
34}
35
36int _tmain(int argc, _TCHAR* argv[])
37{
38        static LPCTSTR g_pszPath = _T("D:\\Projects\\Alax.Info\\Repository-Public\\Utilities\\Miscellaneous\\SetFileOwner\\ReadMe.txt");
39        EnablePrivilege(SE_RESTORE_NAME);
40        PrintOwner(g_pszPath);
41        CSid SecurityIdentifer;
42        ATLENSURE_THROW(SecurityIdentifer.LoadAccount(_T("Guest")), AtlHresultFromLastError());
43        _tprintf(_T("New Owner: %s\\%s\n"), SecurityIdentifer.Domain(), SecurityIdentifer.AccountName());
44        _ATLTRY
45        {
46                SetOwner(g_pszPath, SecurityIdentifer);
47        }
48        _ATLCATCH(Exception)
49        {
50                _tprintf(_T("Exception 0x%08x\n"), (HRESULT) Exception);
51                // NOTE: This might be the worst case scenario: changing ownership is perhaps protected by DACL
52                EnablePrivilege(SE_TAKE_OWNERSHIP_NAME);
53                SetOwner(g_pszPath, SecurityIdentifer);
54        }
55        PrintOwner(g_pszPath);
56        return 0;
57}
58
Note: See TracBrowser for help on using the browser.