/// <summary> /// 获取更高级别的操作系统权限。 /// </summary> /// <param name="privilege">需要获得的权限。</param> /// <exception cref="Win32ApiErrorInformationException">当出现未知的或者无法处理的Win32Api错误代码时,则需要抛出这个异常。</exception> public static void GetSystemAuthority(string privilege) { if (!Win32ApiHelper.CheckEntryPoint("advapi32.dll", "AdjustTokenPrivileges")) { return; } IntPtr tokenHandle = IntPtr.Zero; SLocallyUniqueIdentifier luid = new SLocallyUniqueIdentifier(); STokenPrivileges newPrivileges = new STokenPrivileges(); STokenPrivileges tokenPrivileges; if (!OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref tokenHandle)) { throw new Win32ApiErrorInformationException(); } if (LookupPrivilegeValue(null, privilege, ref luid) == 0) { throw new Win32ApiErrorInformationException(); } tokenPrivileges.PrivilegeCount = 1; tokenPrivileges.Privileges.Attributes = SE_PRIVILEGE_ENABLED; tokenPrivileges.Privileges.ParticularLuid = luid; int size = 4; if (AdjustTokenPrivileges(tokenHandle, 0, ref tokenPrivileges, 4 + (12 * tokenPrivileges.PrivilegeCount), ref newPrivileges, ref size) == 0) { throw new Win32ApiErrorInformationException(); } }
/// <summary> /// 修改指定进程的权限。 /// </summary> /// <param name="processName">指定的待修改进程。</param> /// <param name="systemName">需要被操作的系统,弱势本地系统,这里可以指定为空(NULL Or Nothing)。</param> /// <param name="operationType">待操作的类型,这个操作类型通畅可以用TOKEN_ADJUST_PRIVILEGES代替。</param> /// <param name="privileges">指定的权限(特权)。</param> /// <returns>如果这个方法的操作成功则为true,反之为false。</returns> /// <remarks>该操作允许用户修改指定的进程的权限,不过这个操作可能存在风险,所以在提升权限的时候要谨慎操作。</remarks> public static bool UpdateProcessPrivileges(string processName, string systemName, Int32 operationType, STokenPrivileges privileges) { IntPtr hwnd_t = IntPtr.Zero; bool rv; PrivilegeGetter.LookupPrivilegeValue(systemName, processName, ref privileges.Privileges.ParticularLuid); PrivilegeGetter.OpenProcessToken(PrivilegeGetter.GetCurrentProcess(), operationType, hwnd_t); PrivilegeGetter.AdjustTokenPrivileges(hwnd_t, false, ref privileges, 100000, new STokenPrivileges(), 0); rv = GetLastError() == ERROR_SUCCESS ? true : false; PrivilegeGetter.CloseHandle(hwnd_t); return(rv); }
private static extern int AdjustTokenPrivileges(IntPtr token, int isUnenableJuri, ref STokenPrivileges tokenPrivileges, int bufferLength, ref STokenPrivileges bufferPointer, ref int bufferSize);