private static string GetDisplayFriendlyName(NativeMethods.LUID adapterId, uint targetId) { var targetDeviceName = new NativeMethods.DISPLAYCONFIG_TARGET_DEVICE_NAME() { header = new NativeMethods.DISPLAYCONFIG_DEVICE_INFO_HEADER() { type = NativeMethods.DISPLAYCONFIG_DEVICE_INFO_TYPE.GetTargetName, size = (uint)Marshal.SizeOf <NativeMethods.DISPLAYCONFIG_TARGET_DEVICE_NAME>(), adapterId = adapterId, id = targetId, } }; var result = NativeMethods.DisplayConfigGetDeviceInfo(ref targetDeviceName); if (result != NativeMethods.ERROR_SUCCESS) { throw new Win32Exception(result, "Failed DisplayConfigGetDeviceInfo()"); } if (targetDeviceName.outputTechnology == NativeMethods.DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.Internal) { // The internal display has no friendly name. (It has the empty string as a friendly name) return(@"(Internal)"); } else { return(targetDeviceName.monitorFriendlyDeviceName); } }
/// <summary> /// Adjusts the current process's token privileges to allow it to shut down or reboot the machine. /// Throws an ApplicationException if an error is encountered. /// </summary> private static void AdjustTokenPrivilegesForShutdown() { IntPtr procHandle = System.Diagnostics.Process.GetCurrentProcess().Handle; IntPtr tokenHandle = IntPtr.Zero; bool tokenOpenResult = NativeMethods.OpenProcessToken(procHandle, NativeMethods.TOKENADJUSTPRIVILEGES | NativeMethods.TOKENQUERY, out tokenHandle); if (!tokenOpenResult) { throw new ApplicationException("Error attempting to open process token to raise level for shutdown.\nWin32 Error Code: " + Marshal.GetLastWin32Error()); } NativeMethods.LUID luid = new NativeMethods.LUID(); bool privLookupResult = NativeMethods.LookupPrivilegeValue(null, "SeShutdownPrivilege", ref luid); if (!privLookupResult) { throw new ApplicationException("Error attempting to lookup value for shutdown privilege.\n Win32 Error Code: " + Marshal.GetLastWin32Error()); } NativeMethods.TOKEN_PRIVILEGES newPriv = new NativeMethods.TOKEN_PRIVILEGES { PrivilegeCount = 1, Privileges = new NativeMethods.LUID_AND_ATTRIBUTES[1] }; newPriv.Privileges[0].Luid = luid; newPriv.Privileges[0].Attributes = 0x00000002; bool tokenPrivResult = NativeMethods.AdjustTokenPrivileges(tokenHandle, false, ref newPriv, 0, IntPtr.Zero, IntPtr.Zero); if (!tokenPrivResult) { throw new ApplicationException("Error attempting to adjust the token privileges to allow shutdown.\n Win32 Error Code: " + Marshal.GetLastWin32Error()); } }
/// <summary> /// Tries to enable the specified privilege. /// </summary> /// <param name="privilege">The privilege to enable.</param> /// <exception cref="PrivilegeException">There was an error while requesting a required privilege.</exception> /// <remarks>Thanks to Michael S. Muegel for notifying us about a bug in this code.</remarks> protected static void EnableToken(string privilege) { if (Environment.OSVersion.Platform != PlatformID.Win32NT || !CheckEntryPoint("advapi32.dll", "AdjustTokenPrivileges")) { return; } IntPtr tokenHandle = IntPtr.Zero; NativeMethods.LUID privilegeLUID = new NativeMethods.LUID(); NativeMethods.TOKEN_PRIVILEGES newPrivileges = new NativeMethods.TOKEN_PRIVILEGES(); NativeMethods.TOKEN_PRIVILEGES tokenPrivileges; if (NativeMethodsNet.OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref tokenHandle) == 0) { throw new PrivilegeException(FormatError(Marshal.GetLastWin32Error())); } if (NativeMethodsNet.LookupPrivilegeValue("", privilege, ref privilegeLUID) == 0) { throw new PrivilegeException(FormatError(Marshal.GetLastWin32Error())); } tokenPrivileges.PrivilegeCount = 1; tokenPrivileges.Privileges.Attributes = SE_PRIVILEGE_ENABLED; tokenPrivileges.Privileges.pLuid = privilegeLUID; int size = 4; if (NativeMethodsNet.AdjustTokenPrivileges(tokenHandle, 0, ref tokenPrivileges, 4 + (12 * tokenPrivileges.PrivilegeCount), ref newPrivileges, ref size) == 0) { throw new PrivilegeException(FormatError(Marshal.GetLastWin32Error())); } }
public DisplayConfigData(int configDataId, NativeMethods.LUID adapterId, uint targetId, uint sourceId, int leftPosition, int topPosition, uint horizontalResolution, uint verticalResolution) { ConfigDataId = configDataId; AdapterId = adapterId; TargetId = targetId; SourceId = sourceId; LeftPosition = leftPosition; TopPosition = topPosition; HorizontalResolution = horizontalResolution; VerticalResolution = verticalResolution; }
private IntPtr GetTokenWithEnabledPrivilege(string privilege, NativeMethods.TOKEN_PRIVILEGE previousState) { IntPtr zero = IntPtr.Zero; bool flag = true; try { flag = NativeMethods.OpenThreadToken(NativeMethods.GetCurrentThread(), 40, true, out zero); if (!flag) { if ((long)Marshal.GetLastWin32Error() == (long)0x3f0) { flag = NativeMethods.OpenProcessToken(NativeMethods.GetCurrentProcess(), 40, out zero); } if (!flag) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } NativeMethods.LUID lUID = new NativeMethods.LUID(); flag = NativeMethods.LookupPrivilegeValue(null, privilege, ref lUID); if (flag) { NativeMethods.TOKEN_PRIVILEGE tOKENPRIVILEGE = new NativeMethods.TOKEN_PRIVILEGE(); tOKENPRIVILEGE.PrivilegeCount = 1; tOKENPRIVILEGE.Privilege.Attributes = 2; tOKENPRIVILEGE.Privilege.Luid = lUID; uint num = 0; flag = NativeMethods.AdjustTokenPrivileges(zero, false, ref tOKENPRIVILEGE, Marshal.SizeOf(previousState), ref previousState, ref num); if (!flag) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } else { throw new Win32Exception(Marshal.GetLastWin32Error()); } } finally { if (!flag) { NativeMethods.CloseHandle(zero); zero = IntPtr.Zero; } } return(zero); }
public static void EnablePrivilege(SecurityEntity securityEntity) { if (!Enum.IsDefined(typeof(SecurityEntity), securityEntity)) { throw new InvalidEnumArgumentException("securityEntity", (int)securityEntity, typeof(SecurityEntity)); } var securityEntityValue = GetSecurityEntityValue(securityEntity); try { var locallyUniqueIdentifier = new NativeMethods.LUID(); if (NativeMethods.LookupPrivilegeValue(null, securityEntityValue, ref locallyUniqueIdentifier)) { var TOKEN_PRIVILEGES = new NativeMethods.TOKEN_PRIVILEGES(); TOKEN_PRIVILEGES.PrivilegeCount = 1; TOKEN_PRIVILEGES.Attributes = NativeMethods.SE_PRIVILEGE_ENABLED; TOKEN_PRIVILEGES.Luid = locallyUniqueIdentifier; var tokenHandle = IntPtr.Zero; try { var currentProcess = NativeMethods.GetCurrentProcess(); if (NativeMethods.OpenProcessToken(currentProcess, NativeMethods.TOKEN_ADJUST_PRIVILEGES | NativeMethods.TOKEN_QUERY, out tokenHandle)) { if (NativeMethods.AdjustTokenPrivileges(tokenHandle, false, ref TOKEN_PRIVILEGES, 1024, IntPtr.Zero, IntPtr.Zero)) { var lastError = Marshal.GetLastWin32Error(); if (lastError == NativeMethods.ERROR_NOT_ALL_ASSIGNED) { var win32Exception = new Win32Exception(); throw new InvalidOperationException("AdjustTokenPrivileges failed.", win32Exception); } } else { var win32Exception = new Win32Exception(); throw new InvalidOperationException("AdjustTokenPrivileges failed.", win32Exception); } } else { var win32Exception = new Win32Exception(); var exceptionMessage = string.Format(CultureInfo.InvariantCulture, "OpenProcessToken failed. CurrentProcess: {0}", currentProcess.ToInt32()); throw new InvalidOperationException(exceptionMessage, win32Exception); } } finally { if (tokenHandle != IntPtr.Zero) { NativeMethods.CloseHandle(tokenHandle); } } } else { var win32Exception = new Win32Exception(); var exceptionMessage = string.Format(CultureInfo.InvariantCulture, "LookupPrivilegeValue failed. SecurityEntityValue: {0}", securityEntityValue); throw new InvalidOperationException(exceptionMessage, win32Exception); } } catch (Exception e) { var exceptionMessage = string.Format(CultureInfo.InvariantCulture, "GrandPrivilege failed. SecurityEntity: {0}", securityEntity); throw new InvalidOperationException(exceptionMessage, e); } }
private static NativeMethods.DISPLAYCONFIG_MODE_INFO FindSourceModeInfo(IEnumerable <NativeMethods.DISPLAYCONFIG_MODE_INFO> modeInfoArray, NativeMethods.LUID adapterId, uint sourceId) { foreach (var modeInfo in modeInfoArray) { if (modeInfo.infoType == NativeMethods.DISPLAYCONFIG_MODE_INFO_TYPE.Source && modeInfo.adapterId.HighPart == adapterId.HighPart && modeInfo.adapterId.LowPart == adapterId.LowPart && modeInfo.id == sourceId) { return(modeInfo); } } throw new InvalidOperationException("Couldn't find the source mode info."); }
/// <summary> /// The LookupPrivilegeValue function retrieves the locally unique identifier (LUID) used on a specified system to locally represent the specified privilege name. /// </summary> /// <param name="lpSystemName">Pointer to a null-terminated string specifying the name of the system on which the privilege name is looked up. If a null string is specified, the function attempts to find the privilege name on the local system.</param> /// <param name="lpName">Pointer to a null-terminated string that specifies the name of the privilege, as defined in the Winnt.h header file. For example, this parameter could specify the constant SE_SECURITY_NAME, or its corresponding string, "SeSecurityPrivilege".</param> /// <param name="lpLuid">Pointer to a variable that receives the locally unique identifier by which the privilege is known on the system, specified by the lpSystemName parameter.</param> /// <returns>If the function succeeds, the return value is nonzero.<br></br><br>If the function fails, the return value is zero. To get extended error information, call Marshal.GetLastWin32Error.</br></returns> public static int LookupPrivilegeValue(string lpSystemName, string lpName, ref NativeMethods.LUID lpLuid) { return(NativeMethods.LookupPrivilegeValue(lpSystemName, lpName, ref lpLuid)); }
private static bool SetPrivilege( string securityPrivilege, bool bEnablePrivilege // to enable or disable privilege ) { var identity = WindowsIdentity.GetCurrent(TokenAccessLevels.AdjustPrivileges | TokenAccessLevels.Query); var accessToken = identity.Token; NativeMethods.TOKEN_PRIVILEGES tp; NativeMethods.LUID luid = new NativeMethods.LUID(); if (!NativeMethods.LookupPrivilegeValue( null, // lookup privilege on local system securityPrivilege, // privilege to lookup ref luid)) // receives LUID of privilege { throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()); } tp.PrivilegeCount = 1; tp.Privileges = new NativeMethods.LUID_AND_ATTRIBUTES[1]; tp.Privileges[0].Luid = luid; if (bEnablePrivilege) { tp.Privileges[0].Attributes = NativeMethods.SE_PRIVILEGE_ENABLED; } else { tp.Privileges[0].Attributes = NativeMethods.SE_PRIVILEGE_DISABLED; } NativeMethods.TOKEN_PRIVILEGES previousPrivileges = new NativeMethods.TOKEN_PRIVILEGES(); uint previousPrivilegesLength = 0; // Enable the privilege or disable all privileges. bool succeeded = NativeMethods.AdjustTokenPrivileges( accessToken, false, ref tp, 1024, ref previousPrivileges, out previousPrivilegesLength); if (!succeeded) { throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()); } else if (Marshal.GetLastWin32Error() == NativeMethods.ERROR_NOT_ALL_ASSIGNED) { #if !DMLIB_TEST throw new TransferException( string.Format( CultureInfo.CurrentCulture, Resources.FailedToEnablePrivilegeException, securityPrivilege)); #else throw new Win32Exception(Marshal.GetLastWin32Error()); #endif } if ((previousPrivileges.Privileges.Count() == 1) && (previousPrivileges.Privileges[0].Luid.LowPart == luid.LowPart) && (previousPrivileges.Privileges[0].Luid.HighPart == luid.HighPart) && (previousPrivileges.Privileges[0].Attributes == NativeMethods.SE_PRIVILEGE_ENABLED)) { return(true); } else { return(false); } }