For windows programs
If an application in Windows needs to perform system management or process management, it is often necessary to escalate the process (obtain the permission token );
Generally, there are two methods for elevation of permission in windows:
1) win32API -- AdjustTokenPrivileges;
2) ntdll. dll -- RtlAdjustPrivilege;
The former is a public win32 system API, and the latter is a non-public export function (hidden in ntdll. dll );
There are also some differences between the two;
First look at the first method:
1) win32API -- AdjustTokenPrivileges
//Win32Api: void AdjustPrivilege() { HANDLE hToken; if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken)) { TOKEN_PRIVILEGES tp; tp.PrivilegeCount = 1; tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; if (LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &tp.Privileges[0].Luid)) { AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(tp), NULL, NULL); } CloseHandle(hToken); } }
We can see that the AdjustTokenPrivileges Elevation of Privilege is the structure LUID (LARGE_INTEGER) for the handle of the current process and the privileged value of the corresponding system permission token;
That is to say, you must first use the LookupPrivilegeValue method to query the privileged value of the token (such as SE_DEBUG_NAME;
2) ntdll. dll -- RtlAdjustPrivilege
//ntdll.dllconst unsigned long SE_DEBUG_PRIVILEGE = 0x14;typedef int (__stdcall *fRtlAdjustPrivilege)(ULONG, BOOLEAN, BOOLEAN, PBOOLEAN);void NtAdjustPrivilege(){HMODULE hNtDll = LoadLibrary(_T("ntdll.dll"));if (!hNtDll)return;fRtlAdjustPrivilege funcAdjustPrivilege =(fRtlAdjustPrivilege)GetProcAddress(hNtDll, "RtlAdjustPrivilege");if (funcAdjustPrivilege){BOOLEAN oldStatus;funcAdjustPrivilege(SE_DEBUG_PRIVILEGE, true, false, &oldStatus);}FreeLibrary(hNtDll);}
This method of exporting RtlAdjustPrivilege does not depend on other methods, but you need to define the permission value SE_DEBUG_PRIVILEGE to 0x14. Obviously, this method of writing is always a bad way;
We should let windows define these values by themselves, and we should use these values through the variable name, this design is better;
Of course, in a specific windows platform, as long as the function export by ntdll. dll in windows does not change much, this can also be used.
To sum up, the first method is to use public APIs. There are official documents, which are well-known and do not have to worry about API changes. However, you need to use more than one method (LookupPrivilegeValue and AdjustTokenPrivileges) in combination, the second method can achieve the effect without relying on other methods. It is concise and powerful, but the non-public export method RtlAdjustPrivilege is used, maybe ntdll will be used in later windows versions. dll modification may cause API incompatibility issues. Therefore, if the first method can meet the requirements, try to avoid using the second method. After all, there will be no more lines of code;