public static bool SetPrivilegeTokens(this Process process, string privilegeName, ref TokenPrivileges previousState)
        {
            try
            {
                IntPtr tokenHandle;
                if (!NativeMethods.OpenProcessToken(process.Handle,
                        NativeMethods.TokenAdjustPrivileges | NativeMethods.TokenQuery,
                        out tokenHandle))
                    throw new Win32Exception();

                Luid luid;
                if (!NativeMethods.LookupPrivilegeValueW("", privilegeName, out luid))
                    throw new Win32Exception();

                var token = new TokenPrivileges
                    {
                        PrivilegeCount = 1,
                        Luid = luid,
                        Attributes = NativeMethods.PrivilegeEnabled
                    };

                uint requiredSize = 0;
                if (!NativeMethods.AdjustTokenPrivileges(
                    tokenHandle, false, ref token, (uint)Marshal.SizeOf(token), ref previousState, ref requiredSize))
                    throw new Win32Exception();

                return true;
            }
            catch (Exception e)
            {
                Log.WarnFormat("An exception occurred while attempting to set privilege tokens for a process: {0}", e);
                return false;
            }
        }
 internal static extern bool AdjustTokenPrivileges(
     SafeTokenHandle TokenHandle,
     bool DisableAllPrivileges,
     TokenPrivileges NewState,
     int BufferLength,
     IntPtr PreviousState,
     IntPtr ReturnLength
 );
 public static bool EnablePrivilege(string lpszPrivilege, bool
 bEnablePrivilege)
 {
     var retval = false;
     var ltkpOld = 0;
     var hToken = IntPtr.Zero;
     var tkp = new TokenPrivileges {Privileges = new int[3]};
     new TokenPrivileges {Privileges = new int[3]};
     var tLuid = new Luid();
     tkp.PrivilegeCount = 1;
     if (bEnablePrivilege)
         tkp.Privileges[2] = SePrivilegeEnabled;
     else
         tkp.Privileges[2] = 0;
     if (LookupPrivilegeValue(null, lpszPrivilege, ref tLuid))
     {
         var proc = Process.GetCurrentProcess();
         if (proc.Handle != IntPtr.Zero)
         {
             if (OpenProcessToken(proc.Handle, TokenAdjustPrivileges | TokenQuery,
             ref hToken) != 0)
             {
                 tkp.PrivilegeCount = 1;
                 tkp.Privileges[2] = SePrivilegeEnabled;
                 tkp.Privileges[1] = tLuid.HighPart;
                 tkp.Privileges[0] = tLuid.LowPart;
                 const int bufLength = 256;
                 IntPtr tu = Marshal.AllocHGlobal(bufLength);
                 Marshal.StructureToPtr(tkp, tu, true);
                 if (AdjustTokenPrivileges(hToken, 0, tu, bufLength, IntPtr.Zero, ref ltkpOld) != 0)
                 {
                     // successful AdjustTokenPrivileges doesn't mean privilege could be changed
                     if (Marshal.GetLastWin32Error() == 0)
                     {
                         retval = true; // Token changed
                     }
                 }
                 Marshal.FreeHGlobal(tu);
             }
         }
     }
     if (hToken != IntPtr.Zero)
     {
         CloseHandle(hToken);
     }
     return retval;
 }
Exemple #4
0
        public static void AdjustTokenPrivileges(SafeTokenHandle tokenHandle, bool disableAllPrivileges, ref TokenPrivileges newState)
        {
            Contract.Requires<ArgumentNullException>(tokenHandle != null, "tokenHandle cannot be null");

            if (!AdjustTokenPrivileges(tokenHandle.DangerousGetHandle(), disableAllPrivileges, ref newState, 0u, IntPtr.Zero, IntPtr.Zero)) {
                WindowsApi.NativeMethods.ReportWin32Exception();
            }

            var error = Marshal.GetLastWin32Error();

            if (error == ErrorCodes.NotAllAssigned) {
                try {
                    throw new PrivilegeNotHeldException(GetPrivilegeName(PrivilegeFromLuid(newState.Privileges[0].Luid)));
                }
                catch (InvalidOperationException) {
                    throw new PrivilegeNotHeldException();
                }
            }
        }
        public static bool SetPrivilegeTokens(this Process process, TokenPrivileges token)
        {
            try
            {
                IntPtr tokenHandle;
                if (!NativeMethods.OpenProcessToken(process.Handle,
                        NativeMethods.TokenAdjustPrivileges | NativeMethods.TokenQuery,
                        out tokenHandle))
                    throw new Win32Exception();

                var previousState = new TokenPrivileges();
                uint requiredSize = 0;
                if (!NativeMethods.AdjustTokenPrivileges(
                    tokenHandle, false, ref token, (uint)Marshal.SizeOf(token), ref previousState, ref requiredSize))
                    throw new Win32Exception();

                return true;
            }
            catch (Exception e)
            {
                Log.WarnFormat("An exception occurred while attempting to set privilege tokens for a process: {0}", e);
                return false;
            }
        }
