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; }
/// <summary> /// Returns the current thread or process token with the specified privilege enabled /// and the previous state of this privilege. Free the returned token /// by calling NativeMethods.CloseHandle. /// </summary> private IntPtr GetTokenWithEnabledPrivilege( string privilege, NativeMethods.TOKEN_PRIVILEGE previousState) { IntPtr pToken = IntPtr.Zero; bool ret = true; try { // First try to open the thread token for privilege adjustment. ret = NativeMethods.OpenThreadToken( NativeMethods.GetCurrentThread(), NativeMethods.TOKEN_QUERY | NativeMethods.TOKEN_ADJUST_PRIVILEGES, true, out pToken); if (!ret) { if (Marshal.GetLastWin32Error() == NativeMethods.ERROR_NO_TOKEN) { // Client is not impersonating. Open the process token. ret = NativeMethods.OpenProcessToken( NativeMethods.GetCurrentProcess(), NativeMethods.TOKEN_QUERY | NativeMethods.TOKEN_ADJUST_PRIVILEGES, out pToken); } if (!ret) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } // Get the LUID of the specified privilege. NativeMethods.LUID luid = new NativeMethods.LUID(); ret = NativeMethods.LookupPrivilegeValue( null, privilege, ref luid); if (!ret) { throw new Win32Exception(Marshal.GetLastWin32Error()); } // Enable the privilege. NativeMethods.TOKEN_PRIVILEGE newState = new NativeMethods.TOKEN_PRIVILEGE(); newState.PrivilegeCount = 1; newState.Privilege.Attributes = NativeMethods.SE_PRIVILEGE_ENABLED; newState.Privilege.Luid = luid; uint previousSize = 0; ret = NativeMethods.AdjustTokenPrivileges( pToken, false, ref newState, (uint)Marshal.SizeOf(previousState), ref previousState, ref previousSize); if (!ret) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } finally { if (!ret) { NativeMethods.CloseHandle(pToken); pToken = IntPtr.Zero; } } return pToken; }