/// <summary> /// Sets privilege /// </summary> public static bool SetPrivilege(string privilege, bool enabled) { bool result = false; try { var tp = new TokPriv1Luid(); IntPtr hproc = Process.GetCurrentProcess().Handle; IntPtr htok = IntPtr.Zero; if (OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok)) { tp.Count = 1; tp.Luid = 0; tp.Attr = ((enabled) ? (SE_PRIVILEGE_ENABLED) : (SE_PRIVILEGE_REMOVED)); if (!LookupPrivilegeValue(null, privilege, ref tp.Luid)) return false; result = (AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero)); // Cleanup CloseHandle(htok); } } catch { } return result; }
public static bool SetPrivilege(string privilege, bool enabled) { try { TokPriv1Luid tp = new TokPriv1Luid(); IntPtr hproc = System.Diagnostics.Process.GetCurrentProcess().Handle; IntPtr htok = IntPtr.Zero; if (!OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok)) return false; if (!LookupPrivilegeValue(null, privilege, ref tp.Luid)) return false; tp.Count = 1; tp.Luid = 0; tp.Attr = ((enabled) ? (SE_PRIVILEGE_ENABLED) : (0)); AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero); if (Marshal.GetLastWin32Error() != 0) return false; return true; } catch { return false; } }
internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
/// <summary> /// 调整自身令牌 /// </summary> /// <returns></returns> private static bool AdjustSelfToken() { const int TOKEN_QUERY = 0x00000008; const int TOKEN_ADJUST_PRIVILEGES = 0x00000020; const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege"; var hTok = IntPtr.Zero; if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref hTok) == false) { return false; } var tokp = new TokPriv1Luid { Count = 1, Luid = 0, Attr = 0x00000002 }; if (LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref tokp.Luid) == false) { return false; } return AdjustTokenPrivileges(hTok, false, ref tokp, 0, IntPtr.Zero, IntPtr.Zero); }
internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disableAllPrivileges, ref TokPriv1Luid newState, int len, IntPtr prev, IntPtr relen);
internal static extern bool AdjustTokenPrivileges( IntPtr htok, [MarshalAs(UnmanagedType.Bool)] bool disall, ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
/// <summary> /// Duplicates the token information derived /// from the logged in user's credentials. This /// is required to run the application on the /// logged in users desktop. /// </summary> /// <returns>Returns true if the application was successfully started in the user's desktop.</returns> public Process ExecuteAppAsLoggedOnUser(string AppName, string CmdLineArgs) { //WriteToLog("In ExecuteAppAsLoggedOnUser for all users."); IntPtr LoggedInUserToken = IntPtr.Zero; IntPtr DuplicateToken = IntPtr.Zero; IntPtr ShellProcessToken = IntPtr.Zero; Process currProc = Process.GetCurrentProcess(); bool result = OpenProcessToken(currProc.Handle, TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, ref LoggedInUserToken); if (!result) { WriteToLog("OpenProcessToken failed: " + Marshal.GetLastWin32Error()); return(null); } //Below part for increasing the UAC previleges to the token. TokPriv1Luid tp = new TokPriv1Luid(); tp.Count = 1; tp.Luid = 0; if (!LookupPrivilegeValue(null, SE_INCREASE_QUOTA_NAME, ref tp.Luid)) { WriteToLog("LookupPrivilegeValue failed: " + Marshal.GetLastWin32Error()); return(null); } tp.Attr = SE_PRIVILEGE_ENABLED; if (!AdjustTokenPrivileges(LoggedInUserToken, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero)) { WriteToLog("OpenProcessToken failed: " + Marshal.GetLastWin32Error()); return(null); } CloseHandle(LoggedInUserToken); List <Process> explorerProcessList = new List <Process>(); string trayProcessName = Path.GetFileNameWithoutExtension( AppName); // AppName.Substring(AppName.LastIndexOf(@"\") + 1, AppName.Length - AppName.LastIndexOf(@"\") - 5); string userName = ""; foreach (Process explorerProcess in Process.GetProcessesByName("explorer")) { userName = GetProcessUser(explorerProcess); bool IsProcessRunningForUser = userName.Equals(MainService.MTTerminalUserName, StringComparison.InvariantCultureIgnoreCase); //foreach (Process PHTrayProcess in Process.GetProcessesByName(trayProcessName)) //{ // if (explorerProcess.SessionId == PHTrayProcess.SessionId ) // { // if (log.IsDebugEnabled) // log.Debug(trayProcessName + " is already running for user SessionId " + explorerProcess.SessionId); // IsProcessRunningForUser = true; // break; // } //} if ((Environment.OSVersion.Version.Major > 5 && explorerProcess.SessionId > 0 || Environment.OSVersion.Version.Major == 5) && IsProcessRunningForUser) { if (MainService.thisGlobal.IsDebug()) { log.Info($"Desktop is running for user {userName} and SessionId " + explorerProcess.SessionId); } explorerProcessList.Add(explorerProcess); break; } } if (null != explorerProcessList && explorerProcessList.Count > 0) { foreach (Process explorerProcess in explorerProcessList) { Process ShellProcess = explorerProcess; ShellProcess.StartInfo.LoadUserProfile = true; try { int tokenRights = MAXIMUM_ALLOWED; //TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID; if (!OpenProcessToken(ShellProcess.Handle, tokenRights, ref ShellProcessToken)) { WriteToLog("Unable to OpenProcessToken " + Marshal.GetLastWin32Error()); return(null); } SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES(); sa.nLength = Marshal.SizeOf(sa); if (Environment.UserInteractive && Debugger.IsAttached) { // In debug mode tokens obtained differently IntPtr hToken = WindowsIdentity.GetCurrent().Token; if (!DuplicateTokenEx(hToken, GENERIC_ALL_ACCESS, ref sa, 1, 1, ref DuplicateToken)) { WriteToLog("Unable to duplicate token " + Marshal.GetLastWin32Error()); return(null); } } else { if (!DuplicateTokenEx(ShellProcessToken, tokenRights, ref sa, 2, 1, ref DuplicateToken)) { WriteToLog("Unable to duplicate token " + Marshal.GetLastWin32Error()); return(null); } } //if (MainService.thisGlobal.IsDebug()) // log.Info("Duplicated the token " + WindowsIdentity.GetCurrent().Name); //WriteToLog("Duplicated the token " + WindowsIdentity.GetCurrent().Name); SECURITY_ATTRIBUTES processAttributes = new SECURITY_ATTRIBUTES(); SECURITY_ATTRIBUTES threadAttributes = new SECURITY_ATTRIBUTES(); PROCESS_INFORMATION pi; STARTUPINFO si = new STARTUPINFO(); si.cb = (uint)Marshal.SizeOf(si); IntPtr UserEnvironment = IntPtr.Zero; uint dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE; if (!CreateEnvironmentBlock(out UserEnvironment, ShellProcessToken, true)) { WriteToLog("Unable to create user's enviroment block " + Marshal.GetLastWin32Error()); } else { dwCreationFlags |= CREATE_UNICODE_ENVIRONMENT; } string WorkingDir = Path.GetDirectoryName(AppName); if (!CreateProcessAsUser(DuplicateToken, AppName, CmdLineArgs, ref processAttributes, ref threadAttributes, true, dwCreationFlags, UserEnvironment, WorkingDir, ref si, out pi)) { WriteToLog("Unable to create process " + Marshal.GetLastWin32Error()); if (Marshal.GetLastWin32Error() == 740) { WriteToLog( "Please check the installation as some elevated permissions is required to execute the binaries"); } return(null); } log.Info(string.Format("Process {0} started under user {1} successfully", AppName, userName)); Process trayApp = Process.GetProcessById(Convert.ToInt32(pi.dwProcessId)); trayApp.StartInfo.LoadUserProfile = true; return(trayApp); //break; } finally { if (ShellProcessToken != null) { CloseHandle(ShellProcessToken); } if (DuplicateToken != null) { CloseHandle(DuplicateToken); } } } } else { WriteToLog("No user has been identified to have logged into the system."); } //WriteToLog("Finished ExecuteAppAsLoggedOnUser for all users."); return(null); }
private static extern bool AdjustTokenPrivileges(IntPtr htoken, bool disable, ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
static extern bool AdjustTokenPrivileges(IntPtr tokenHandle, [MarshalAs(UnmanagedType.Bool)] bool disableAllPrivileges, ref TokPriv1Luid newState, UInt32 zero, IntPtr null1, IntPtr null2);
internal static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, [MarshalAs(UnmanagedType.Bool)] bool DisableAllPrivileges, ref TokPriv1Luid NewState, uint BufferLength, IntPtr PreviousState, IntPtr ReturnLength);