Exemple #6
0
        public static bool AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges, out TokenPrivileges NewState, int BufferLength, out TokenPrivileges PreviousState, out int ReturnLength, [CallerMemberName] string callerName = "")
        {
            if (!PInvokeDebugger.LoggingEnabled)
            {
                return(PInvoke_AdjustTokenPrivileges(TokenHandle, DisableAllPrivileges, out NewState, BufferLength, out PreviousState, out ReturnLength));
            }

            bool             returnValue = PInvoke_AdjustTokenPrivileges(TokenHandle, DisableAllPrivileges, out NewState, BufferLength, out PreviousState, out ReturnLength);
            PInvokeDebugInfo debugInfo   = PInvokeDebugInfo.TraceDebugInfo(
                ModuleName,
                nameof(AdjustTokenPrivileges),
                callerName,
                returnValue,
                false,
                nameof(TokenHandle), TokenHandle,
                nameof(DisableAllPrivileges), DisableAllPrivileges,
                nameof(NewState), NewState,
                nameof(BufferLength), BufferLength,
                nameof(PreviousState), PreviousState,
                nameof(ReturnLength), ReturnLength
                );

            PInvokeDebugger.SafeCapture(debugInfo);
            return(returnValue);
        }
 public static extern bool AdjustTokenPrivileges(IntPtr tokenHandle, bool disableAllPrivileges, ref TokenPrivileges newState, int bufferLength, IntPtr previousState, IntPtr returnLength);
Exemple #8
0
		static void Main(string[] args)
		{
            // Check settings
            var version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            if (!version.Equals( Properties.Settings.Default.Version ))
            {
                // Upgrade
                Properties.Settings.Default.Upgrade();
                Properties.Settings.Default.Version = version;
                Properties.Settings.Default.Save();
            }

            // Initial delay
			if (Properties.Settings.Default.StartupDelay > 0) Thread.Sleep(Properties.Settings.Default.StartupDelay * 1000);

			// Be fully safe
			try
			{
				// Get a token for this process
				IntPtr hToken;
				if (OpenProcessToken(Process.GetCurrentProcess().Handle, 0x28, out hToken))
				{
					// Helper
					TokenPrivileges pPriv = new TokenPrivileges();

					// Lookup the privilege value
					if (LookupPrivilegeValue(null, "SeShutdownPrivilege", out pPriv.Luid))
					{
						// Finish
						pPriv.PrivilegeCount = 1;
						pPriv.Attributes = 2;

						// Update
						AdjustTokenPrivileges(hToken, false, ref pPriv, 0, IntPtr.Zero, IntPtr.Zero);
					}

					// Release
					CloseHandle(hToken);
				}

				// Load language
				string language = Properties.Settings.Default.Language;
				if (!string.IsNullOrEmpty(language))
					try
					{
						// Choose it
						Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(language);
					}
					catch
					{
						// Ignore any error
					}

				// Initialize
				Application.EnableVisualStyles();
				Application.SetCompatibleTextRenderingDefault(false);

				// Create 
				using (VCRNETControl main = new VCRNETControl(args))
                    if ((1 == args.Length) && args[0].Equals("/install"))
                    {
                        // Run
                        Application.Run(main);
                    }
                    else
                    {
                        // Run
                        Application.Run();
                    }
			}
			catch (Exception e)
			{
				// Report and terminate
				MessageBox.Show(e.ToString());
			}
		}
Exemple #9
0
 static private extern bool AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges, ref TokenPrivileges NewState, UInt32 BufferLength, IntPtr PreviousState, IntPtr ReturnLength);
