Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if running as Administrator with or without elevated privileges?

I have an application that needs to detect whether or not it is running with elevated privileges or not. I currently have code set up like this:

static bool IsAdministrator() {     WindowsIdentity identity = WindowsIdentity.GetCurrent();     WindowsPrincipal principal = new WindowsPrincipal(identity);     return principal.IsInRole (WindowsBuiltInRole.Administrator); } 

This works to detect if a user is an administrator or not, but doesn't work if running as an administrator without elevation. (For example in vshost.exe).

How can I determine whether or not elevation is [already in force or] possible?

like image 644
MiffTheFox Avatar asked Aug 02 '09 23:08

MiffTheFox


People also ask

How do you check if I have elevated access?

1. Check for Administrative Privileges in Settings. To open settings, press the Windows and I keys. Go to account, and below your profile picture, you should see if you have administrative privileges.

How do I know if CMD is run as administrator?

You should use "net session" command and look for an error return code of "0" to verify administrator rights.

When you want to run a program with elevated or administrative privileges?

Right-click or press-and-hold on the shortcut, and then right-click or press-and-hold again on the program's name. Then, from the menu that opens, choose "Run as administrator." You can also use the "Ctrl + Shift + Click/Tap" shortcut on an app's taskbar shortcut to run it with administrator permissions in Windows 10.


2 Answers

Try this out:

using Microsoft.Win32; using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Principal;  public static class UacHelper {     private const string uacRegistryKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System";     private const string uacRegistryValue = "EnableLUA";      private static uint STANDARD_RIGHTS_READ = 0x00020000;     private static uint TOKEN_QUERY = 0x0008;     private static uint TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY);      [DllImport("advapi32.dll", SetLastError = true)]     [return: MarshalAs(UnmanagedType.Bool)]     static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);      [DllImport("advapi32.dll", SetLastError = true)]     public static extern bool GetTokenInformation(IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, IntPtr TokenInformation, uint TokenInformationLength, out uint ReturnLength);      public enum TOKEN_INFORMATION_CLASS     {         TokenUser = 1,         TokenGroups,         TokenPrivileges,         TokenOwner,         TokenPrimaryGroup,         TokenDefaultDacl,         TokenSource,         TokenType,         TokenImpersonationLevel,         TokenStatistics,         TokenRestrictedSids,         TokenSessionId,         TokenGroupsAndPrivileges,         TokenSessionReference,         TokenSandBoxInert,         TokenAuditPolicy,         TokenOrigin,         TokenElevationType,         TokenLinkedToken,         TokenElevation,         TokenHasRestrictions,         TokenAccessInformation,         TokenVirtualizationAllowed,         TokenVirtualizationEnabled,         TokenIntegrityLevel,         TokenUIAccess,         TokenMandatoryPolicy,         TokenLogonSid,         MaxTokenInfoClass     }      public enum TOKEN_ELEVATION_TYPE     {         TokenElevationTypeDefault = 1,         TokenElevationTypeFull,         TokenElevationTypeLimited     }      public static bool IsUacEnabled     {         get         {             RegistryKey uacKey = Registry.LocalMachine.OpenSubKey(uacRegistryKey, false);             bool result = uacKey.GetValue(uacRegistryValue).Equals(1);             return result;         }     }      public static bool IsProcessElevated     {         get         {             if (IsUacEnabled)             {                 IntPtr tokenHandle;                 if (!OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_READ, out tokenHandle))                 {                     throw new ApplicationException("Could not get process token.  Win32 Error Code: " + 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;                 }                 else                 {                     throw new ApplicationException("Unable to determine the current elevation.");                 }             }             else             {                 WindowsIdentity identity = WindowsIdentity.GetCurrent();                 WindowsPrincipal principal = new WindowsPrincipal(identity);                 bool result = principal.IsInRole(WindowsBuiltInRole.Administrator);                 return result;             }         }     } } 
like image 70
Steven Avatar answered Sep 27 '22 20:09

Steven


(new answer six years after the question was asked)

Disclaimer: This is just something that happened to work on my particular OS with my particular settings with my particular user:

using System.Security.Principal;  // ...      static bool IsElevated     {       get       {         return WindowsIdentity.GetCurrent().Owner           .IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid);       }     } 

So when I run this "Run as administrator", the property get accessor returns true. When running normally (even if my user "is" administrator, just not running this particular application "as administrator"), it returns false.

This seems much simpler than many other answers.

I have no idea if there are cases where this fails.

PS! This also seems OK:

    static bool IsElevated     {       get       {         var id = WindowsIdentity.GetCurrent();         return id.Owner != id.User;       }     } 
like image 29
Jeppe Stig Nielsen Avatar answered Sep 27 '22 21:09

Jeppe Stig Nielsen