Example #1
0
 private void RevertPrivilege(NativeMethods.TOKEN_PRIVILEGES priv)
 {
     if (!NativeMethods.AdjustTokenPrivileges(token, false, ref priv, 0, IntPtr.Zero, IntPtr.Zero))
     {
         throw new System.ComponentModel.Win32Exception();
     }
 }
    private static bool AssertPrivelege(string privelege)
    {
        IntPtr token;
        var    tokenPrivileges = new NativeMethods.TOKEN_PRIVILEGES( );

        tokenPrivileges.Privileges = new NativeMethods.LUID_AND_ATTRIBUTES[1];
        var success =
            NativeMethods.OpenProcessToken(NativeMethods.GetCurrentProcess( ), NativeMethods.TOKEN_ADJUST_PRIVILEGES, out token)
            &&
            NativeMethods.LookupPrivilegeValue(null, privelege, out tokenPrivileges.Privileges[0].Luid);

        try
        {
            if (success)
            {
                tokenPrivileges.PrivilegeCount           = 1;
                tokenPrivileges.Privileges[0].Attributes = NativeMethods.SE_PRIVILEGE_ENABLED;
                success =
                    NativeMethods.AdjustTokenPrivileges(token, false, ref tokenPrivileges, Marshal.SizeOf(tokenPrivileges), IntPtr.Zero, IntPtr.Zero)
                    &&
                    (Marshal.GetLastWin32Error( ) == 0);
            }
            if (!success)
            {
                Console.WriteLine("Could not assert privilege: " + privelege);
            }
        }
        finally
        {
            NativeMethods.CloseHandle(token);
        }
        return(success);
    }
Example #3
0
        /// <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()));
            }
        }
Example #5
0
        private void EnablePrivilege(Privilege priv)
        {
            NativeMethods.TOKEN_PRIVILEGES newState  = new NativeMethods.TOKEN_PRIVILEGES(LuidFromPrivilege(priv), NativeMethods.PrivilegeAttributes.Enabled);
            NativeMethods.TOKEN_PRIVILEGES prevState = new NativeMethods.TOKEN_PRIVILEGES();
            uint retLen = 0;

            if (!NativeMethods.AdjustTokenPrivileges(token, false, ref newState, NativeMethods.TOKEN_PRIVILEGES.SizeInBytes, ref prevState, ref retLen))
            {
                throw new System.ComponentModel.Win32Exception();
            }
            if ((prevState.Privileges.Attributes & NativeMethods.PrivilegeAttributes.Enabled) != NativeMethods.PrivilegeAttributes.Enabled)
            {
                prevPrivs.Push(prevState);
            }
        }
Example #6
0
        private static bool EnableDebugPrivileges()
        {
            var result = false;

            IntPtr token;

            if (NativeMethods.OpenProcessToken(System.Diagnostics.Process.GetCurrentProcess().Handle, TokenAccessLevels.AllAccess, out token))
            {
                var privileges = new NativeMethods.TOKEN_PRIVILEGES();
                privileges.PrivilegeCount = 1;
                privileges.Luid.LowPart   = 0x14;
                privileges.Luid.HighPart  = 0;
                privileges.Attributes     = 2;

                result = NativeMethods.AdjustTokenPrivileges(token, false, ref privileges, 0, IntPtr.Zero, IntPtr.Zero);

                NativeMethods.CloseHandle(token);
            }

            return(result);
        }
Example #7
0
        /// <summary>
        /// Set the SeTimeZonePrivilege, which controls access to the SetDynamicTimeZoneInformation API
        /// </summary>
        /// <param name="enable">Set to true to enable (or false to disable) the privilege.</param>
        protected void SetAccessToken(bool enable)
        {
            // open the access token for the current process
            IntPtr hToken   = IntPtr.Zero;
            IntPtr hProcess = NativeMethods.GetCurrentProcess();

            if (!NativeMethods.OpenProcessToken(hProcess,
                                                NativeMethods.TOKEN_ADJUST_PRIVILEGES | NativeMethods.TOKEN_QUERY, ref hToken))
            {
                ThrowWin32Error();
            }

            try
            {
                // setup the privileges being requested
                NativeMethods.TOKEN_PRIVILEGES tp = new NativeMethods.TOKEN_PRIVILEGES()
                {
                    PrivilegeCount = 1,
                    Luid           = 0,
                    Attributes     = (enable ? NativeMethods.SE_PRIVILEGE_ENABLED : 0),
                };

                // lookup the Luid of the SeTimeZonePrivilege
                if (!NativeMethods.LookupPrivilegeValue(null, NativeMethods.SE_TIME_ZONE_NAME, ref tp.Luid))
                {
                    ThrowWin32Error();
                }

                // set the privilege for the open access token
                if (!NativeMethods.AdjustTokenPrivileges(hToken, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero))
                {
                    ThrowWin32Error();
                }
            }
            finally
            {
                NativeMethods.CloseHandle(hToken);
            }
        }