Exemple #10
0
        // Based on http://blogs.microsoft.co.il/sasha/2009/07/09/launch-a-process-as-standard-user-from-an-elevated-process/
        public unsafe static Process CreateProcessAsStandardUser(string exePath, string arguments, bool launchSuspended = false)
        {
            //Enable SeIncreaseQuotaPrivilege in this process.  (This requires administrative privileges.)
            IntPtr hProcessToken  = IntPtr.Zero;
            var    currentProcess = Process.GetCurrentProcess();

            if (!OpenProcessToken(currentProcess.Handle, TokenAcess.AdjustPrivileges, out hProcessToken))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            try
            {
                TokenPrivileges tkp = new TokenPrivileges();
                tkp.PrivilegeCount = 1;
                if (!LookupPrivilegeValue(null, IncreaseQuotaName, out Luid luid))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                tkp.Attributes = PrivilegeEnabled;

                if (!AdjustTokenPrivileges(hProcessToken, false, ref tkp, 0, IntPtr.Zero, IntPtr.Zero))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
            finally
            {
                CloseHandle(hProcessToken);
            }

            //Get window handle representing the desktop shell.  This might not work if there is no shell window, or when
            //using a custom shell.  Also note that we're assuming that the shell is not running elevated.
            IntPtr hShellWnd = GetShellWindow();

            if (hShellWnd == IntPtr.Zero)
            {
                throw new InvalidOperationException("Unable to locate shell window; you might be using a custom shell");
            }


            int shellPid;

            GetWindowThreadProcessId(hShellWnd, out shellPid);
            if (shellPid == 0)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            //Open the desktop shell process in order to get the process token.
            IntPtr hShellProcess = OpenProcess(ProcessQueryInformation, false, shellPid);

            if (hShellProcess == IntPtr.Zero)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }


            IntPtr hShellProcessToken = IntPtr.Zero;
            IntPtr hPrimaryToken      = IntPtr.Zero;

            try
            {
                //Get the process token of the desktop shell.
                if (!OpenProcessToken(hShellProcess, TokenAcess.Duplicate, out hShellProcessToken))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                //Duplicate the shell's process token to get a primary token.
                const TokenAcess tokenRights = TokenAcess.Query | TokenAcess.AssignPrimary | TokenAcess.Duplicate | TokenAcess.AdjustDefault | TokenAcess.AdjustSessionId;
                if (!DuplicateTokenEx(hShellProcessToken, tokenRights, IntPtr.Zero, SecurityImpersonationLevel.Impersonation, TokenType.Primary, out hPrimaryToken))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                if (!IsUacEnabled)
                {
                    if (!ConvertStringSidToSid(MediumIntegritySid, out IntPtr sid))
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }

                    // Set integrity level to Medium
                    TokenMandatoryLabel tokenMandatoryLabel = new TokenMandatoryLabel();
                    tokenMandatoryLabel.Label.Attributes = GroupIntegrity;
                    tokenMandatoryLabel.Label.Sid        = sid;
                    var size = Marshal.SizeOf(tokenMandatoryLabel) + GetLengthSid(sid);
                    if (!SetTokenInformation(hPrimaryToken, TokenInformationClass.IntegrityLevel, &tokenMandatoryLabel, size))
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }

                    // Remove elevation from token - Commented out because I couldn't get it to work.
                    //TokenElevation elevation = new TokenElevation();
                    //if (!SetTokenInformation(hPrimaryToken, TokenInformationClass.Elevation, &elevation, 4))
                    //    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                //Start the target process with the new token.
                StartupInfo        startupInfo = new StartupInfo();
                ProcessInformation pi          = new ProcessInformation();
                var creationFlags = launchSuspended ? CreateSuspended : 0;
                if (!CreateProcessWithTokenW(hPrimaryToken, 0, exePath, exePath + " " + arguments, creationFlags, IntPtr.Zero, IntPtr.Zero, ref startupInfo, out pi))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                CloseHandle(pi.ProcessHandle);
                CloseHandle(pi.ThreadHandle);
                return(Process.GetProcessById(pi.ProcessId));
            }
            finally
            {
                if (hShellProcessToken != IntPtr.Zero)
                {
                    CloseHandle(hShellProcessToken);
                }

                if (hPrimaryToken != IntPtr.Zero)
                {
                    CloseHandle(hPrimaryToken);
                }

                if (hShellProcess != IntPtr.Zero)
                {
                    CloseHandle(hShellProcess);
                }
            }
        }
 public bool Equals(TokenPrivileges other)
 {
     return PrivilegeCount == other.PrivilegeCount && Attributes == other.Attributes;
 }
 public static extern bool AdjustTokenPrivileges(
     [In] IntPtr tokenHandle,
     [MarshalAs(UnmanagedType.Bool)] bool disableAllPrivileges,
     ref TokenPrivileges newState,
     uint bufferLength,
     ref TokenPrivileges previousState,
     ref uint returnLength);
Exemple #13
0
 internal static extern bool PInvoke_AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges, out TokenPrivileges NewState, int BufferLength, out TokenPrivileges PreviousState, out int ReturnLength);
