Home >Backend Development >C++ >How to Reliably Detect Administrator and Elevated Privileges in Windows?
How to detect admin rights with or without elevated privileges
Your current code successfully identifies administrator status, but fails when determining elevated privileges. To comprehensively address this issue, we'll explore another approach.
Check if UAC is enabled
First, let’s make sure User Account Control (UAC) is enabled. UAC is a security feature that limits unauthorized changes to the operating system. If UAC is enabled, we will need a different approach to checking for elevated privileges.
<code>RegistryKey uacKey = Registry.LocalMachine.OpenSubKey(uacRegistryKey, false); bool isUacEnabled = uacKey.GetValue(uacRegistryValue).Equals(1);</code>
Confirm process elevated privileges
Next, let’s check the elevated privilege status of the current process. If UAC is enabled, we will use the GetTokenInformation
function to retrieve the token promotion type.
<code>IntPtr tokenHandle; if (!OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_READ, out tokenHandle)) {throw new ApplicationException("无法获取进程令牌。Win32 错误代码: " + Marshal.GetLastWin32Error());} TOKEN_ELEVATION_TYPE elevationResult = TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault; int elevationResultSize = Marshal.SizeOf((int)elevationResult); uint returnedSize = 0; IntPtr elevationTypePtr = Marshal.AllocHGlobal(elevationResultSize); bool success = GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS.TokenElevationType, elevationTypePtr, (uint)elevationResultSize, out returnedSize); if (success) { elevationResult = (TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(elevationTypePtr); bool isProcessAdmin = elevationResult == TOKEN_ELEVATION_TYPE.TokenElevationTypeFull; return isProcessAdmin; }</code>
If UAC is not enabled, we can rely on WindowsPrincipal.IsInRole
to check the promotion status.
<code>WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); bool result = principal.IsInRole(WindowsBuiltInRole.Administrator); return result;</code>
Complete Solution
By combining these two methods, we can comprehensively detect whether an application is running with elevated privileges, regardless of UAC status.
The above is the detailed content of How to Reliably Detect Administrator and Elevated Privileges in Windows?. For more information, please follow other related articles on the PHP Chinese website!