Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In .NET/C# test if process has administrative privileges

Is there a canonical way to test to see if the process has administrative privileges on a machine?

I'm going to be starting a long running process, and much later in the process' lifetime it's going to attempt some things that require admin privileges.

I'd like to be able to test up front if the process has those rights rather than later on.

like image 984
Clinton Pierce Avatar asked Jul 06 '09 20:07

Clinton Pierce


People also ask

What is NET in C#?

NET Framework applications are written in C#, F#, or Visual Basic and compiled to Common Intermediate Language (CIL). The Common Language Runtime (CLR) runs . NET applications on a given machine, converting the CIL to machine code.

Is .NET and C# the same?

In summary, C# is a programming language, while . NET is a developer platform. After comparing C# vs . NET, it is clear that both are essential for application development.

Is .NET written in C?

NET Framework is written in C++ and C#.

Is .NET still used?

The use of . Net has been growing steadily over the years, becoming a prevalent programming language among programmers and software developers. It is also being used by many different companies as well as several governments across the world.


2 Answers

This will check if user is in the local Administrators group (assuming you're not checking for domain admin permissions)

using System.Security.Principal;  public bool IsUserAdministrator() {     //bool value to hold our return value     bool isAdmin;     WindowsIdentity user = null;     try     {         //get the currently logged in user         user = WindowsIdentity.GetCurrent();         WindowsPrincipal principal = new WindowsPrincipal(user);         isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);     }     catch (UnauthorizedAccessException ex)     {         isAdmin = false;     }     catch (Exception ex)     {         isAdmin = false;     }     finally     {         if (user != null)             user.Dispose();     }     return isAdmin; } 
like image 54
Wadih M. Avatar answered Sep 16 '22 16:09

Wadih M.


Starting with Wadih M's code, I've got some additional P/Invoke code to try and handle the case of when UAC is on.

http://www.davidmoore.info/blog/2011/06/20/how-to-check-if-the-current-user-is-an-administrator-even-if-uac-is-on/

First, we’ll need some code to support the GetTokenInformation API call:

[DllImport("advapi32.dll", SetLastError = true)] static extern bool GetTokenInformation(IntPtr tokenHandle, TokenInformationClass tokenInformationClass, IntPtr tokenInformation, int tokenInformationLength, out int returnLength);  /// <summary> /// Passed to <see cref="GetTokenInformation"/> to specify what /// information about the token to return. /// </summary> enum TokenInformationClass {      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 }  /// <summary> /// The elevation type for a user token. /// </summary> enum TokenElevationType {     TokenElevationTypeDefault = 1,     TokenElevationTypeFull,     TokenElevationTypeLimited } 

Then, the actual code to detect if the user is an Administrator (returning true if they are, otherwise false).

var identity = WindowsIdentity.GetCurrent(); if (identity == null) throw new InvalidOperationException("Couldn't get the current user identity"); var principal = new WindowsPrincipal(identity);  // Check if this user has the Administrator role. If they do, return immediately. // If UAC is on, and the process is not elevated, then this will actually return false. if (principal.IsInRole(WindowsBuiltInRole.Administrator)) return true;  // If we're not running in Vista onwards, we don't have to worry about checking for UAC. if (Environment.OSVersion.Platform != PlatformID.Win32NT || Environment.OSVersion.Version.Major < 6) {      // Operating system does not support UAC; skipping elevation check.      return false; }  int tokenInfLength = Marshal.SizeOf(typeof(int)); IntPtr tokenInformation = Marshal.AllocHGlobal(tokenInfLength);  try {     var token = identity.Token;     var result = GetTokenInformation(token, TokenInformationClass.TokenElevationType, tokenInformation, tokenInfLength, out tokenInfLength);      if (!result)     {         var exception = Marshal.GetExceptionForHR( Marshal.GetHRForLastWin32Error() );         throw new InvalidOperationException("Couldn't get token information", exception);     }      var elevationType = (TokenElevationType)Marshal.ReadInt32(tokenInformation);      switch (elevationType)     {         case TokenElevationType.TokenElevationTypeDefault:             // TokenElevationTypeDefault - User is not using a split token, so they cannot elevate.             return false;         case TokenElevationType.TokenElevationTypeFull:             // TokenElevationTypeFull - User has a split token, and the process is running elevated. Assuming they're an administrator.             return true;         case TokenElevationType.TokenElevationTypeLimited:             // TokenElevationTypeLimited - User has a split token, but the process is not running elevated. Assuming they're an administrator.             return true;         default:             // Unknown token elevation type.             return false;      } } finally {         if (tokenInformation != IntPtr.Zero) Marshal.FreeHGlobal(tokenInformation); } 
like image 36
David Moore Avatar answered Sep 16 '22 16:09

David Moore