Exemple #14
0
 private static extern bool AdjustTokenPrivileges(IntPtr tokenHandle, bool disableAllPrivileges, [MarshalAs(UnmanagedType.Struct)] ref TokenPrivileges newState, int bufferLength,
                                                  IntPtr previousState, ref int returnLength);
 internal static extern bool AdjustTokenPrivileges(IntPtr hToken, bool disableAllPrivileges, ref TokenPrivileges newState, int len, IntPtr previousState, IntPtr returnLen);
Exemple #16
0
 static extern bool AdjustTokenPrivileges(IntPtr TokenHandle,
    [MarshalAs(UnmanagedType.Bool)] bool DisableAllPrivileges,
    ref TokenPrivileges NewState,
    UInt32 Zero,
    IntPtr Null1,
    IntPtr Null2);
Exemple #17
0
 static private extern bool AdjustTokenPrivileges( IntPtr handle, bool disableAllPrivileges, ref TokenPrivileges newState, UInt32 bufferLength, IntPtr previousState, IntPtr returnLength );
Exemple #18
0
        /// <summary>
        /// Der SCM möchte den VCR.NET Recording Service starten.
        /// </summary>
        /// <param name="args">Befehlszeilenparameter für den Start.</param>
        protected override void OnStart( string[] args )
        {
            // Fully save
            try
            {
                // Report
                Tools.ExtendedLogging( "SCM has requested a Service Start" );

                // Report delay
                if (!Tools.DebugMode)
                    RequestAdditionalTime( 300000 );

                // Create server instance
                VCRServer = new VCRServer( Tools.ApplicationDirectory.Parent );

                // Create web server instance
                m_WebServer = new WebServer.ServerHost( VCRServer );

                // Report
                Tools.ExtendedLogging( "Attaching Process" );

                // Get a token for this process
                IntPtr processToken;
                if (!OpenProcessToken( Process.GetCurrentProcess().Handle, 0x28, out processToken ))
                    return;

                // Report
                Tools.ExtendedLogging( "Aquiring Shutdown Privileges" );

                // Helper
                TokenPrivileges privileges = new TokenPrivileges();

                // Lookup the privilege value
                if (LookupPrivilegeValue( null, "SeShutdownPrivilege", out privileges.Luid ))
                {
                    // Finish
                    privileges.PrivilegeCount = 1;
                    privileges.Attributes = 2;

                    // Update
                    if (!AdjustTokenPrivileges( processToken, false, ref privileges, 0, IntPtr.Zero, IntPtr.Zero ))
                        VCRServer.Log( LoggingLevel.Security, EventLogEntryType.Warning, Properties.Resources.AquirePrivilegeFailed );
                }
                else
                {
                    // Report
                    VCRServer.Log( LoggingLevel.Security, EventLogEntryType.Error, Properties.Resources.LookupPrivilegeFailed );
                }

                // Release
                CloseHandle( processToken );

                // Report
                Tools.ExtendedLogging( "Web Server Start initiated from Thread {0}", Thread.CurrentThread.ManagedThreadId );

                // Create the web server on a separate thread
                m_webStarter = new Thread( () =>
                    {
                        // Be safe
                        try
                        {
                            // Report
                            Tools.ExtendedLogging( "Starting Web Server on Thread {0}", Thread.CurrentThread.ManagedThreadId );

                            // Start Web Server
                            m_WebServer.Start();
                        }
                        catch (Exception e)
                        {
                            // Report
                            EventLog.WriteEntry( e.ToString(), EventLogEntryType.Error );
                        }
                    } );

                // Start it
                m_webStarter.Start();

                // Report
                Tools.ExtendedLogging( "Final Initialisation started" );

                // Start our child process and report success
                VCRServer.Log( LoggingLevel.Full, Properties.Resources.ServiceStarted );

                // Register with power manager
                PowerManager.OnChanged += HibernationChanged;

                // Run initial scan
                PowerManager.OnResume();

                // Create hibernate thread
                m_HibernateHelper = new Thread( ReTestShutdown ) { Name = "Periodic Check for Hibernation" };
                m_HibernateHelper.Start();

                // Report
                Tools.ExtendedLogging( "Returning Control to SCM" );
            }
            catch (Exception e)
            {
                // Report
                Tools.LogException( "OnStart", e );

                // Process
                throw e;
            }
        }
 internal static extern bool AdjustTokenPrivileges([In] SafeNativeHandle tokenHandle,
                                                   [In] bool disableAllPrivileges, [In] ref TokenPrivileges newState, [In] uint bufferLength,
                                                   IntPtr previousState, IntPtr returnLength);