1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| BOOL SetPrivilege(
HANDLE hToken, // access token handle
LPCTSTR lpszPrivilege, // name of privilege to enable/disable
BOOL bEnablePrivilege // to enable or disable privilege
)
{
char tmp[100];
TOKEN_PRIVILEGES tp;
LUID luid;
if ( !LookupPrivilegeValue(
NULL, // lookup privilege on local system
lpszPrivilege, // privilege to lookup
&luid ) ) // receives LUID of privilege
{
sprintf(tmp, "LookupPrivilegeValue error: %u\n", GetLastError() );
Form1->Edit1->Text = tmp;
return FALSE;
}
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
if (bEnablePrivilege)
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
else
tp.Privileges[0].Attributes = 0;
// Enable the privilege or disable all privileges.
AdjustTokenPrivileges(
hToken,
FALSE,
&tp,
sizeof(TOKEN_PRIVILEGES),
(PTOKEN_PRIVILEGES) NULL,
(PDWORD) NULL);
// Call GetLastError to determine whether the function succeeded.
if (GetLastError() != ERROR_SUCCESS)
{
sprintf(tmp, "AdjustTokenPrivileges failed: %u\n", GetLastError() );
Form1->Edit1->Text = tmp;
return FALSE;
}
return TRUE;
}
void __fastcall TForm1::Button1Click(TObject *Sender)
{
DeleteFile("test");
HANDLE TokenHandle;
if (OpenProcessToken( GetCurrentProcess() , TOKEN_ADJUST_PRIVILEGES, &TokenHandle) != ERROR_SUCCESS)
{
LPVOID lpMsgBuf;
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf, 0, NULL);
Edit1->Text = (LPCTSTR)lpMsgBuf;
LocalFree( lpMsgBuf );
}
SetPrivilege(TokenHandle, SE_BACKUP_NAME, true);
TRegistry * Reg = new TRegistry();
Reg->RootKey = HKEY_CURRENT_USER;
if(Reg->SaveKey("Software\\MyCle\\","test"))
Edit1->Text = "OK";
else
Edit1->Text = "KO";
delete Reg;
} |
Partager