Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for iselevated.cs

(view source code of iselevated.cs as plain text)

  1. using Microsoft.Win32;
  2. using System;
  3. using System.Diagnostics;
  4. using System.Runtime.InteropServices;
  5. using System.Security.Principal;
  6.  
  7. namespace RobVanderWoude
  8. {
  9. 	class IsElevated
  10. 	{
  11. 		static int Main(string[] args)
  12. 		{
  13. 			if (args.Length == 0)
  14. 			{
  15. 				if (RobVanderWoude.UacHelper.IsProcessElevated)
  16. 				{
  17. 					return 0;
  18. 				}
  19. 				else
  20. 				{
  21. 					return 1;
  22. 				}
  23. 			}
  24. 			else
  25. 			{
  26. 				Console.WriteLine();
  27. 				Console.WriteLine("IsElevated.exe, Version 1.00");
  28. 				Console.WriteLine("Return true (0) if running in a process with elevated privileges");
  29. 				Console.WriteLine();
  30. 				Console.WriteLine("Usage:  ISELEVATED.EXE");
  31. 				Console.WriteLine();
  32. 				Console.WriteLine("Based on a thread on stackoverflow.com:");
  33. 				Console.WriteLine("/questions/1220213/c-detect-if-running-with-elevated-privileges");
  34. 				Console.WriteLine();
  35. 				Console.WriteLine("Written by Rob van der Woude");
  36. 				Console.WriteLine("http://www.robvanderwoude.com");
  37. 				return 2;
  38. 			}
  39. 		}
  40. 	}
  41.  
  42.  
  43. 	// Source of the following code:
  44. 	// http://stackoverflow.com/questions/1220213/c-detect-if-running-with-elevated-privileges
  45.  
  46. 	public static class UacHelper
  47. 	{
  48. 		private const string uacRegistryKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System";
  49. 		private const string uacRegistryValue = "EnableLUA";
  50.  
  51. 		private static uint STANDARD_RIGHTS_READ = 0x00020000;
  52. 		private static uint TOKEN_QUERY = 0x0008;
  53. 		private static uint TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY);
  54.  
  55. 		[DllImport("advapi32.dll", SetLastError = true)]
  56. 		[return: MarshalAs(UnmanagedType.Bool)]
  57. 		static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);
  58.  
  59. 		[DllImport("advapi32.dll", SetLastError = true)]
  60. 		public static extern bool GetTokenInformation(IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, IntPtr TokenInformation, uint TokenInformationLength, out uint ReturnLength);
  61.  
  62. 		public enum TOKEN_INFORMATION_CLASS
  63. 		{
  64. 			TokenUser = 1,
  65. 			TokenGroups,
  66. 			TokenPrivileges,
  67. 			TokenOwner,
  68. 			TokenPrimaryGroup,
  69. 			TokenDefaultDacl,
  70. 			TokenSource,
  71. 			TokenType,
  72. 			TokenImpersonationLevel,
  73. 			TokenStatistics,
  74. 			TokenRestrictedSids,
  75. 			TokenSessionId,
  76. 			TokenGroupsAndPrivileges,
  77. 			TokenSessionReference,
  78. 			TokenSandBoxInert,
  79. 			TokenAuditPolicy,
  80. 			TokenOrigin,
  81. 			TokenElevationType,
  82. 			TokenLinkedToken,
  83. 			TokenElevation,
  84. 			TokenHasRestrictions,
  85. 			TokenAccessInformation,
  86. 			TokenVirtualizationAllowed,
  87. 			TokenVirtualizationEnabled,
  88. 			TokenIntegrityLevel,
  89. 			TokenUIAccess,
  90. 			TokenMandatoryPolicy,
  91. 			TokenLogonSid,
  92. 			MaxTokenInfoClass
  93. 		}
  94.  
  95. 		public enum TOKEN_ELEVATION_TYPE
  96. 		{
  97. 			TokenElevationTypeDefault = 1,
  98. 			TokenElevationTypeFull,
  99. 			TokenElevationTypeLimited
  100. 		}
  101.  
  102. 		public static bool IsUacEnabled
  103. 		{
  104. 			get
  105. 			{
  106. 				RegistryKey uacKey = Registry.LocalMachine.OpenSubKey(uacRegistryKey, false);
  107. 				bool result = uacKey.GetValue(uacRegistryValue).Equals(1);
  108. 				return result;
  109. 			}
  110. 		}
  111.  
  112. 		public static bool IsProcessElevated
  113. 		{
  114. 			get
  115. 			{
  116. 				if (IsUacEnabled)
  117. 				{
  118. 					IntPtr tokenHandle;
  119. 					//if (!OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_READ, out tokenHandle))
  120. 					if (!OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_READ, out tokenHandle))
  121. 					{
  122. 						throw new ApplicationException("Could not get process token.  Win32 Error Code: " + Marshal.GetLastWin32Error());
  123. 					}
  124.  
  125. 					TOKEN_ELEVATION_TYPE elevationResult = TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault;
  126.  
  127. 					int elevationResultSize = Marshal.SizeOf((int)elevationResult);
  128. 					uint returnedSize = 0;
  129. 					IntPtr elevationTypePtr = Marshal.AllocHGlobal(elevationResultSize);
  130.  
  131. 					bool success = GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS.TokenElevationType, elevationTypePtr, (uint)elevationResultSize, out returnedSize);
  132. 					if (success)
  133. 					{
  134. 						elevationResult = (TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(elevationTypePtr);
  135. 						bool isProcessAdmin = elevationResult == TOKEN_ELEVATION_TYPE.TokenElevationTypeFull;
  136. 						return isProcessAdmin;
  137. 					}
  138. 					else
  139. 					{
  140. 						throw new ApplicationException("Unable to determine the current elevation.");
  141. 					}
  142. 				}
  143. 				else
  144. 				{
  145. 					WindowsIdentity identity = WindowsIdentity.GetCurrent();
  146. 					WindowsPrincipal principal = new WindowsPrincipal(identity);
  147. 					bool result = principal.IsInRole(WindowsBuiltInRole.Administrator);
  148. 					return result;
  149. 				}
  150. 			}
  151. 		}
  152. 	}
  153. }

page last modified: 2024-04-16; loaded in 0.0230 seconds