Example #8
0
        /// <summary>
        /// Set the SeTimeZonePrivilege, which controls access to the SetDynamicTimeZoneInformation API
        /// </summary>
        /// <param name="enable">Set to true to enable (or false to disable) the privilege.</param>
        protected void SetAccessToken(bool enable)
        {
            // open the access token for the current process
            IntPtr hToken = IntPtr.Zero;
            IntPtr hProcess = NativeMethods.GetCurrentProcess();
            if (!NativeMethods.OpenProcessToken(hProcess,
                NativeMethods.TOKEN_ADJUST_PRIVILEGES | NativeMethods.TOKEN_QUERY, ref hToken))
            {
                ThrowWin32Error();
            }

            try
            {
                // setup the privileges being requested
                NativeMethods.TOKEN_PRIVILEGES tp = new NativeMethods.TOKEN_PRIVILEGES()
                {
                    PrivilegeCount = 1,
                    Luid = 0,
                    Attributes = (enable ? NativeMethods.SE_PRIVILEGE_ENABLED : 0),
                };

                // lookup the Luid of the SeTimeZonePrivilege
                if (!NativeMethods.LookupPrivilegeValue(null, NativeMethods.SE_TIME_ZONE_NAME, ref tp.Luid))
                {
                    ThrowWin32Error();
                }

                // set the privilege for the open access token
                if (!NativeMethods.AdjustTokenPrivileges(hToken, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero))
                {
                    ThrowWin32Error();
                }
            }
            finally
            {
                NativeMethods.CloseHandle(hToken);
            }
        }
        public bool Start()
        {
            processInfo = new NativeMethods.ProcessInformation();
            var startInfo = new NativeMethods.StartupInfo();
            var success   = false;

            SafeFileHandle hToken, hReadOut, hWriteOut, hReadErr, hWriteErr, hReadIn, hWriteIn;

            var securityAttributes = new NativeMethods.SecurityAttributes();

            securityAttributes.bInheritHandle = true;

            success = NativeMethods.CreatePipe(out hReadOut, out hWriteOut, securityAttributes, 0);
            if (!success)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            success = NativeMethods.CreatePipe(out hReadErr, out hWriteErr, securityAttributes, 0);
            if (!success)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            success = NativeMethods.CreatePipe(out hReadIn, out hWriteIn, securityAttributes, 0);
            if (!success)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            success = NativeMethods.SetHandleInformation(hReadOut, NativeMethods.Constants.HANDLE_FLAG_INHERIT, 0);
            if (!success)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            // Logon user
            success = NativeMethods.LogonUser(
                runSpec.Credentials.UserName,
                runSpec.Credentials.Domain,
                runSpec.Credentials.Password,
                NativeMethods.LogonType.LOGON32_LOGON_BATCH,
                NativeMethods.LogonProvider.LOGON32_PROVIDER_DEFAULT,
                out hToken
                );
            if (!success)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            NativeMethods.LUID privilegeLuid;
            if (!NativeMethods.LookupPrivilegeValue(null, "SeImpersonatePrivilege", out privilegeLuid))
            {
                int lastError = Marshal.GetLastWin32Error();
                throw new Win32Exception(lastError, "Error calling LookupPrivilegeValue: " + lastError);
            }

            var tokenPrivileges = new NativeMethods.TOKEN_PRIVILEGES();

            tokenPrivileges.PrivilegeCount = 1;
            tokenPrivileges.Attributes     = 1;
            tokenPrivileges.Luid           = privilegeLuid;
            if (!NativeMethods.AdjustTokenPrivileges(hToken, false,
                                                     ref tokenPrivileges,
                                                     1024, IntPtr.Zero, IntPtr.Zero))
            {
                var lastError = Marshal.GetLastWin32Error();
                throw new Win32Exception(lastError, "Error calling AdjustTokenPrivileges: " + lastError);
            }

            IntPtr unmanagedEnv;

            if (!NativeMethods.CreateEnvironmentBlock(out unmanagedEnv, hToken.DangerousGetHandle(), false))
            {
                int lastError = Marshal.GetLastWin32Error();
                throw new Win32Exception(lastError, "Error calling CreateEnvironmentBlock: " + lastError);
            }

            // Create process
            startInfo.cb         = Marshal.SizeOf(startInfo);
            startInfo.dwFlags    = NativeMethods.Constants.STARTF_USESTDHANDLES;
            startInfo.hStdOutput = hWriteOut;
            startInfo.hStdError  = hWriteErr;
            startInfo.hStdInput  = hReadIn;

            success = NativeMethods.CreateProcessWithTokenW(
                hToken,
                NativeMethods.LogonFlags.WithProfile,
                null,
                CommandLine(),
                NativeMethods.CreateProcessFlags.CREATE_UNICODE_ENVIRONMENT,
                unmanagedEnv,
                null,
                ref startInfo,
                out processInfo
                );

            if (!success)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            NativeMethods.DestroyEnvironmentBlock(unmanagedEnv);
            NativeMethods.CloseHandle(processInfo.hThread);

            Handle = processInfo.hProcess;

            startInfo.hStdOutput.Close();
            startInfo.hStdError.Close();
            startInfo.hStdInput.Close();
            StandardOutput = new StreamReader(new FileStream(hReadOut, FileAccess.Read), Console.OutputEncoding);
            StandardError  = new StreamReader(new FileStream(hReadErr, FileAccess.Read), Console.OutputEncoding);
            StandardInput  = new StreamWriter(new FileStream(hWriteIn, FileAccess.Write), Console.InputEncoding)
            {
                AutoFlush = true
            };

            WaitForExitAsync();

            return(success);
        }
Example #10
0
    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);
        }
    }
Example #11
0
 /// <summary>
 /// The AdjustTokenPrivileges function enables or disables privileges in the specified access token. Enabling or disabling privileges in an access token requires TOKEN_ADJUST_PRIVILEGES access.
 /// </summary>
 /// <param name="TokenHandle">Handle to the access token that contains the privileges to be modified. The handle must have TOKEN_ADJUST_PRIVILEGES access to the token. If the PreviousState parameter is not NULL, the handle must also have TOKEN_QUERY access.</param>
 /// <param name="DisableAllPrivileges">Specifies whether the function disables all of the token's privileges. If this value is TRUE, the function disables all privileges and ignores the NewState parameter. If it is FALSE, the function modifies privileges based on the information pointed to by the NewState parameter.</param>
 /// <param name="NewState">Pointer to a TOKEN_PRIVILEGES structure that specifies an array of privileges and their attributes. If the DisableAllPrivileges parameter is FALSE, AdjustTokenPrivileges enables or disables these privileges for the token. If you set the SE_PRIVILEGE_ENABLED attribute for a privilege, the function enables that privilege; otherwise, it disables the privilege. If DisableAllPrivileges is TRUE, the function ignores this parameter.</param>
 /// <param name="BufferLength">Specifies the size, in bytes, of the buffer pointed to by the PreviousState parameter. This parameter can be zero if the PreviousState parameter is NULL.</param>
 /// <param name="PreviousState">Pointer to a buffer that the function fills with a TOKEN_PRIVILEGES structure that contains the previous state of any privileges that the function modifies. This parameter can be NULL.</param>
 /// <param name="ReturnLength">Pointer to a variable that receives the required size, in bytes, of the buffer pointed to by the PreviousState parameter. This parameter can be NULL if PreviousState is NULL.</param>
 /// <returns>If the function succeeds, the return value is nonzero. To determine whether the function adjusted all of the specified privileges, call Marshal.GetLastWin32Error.</returns>
 public static int AdjustTokenPrivileges(IntPtr TokenHandle, int DisableAllPrivileges, ref NativeMethods.TOKEN_PRIVILEGES NewState, int BufferLength, ref NativeMethods.TOKEN_PRIVILEGES PreviousState, ref int ReturnLength)
 {
     return(NativeMethods.AdjustTokenPrivileges(TokenHandle, DisableAllPrivileges, ref NewState, BufferLength, ref PreviousState, ref ReturnLength));
 }
Example #12
0
        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);
            }
        }