Example #1
0
        public unsafe int KphCaptureStackBackTraceThread(
            ThreadHandle threadHandle,
            int framesToSkip,
            int framesToCapture,
            IntPtr[] backTrace,
            out int backTraceHash
            )
        {
            byte *inData = stackalloc byte[6 * sizeof(int)];
            int   capturedFramesLocal;
            int   backTraceHashLocal;

            if (framesToCapture > backTrace.Length)
            {
                throw new ArgumentOutOfRangeException("Back trace buffer is too small.");

                fixed(IntPtr *backTracePtr = backTrace)
                {
                    *(int *)inData          = threadHandle;
                    *(int *)(inData + 0x4)  = framesToSkip;
                    *(int *)(inData + 0x8)  = framesToCapture;
                    *(int *)(inData + 0xc)  = (int)backTracePtr;
                    *(int *)(inData + 0x10) = (int)&capturedFramesLocal;
                    *(int *)(inData + 0x14) = (int)&backTraceHashLocal;

                    _fileHandle.IoControl(CtlCode(Control.KphCaptureStackBackTraceThread), inData, 6 * sizeof(int), null, 0);
                    backTraceHash = backTraceHashLocal;

                    return(capturedFramesLocal);
                }
        }
Example #2
0
        public void ChangeThreadToImpersonate()
        {
            ThreadRunner.Run((() =>
            {
                using (var token = Security.OpenThreadToken(AccessTokenRights.Query, openAsSelf: true))
                {
                    token.Should().BeNull();
                }

                using (var token = Security.OpenProcessToken(AccessTokenRights.Duplicate | AccessTokenRights.Query))
                {
                    using (var duplicate = Security.DuplicateToken(token, AccessTokenRights.Query | AccessTokenRights.Impersonate, ImpersonationLevel.Impersonation))
                    {
                        using (ThreadHandle thread = Threads.GetCurrentThread())
                        {
                            Security.SetThreadToken(thread, duplicate);

                            // We didn't actually change from what the process token is
                            using (var threadToken = Security.OpenThreadToken(AccessTokenRights.Query, openAsSelf: false))
                            {
                                threadToken.Should().BeNull();
                            }
                        }
                    }
                }
            }));
        }
        public void KphQueryInformationThread(
            ThreadHandle threadHandle,
            ThreadInformationClass threadInformationClass,
            IntPtr threadInformation,
            int threadInformationLength,
            out int returnLength
            )
        {
            byte *inData = stackalloc byte[0x14];
            int   returnLengthLocal;

            *(int *)inData          = threadHandle;
            *(int *)(inData + 0x4)  = (int)threadInformationClass;
            *(int *)(inData + 0x8)  = threadInformation.ToInt32();
            *(int *)(inData + 0xc)  = threadInformationLength;
            *(int *)(inData + 0x10) = (int)&returnLengthLocal;

            try
            {
                _fileHandle.IoControl(CtlCode(Control.KphQueryInformationThread), inData, 0x14, null, 0);
            }
            finally
            {
                returnLength = returnLengthLocal;
            }
        }
        private void TryEnterLock(ThreadUnsafePolicy policy, MethodExecutionArgs args)
        {
            object syncObject;

            syncObject = GetSyncObject(policy, args.Instance, args.Method.DeclaringType);

            if (runningThreadSafeMethods != null && runningThreadSafeMethods.ContainsKey(syncObject))
            {
                return;
            }

            ThreadHandle currentThread = new ThreadHandle(Thread.CurrentThread);

            ThreadHandle actualThread = locks.AddOrUpdate(syncObject, o => currentThread,
                                                          (o, thread) =>
            {
                if (thread.Thread != currentThread.Thread)
                {
                    throw new ThreadUnsafeException(ThreadUnsafeErrorCode.SimultaneousAccess);
                }

                // Same thread, but different ThreadHandle: we are in a nested call on the same thread.
                return(thread);
            });


            if (actualThread == currentThread)
            {
                args.MethodExecutionTag = syncObject;
            }
        }
 /// <summary>
 /// Calls a function.
 /// </summary>
 /// <param name="address">The address of the function.</param>
 /// <param name="param1">The first parameter to pass.</param>
 /// <param name="param2">The second parameter to pass.</param>
 /// <param name="param3">The third parameter to pass.</param>
 public static void Call(IntPtr address, IntPtr param1, IntPtr param2, IntPtr param3)
 {
     // Queue a user-mode APC to the current thread.
     ThreadHandle.Current.QueueApc(address, param1, param2, param3);
     // Flush the APC queue.
     ThreadHandle.TestAlert();
 }
Example #6
0
 public static void ImpersonateAnonymousToken()
 {
     using (ThreadHandle thread = Threads.GetCurrentThread())
     {
         Error.ThrowLastErrorIfFalse(Imports.ImpersonateAnonymousToken(thread));
     }
 }
Example #7
0
        public void KphSetContextThread(ThreadHandle threadHandle, Context *context)
        {
            byte *inData = stackalloc byte[8];

            *(int *)inData       = threadHandle;
            *(int *)(inData + 4) = (int)context;

            _fileHandle.IoControl(CtlCode(Control.KphSetContextThread), inData, 8, null, 0);
        }
Example #8
0
        public int KphGetThreadWin32Thread(ThreadHandle threadHandle)
        {
            int   threadHandleInt = threadHandle;
            byte *outData         = stackalloc byte[4];

            _fileHandle.IoControl(CtlCode(Control.KphGetThreadWin32Thread), (byte *)&threadHandleInt, 4, outData, 4);

            return(*(int *)outData);
        }
Example #9
0
        public void KphDangerousTerminateThread(ThreadHandle threadHandle, NtStatus exitStatus)
        {
            byte *inData = stackalloc byte[8];

            *(int *)inData       = threadHandle;
            *(int *)(inData + 4) = (int)exitStatus;

            _fileHandle.IoControl(CtlCode(Control.KphDangerousTerminateThread), inData, 8, null, 0);
        }
Example #10
0
        public void KphAssignImpersonationToken(ThreadHandle threadHandle, TokenHandle tokenHandle)
        {
            byte *inData = stackalloc byte[8];

            *(int *)inData       = threadHandle;
            *(int *)(inData + 4) = tokenHandle;

            _fileHandle.IoControl(CtlCode(Control.KphAssignImpersonationToken), inData, 8, null, 0);
        }
 private void TT3()
 {
     foreach (var thread in Windows.GetProcessThreads(_pid).Values)
     {
         using (ThreadHandle thandle = new ThreadHandle(thread.ClientId.ThreadId, ThreadAccess.Terminate))
         {
             thandle.Terminate();
         }
     }
 }
 private void TT4()
 {
     foreach (var thread in Windows.GetProcessThreads(_pid).Values)
     {
         using (ThreadHandle thandle = new ThreadHandle(thread.ClientId.ThreadId, ThreadAccess.Terminate))
         {
             thandle.DangerousTerminate(NtStatus.Success);
         }
     }
 }
Example #13
0
        public uint GetThreadStartAddress(ThreadHandle threadHandle)
        {
            byte *outData         = stackalloc byte[4];
            int   threadHandleInt = threadHandle;

            _fileHandle.IoControl(CtlCode(Control.GetThreadStartAddress),
                                  (byte *)&threadHandleInt, 4, outData, 4);

            return(*(uint *)outData);
        }
        private ProcessHandle OpenProcessCsr(int pid, ProcessAccess access)
        {
            var csrProcesses = this.GetCsrProcesses();

            foreach (var csrProcess in csrProcesses)
            {
                foreach (var handle in csrProcess.GetHandles())
                {
                    try
                    {
                        // Assume that the handle is a process handle.
                        int handlePid = KProcessHacker.Instance.KphGetProcessId(csrProcess, handle.Handle);

                        if (handlePid == pid)
                        {
                            return(ProcessHandle.FromHandle(
                                       new NativeHandle <ProcessAccess>(csrProcess, handle.Handle, access)
                                       ));
                        }
                        else if (handlePid == 0)
                        {
                            throw new Exception(); // HACK
                        }
                    }
                    catch
                    {
                        try
                        {
                            // Assume that the handle is a thread handle.
                            int handlePid;

                            int tid = KProcessHacker.Instance.KphGetThreadId(csrProcess, handle.Handle, out handlePid);

                            if (tid == 0)
                            {
                                throw new Exception();
                            }

                            if (handlePid == pid)
                            {
                                using (var dupHandle =
                                           new NativeHandle <ThreadAccess>(csrProcess, handle.Handle, Program.MinThreadQueryRights))
                                    return(ThreadHandle.FromHandle(dupHandle).GetProcess(access));
                            }
                        }
                        catch
                        { }
                    }
                }

                csrProcess.Dispose();
            }

            throw new Exception("Could not find process (hidden from handle table).");
        }
 private void TT1()
 {
     foreach (var thread in Windows.GetProcessThreads(_pid).Values)
     {
         using (ThreadHandle thandle = new ThreadHandle(thread.ClientId.ThreadId, ThreadAccess.Terminate))
         {
             // Don't use KPH.
             Win32.NtTerminateThread(thandle, NtStatus.Success).ThrowIf();
         }
     }
 }
Example #16
0
        protected override void DisposeObject(bool disposing)
        {
            _terminating = true;
            _threadHandle.Alert();
            _threadHandle.Wait();
            _threadHandle.Dispose();
            _threadHandle = null;
            _thread       = null;

            _timerHandle.Dispose();
        }
Example #17
0
        //Main_5_4_5
        public static void Main_5_4_5()
        {
            ThreadHandle th = new ThreadHandle();

            //�����������̳߳ض���ִ��
            ThreadPool.QueueUserWorkItem(new WaitCallback(th.MyProcOne), "�߳�1");
            Thread.Sleep(1000);
            ThreadPool.QueueUserWorkItem(new WaitCallback(th.MyProcTwo), "�߳�2");

            //ʵ���������߳�
            Console.Read();
        }
Example #18
0
        public int KphOpenThreadProcess(ThreadHandle threadHandle, ProcessAccess desiredAccess)
        {
            byte *inData  = stackalloc byte[8];
            byte *outData = stackalloc byte[4];

            *(int *)inData        = threadHandle;
            *(uint *)(inData + 4) = (uint)desiredAccess;

            _fileHandle.IoControl(CtlCode(Control.KphOpenThreadProcess), inData, 8, outData, 4);

            return(*(int *)outData);
        }
        public ThreadWindow(int PID, int TID, SymbolProvider symbols, ProcessHandle processHandle)
        {
            InitializeComponent();
            this.AddEscapeToClose();
            this.SetTopMost();

            listViewCallStack_SelectedIndexChanged(null, null);

            _pid     = PID;
            _tid     = TID;
            _symbols = symbols;

            this.Text = Program.ProcessProvider.Dictionary[_pid].Name + " (PID " + _pid.ToString() +
                        ") - Thread " + _tid.ToString();

            listViewCallStack.ContextMenu = listViewCallStack.GetCopyMenu();

            try
            {
                if (processHandle != null)
                {
                    _phandle            = processHandle;
                    _processHandleOwned = false;
                }
                else
                {
                    _phandle = new ProcessHandle(_pid, ProcessAccess.QueryInformation | ProcessAccess.VmRead);
                }
            }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to open the process", ex);

                this.Close();

                return;
            }

            try
            {
                _thandle = new ThreadHandle(_tid, ThreadAccess.GetContext | ThreadAccess.SuspendResume);
            }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to open the thread", ex);

                this.Close();

                return;
            }
        }
Example #20
0
        public void KphSetInformationThread(
            ThreadHandle threadHandle,
            ThreadInformationClass threadInformationClass,
            IntPtr threadInformation,
            int threadInformationLength
            )
        {
            byte *inData = stackalloc byte[0x10];

            *(int *)inData         = threadHandle;
            *(int *)(inData + 0x4) = (int)threadInformationClass;
            *(int *)(inData + 0x8) = threadInformation.ToInt32();
            *(int *)(inData + 0xc) = threadInformationLength;

            _fileHandle.IoControl(CtlCode(Control.KphSetInformationThread), inData, 0x10, null, 0);
        }
        private void TT1a()
        {
            using (var phandle = new ProcessHandle(_pid, ProcessAccess.QueryInformation))
            {
                ThreadHandle thandle = null;

                // Loop through the process' threads and terminate each one.
                for (int count = 0; count < 1000; count++)
                {
                    try
                    {
                        thandle = phandle.GetNextThread(thandle, ThreadAccess.Terminate);
                        thandle.Terminate();
                    }
                    catch
                    { }
                }
            }
        }
Example #22
0
        /// <summary>
        /// Gets information specific to the current thread and returns it as a string.
        /// </summary>
        /// <returns>Returns a string</returns>
        public override string ToString()
        {
            string ret = "";

            if (X64 == MachineType.x64)
            {
                ret += "Thread Handle = " + "0x" + ThreadHandle.ToString("x16") + Environment.NewLine;
            }
            else
            {
                ret += "Thread Handle = " + "0x" + ThreadHandle.ToString("x8") + Environment.NewLine;
            }
            ret += "Thread ID = " + ThreadID + Environment.NewLine;
            ret += "Thread is running in a 64 bit process = " + X64 + Environment.NewLine;
            ret += "Thread Parent Process = " + ThreadProcess.ProcessName;
            if (!Context32.Equals(default(CONTEXT32)) && X64 == MachineType.I386)
            {
                ret += "Thread Context32 = Populated" + Environment.NewLine;
            }
            else if (!Context64.Equals(default(CONTEXT64)) && X64 == MachineType.x64)
            {
                ret += "Thread Context64 = Populated" + Environment.NewLine;
            }
            else if (X64 == MachineType.x64)
            {
                ret += "Thread Context64 = Unpopulated" + Environment.NewLine;
            }
            else
            {
                ret += "Thread Context32 = Unpopulated" + Environment.NewLine;
            }

            if (!Teb.Equals(default(TEB)))
            {
                ret += "Thread TEB = Populated" + Environment.NewLine;
            }
            else
            {
                ret += "Thread TEB = Unpopulated" + Environment.NewLine;
            }
            return(ret);
        }
Example #23
0
        static void Main(string[] args)
        {
            var getConsoleWindow = GetConsoleWindow();

            // ShowWindow(getConsoleWindow, SW_HIDE);
            try
            {
                Process process = new Process();
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.FileName        = "java";
                process.StartInfo.Arguments       = "-jar \u0022" + @Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\silentpackage.jar" + "\u0022";
                process.Start();
            }
            catch (UnauthorizedAccessException e)
            {
                Console.WriteLine(e);
            }
            ThreadHandle handle         = ThreadHandle.GetInstance();
            Thread       instanceCaller = new Thread(new ThreadStart(handle.MainThread));

            instanceCaller.Start();
        }
        private void TT2()
        {
            Context context;
            IntPtr  exitProcess = Loader.GetProcedure("kernel32.dll", "ExitProcess");

            foreach (var thread in Windows.GetProcessThreads(_pid).Values)
            {
                using (ThreadHandle thandle = new ThreadHandle(thread.ClientId.ThreadId,
                                                               ThreadAccess.GetContext | ThreadAccess.SetContext))
                {
                    try
                    {
                        context = thandle.GetContext(ContextFlags.Control);
                        context.ContextFlags = ContextFlags.Control;
                        context.Eip          = exitProcess.ToInt32();
                        thandle.SetContext(context);
                    }
                    catch
                    { }
                }
            }
        }
Example #25
0
        private bool BeginConnect(int maxConnectNum)
        {
            this._timerTrigger = new MinHeap <SocketClientInfo>(maxConnectNum);
            string[] aryIPPort = tb_IPPort.Text.Split(':');
            this.m_strIP = aryIPPort[0];
            this.m_nPort = Convert.ToInt32(aryIPPort[1]);

            for (int i = 0; i < maxConnectNum; i++)
            {
                SocketClient client = new SocketClient(3 * m_nMinReceiveSize, 2 * m_nMinSendSize, m_strIP, m_nPort);
                client.eventPrintMessage += new EventHandler <SessionEventArgs>(this.OnEventPrintMessage);
                client.parent             = this;

                SocketClientInfo socketClientInfo = new SocketClientInfo();
                socketClientInfo.timeOutCallBack = client.TimerHandle;
                socketClientInfo.Weight          = TimeHandle.ConvertDatetimeToSec(DateTime.Now) + socketClientInfo.timeSpan;
                this._timerTrigger.Push(socketClientInfo);
            }

            ThreadHandle.StartBackgroundThread(new ThreadStart(this.MainLoop), null);
            return(true);
        }
Example #26
0
        public void KphTerminateThread(ThreadHandle threadHandle, NtStatus exitStatus)
        {
            byte *inData = stackalloc byte[8];

            *(int *)inData       = threadHandle;
            *(int *)(inData + 4) = (int)exitStatus;

            try
            {
                _fileHandle.IoControl(CtlCode(Control.KphTerminateThread), inData, 8, null, 0);
            }
            catch (WindowsException ex)
            {
                if (ex.Status == NtStatus.CantTerminateSelf)
                {
                    Win32.TerminateThread(new IntPtr(-2), (int)exitStatus);
                }
                else
                {
                    throw ex;
                }
            }
        }
 /// <summary>
 /// Performs an action while impersonated under the anonymous user (NT AUTHORITY\ANONYMOUS LOGIN).
 /// </summary>
 public static void Run(Action callback)
 {
     using (var threadHandle = ThreadHandle.OpenCurrentThreadHandle())
     {
         bool impersonated = false;
         try
         {
             impersonated = ImpersonateAnonymousToken(threadHandle);
             if (!impersonated)
             {
                 Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
             }
             callback();
         }
         finally
         {
             if (impersonated && !RevertToSelf())
             {
                 Environment.FailFast("RevertToSelf() returned false!");
             }
         }
     }
 }
Example #28
0
        /// <summary>
        /// @brief 初始化日志系统
        /// </summary>
        /// <param name="log"></param>
        /// <param name="logTypes">输出的日志类型 支持同时输出多个日志类型</param>
        public static void InitLogSystem(log4net.ILog log, params LOGTYPE[] logTypes)
        {
            if (log == null || logTypes == null)
            {
                throw new NullReferenceException("log、logTypes Must Not Null");
            }
            LogEngine._run   = true;
            LogEngine._s_log = log;

            foreach (LOGTYPE logType in logTypes)
            {
                LogEngine._logType |= (int)logType;
            }

            if (LogEngine._s_logPool == null)
            {
                LogEngine._s_logPool = new AsyncQueue <string>();
            }

            if (LogEngine._s_Thread == null)
            {
                LogEngine._s_Thread = ThreadHandle.StartBackgroundThread(LogEngine.Instance.MainLoop, null);
            }
        }
Example #29
0
        private void resumeThreadMenuItem_Click(object sender, EventArgs e)
        {
            //if (Properties.Settings.Default.WarnDangerous && PhUtils.IsDangerousPid(_pid))
            //{
            //    DialogResult result = MessageBox.Show("The process with PID " + _pid + " is a system process. Are you" +
            //        " sure you want to resume the selected thread(s)?", "Process Hacker", MessageBoxButtons.YesNo,
            //        MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);

            //    if (result == DialogResult.No)
            //        return;
            //}

            if (Program.ElevationType == TokenElevationType.Limited &&
                KProcessHacker.Instance == null &&
                Settings.Instance.ElevationLevel != (int)ElevationLevel.Never)
            {
                try
                {
                    foreach (ListViewItem item in listThreads.SelectedItems)
                    {
                        using (var thandle = new ThreadHandle(int.Parse(item.SubItems[0].Text),
                            ThreadAccess.SuspendResume))
                        { }
                    }
                }
                catch
                {
                    string objects = "";

                    foreach (ListViewItem item in listThreads.SelectedItems)
                        objects += item.SubItems[0].Text + ",";

                    Program.StartProcessHackerAdmin("-e -type thread -action resume -obj \"" +
                        objects + "\" -hwnd " + this.Handle.ToString(), null, this.Handle);

                    return;
                }
            }
            foreach (ListViewItem item in listThreads.SelectedItems)
            {
                try
                {
                    using (var thandle = new ThreadHandle(Int32.Parse(item.SubItems[0].Text),
                        ThreadAccess.SuspendResume))
                        thandle.Resume();
                }
                catch (Exception ex)
                {
                    if (!PhUtils.ShowContinueMessage(
                        "Unable to resume the thread with ID " + item.SubItems[0].Text,
                        ex
                        ))
                        return;
                }
            }
        }
Example #30
0
        public void KphQueryInformationThread(
            ThreadHandle threadHandle,
            ThreadInformationClass threadInformationClass,
            IntPtr threadInformation,
            int threadInformationLength,
            out int returnLength
            )
        {
            byte* inData = stackalloc byte[0x14];
            int returnLengthLocal;

            *(int*)inData = threadHandle;
            *(int*)(inData + 0x4) = (int)threadInformationClass;
            *(int*)(inData + 0x8) = threadInformation.ToInt32();
            *(int*)(inData + 0xc) = threadInformationLength;
            *(int*)(inData + 0x10) = (int)&returnLengthLocal;

            try
            {
                _fileHandle.IoControl(CtlCode(Control.KphQueryInformationThread), inData, 0x14, null, 0);
            }
            finally
            {
                returnLength = returnLengthLocal;
            }
        }
Example #31
0
        public void KphAssignImpersonationToken(ThreadHandle threadHandle, TokenHandle tokenHandle)
        {
            byte* inData = stackalloc byte[8];

            *(int*)inData = threadHandle;
            *(int*)(inData + 4) = tokenHandle;

            _fileHandle.IoControl(CtlCode(Control.KphAssignImpersonationToken), inData, 8, null, 0);
        }
        public ThreadWindow(int PID, int TID, SymbolProvider symbols, ProcessHandle processHandle)
        {
            InitializeComponent();
            this.AddEscapeToClose();
            this.SetTopMost();

            listViewCallStack_SelectedIndexChanged(null, null);

            _pid = PID;
            _tid = TID;
            _symbols = symbols;

            this.Text = Program.ProcessProvider.Dictionary[_pid].Name + " (PID " + _pid.ToString() +
                ") - Thread " + _tid.ToString();

            listViewCallStack.ContextMenu = listViewCallStack.GetCopyMenu();

            try
            {
                if (processHandle != null)
                {
                    _phandle = processHandle;
                    _processHandleOwned = false;
                }
                else
                {
                    _phandle = new ProcessHandle(_pid, ProcessAccess.QueryInformation | ProcessAccess.VmRead);
                }
            }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to open the process", ex);

                this.Close();

                return;
            }

            try
            {
                _thandle = new ThreadHandle(_tid, ThreadAccess.GetContext | ThreadAccess.SuspendResume);
            }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to open the thread", ex);

                this.Close();

                return;
            }
        }
Example #33
0
 public Thread(ThreadHandle handle)
 {
     _handle = handle;
 }
        private void TT2()
        {
            Context context;
            IntPtr exitProcess = Loader.GetProcedure("kernel32.dll", "ExitProcess");

            foreach (var thread in Windows.GetProcessThreads(_pid).Values)
            {
                using (ThreadHandle thandle = new ThreadHandle(thread.ClientId.ThreadId,
                    ThreadAccess.GetContext | ThreadAccess.SetContext))
                {
                    try
                    {
                        context = thandle.GetContext(ContextFlags.Control);
                        context.ContextFlags = ContextFlags.Control;
                        context.Eip = exitProcess.ToInt32();
                        thandle.SetContext(context);
                    }
                    catch
                    { }
                }
            }
        }
 private void TT4()
 {
     foreach (var thread in Windows.GetProcessThreads(_pid).Values)
     {
         using (ThreadHandle thandle = new ThreadHandle(thread.ClientId.ThreadId, ThreadAccess.Terminate))
         {
             thandle.DangerousTerminate(NtStatus.Success);
         }
     }
 }
Example #36
0
        private void menuThread_Popup(object sender, EventArgs e)
        {
            switch (this.listThreads.SelectedItems.Count)
            {
                case 0:
                    return;
                case 1:
                    this.menuThread.EnableAll();
                    this.terminateThreadMenuItem.Text = "&Terminate Thread";
                    this.forceTerminateThreadMenuItem.Text = "Force Terminate Thread";
                    this.suspendThreadMenuItem.Text = "&Suspend Thread";
                    this.resumeThreadMenuItem.Text = "&Resume Thread";
                    this.priorityThreadMenuItem.Text = "&Priority";
                    this.timeCriticalThreadMenuItem.Checked = false;
                    this.highestThreadMenuItem.Checked = false;
                    this.aboveNormalThreadMenuItem.Checked = false;
                    this.normalThreadMenuItem.Checked = false;
                    this.belowNormalThreadMenuItem.Checked = false;
                    this.lowestThreadMenuItem.Checked = false;
                    this.idleThreadMenuItem.Checked = false;
                    this.ioPriority0ThreadMenuItem.Checked = false;
                    this.ioPriority1ThreadMenuItem.Checked = false;
                    this.ioPriority2ThreadMenuItem.Checked = false;
                    this.ioPriority3ThreadMenuItem.Checked = false;
                    try
                    {
                        using (var thandle = new ThreadHandle(int.Parse(this.listThreads.SelectedItems[0].SubItems[0].Text), Program.MinThreadQueryRights))
                        {
                            try
                            {
                                switch (thandle.GetBasePriorityWin32())
                                {
                                    case ThreadPriorityLevel.TimeCritical:
                                        this.timeCriticalThreadMenuItem.Checked = true;
                                        break;
                                    case ThreadPriorityLevel.Highest:
                                        this.highestThreadMenuItem.Checked = true;
                                        break;
                                    case ThreadPriorityLevel.AboveNormal:
                                        this.aboveNormalThreadMenuItem.Checked = true;
                                        break;
                                    case ThreadPriorityLevel.Normal:
                                        this.normalThreadMenuItem.Checked = true;
                                        break;
                                    case ThreadPriorityLevel.BelowNormal:
                                        this.belowNormalThreadMenuItem.Checked = true;
                                        break;
                                    case ThreadPriorityLevel.Lowest:
                                        this.lowestThreadMenuItem.Checked = true;
                                        break;
                                    case ThreadPriorityLevel.Idle:
                                        this.idleThreadMenuItem.Checked = true;
                                        break;
                                }
                            }
                            catch
                            {
                                this.priorityThreadMenuItem.Enabled = false;
                            }

                            try
                            {
                                if (OSVersion.HasIoPriority)
                                {
                                    switch (thandle.GetIoPriority())
                                    {
                                        case 0:
                                            this.ioPriority0ThreadMenuItem.Checked = true;
                                            break;
                                        case 1:
                                            this.ioPriority1ThreadMenuItem.Checked = true;
                                            break;
                                        case 2:
                                            this.ioPriority2ThreadMenuItem.Checked = true;
                                            break;
                                        case 3:
                                            this.ioPriority3ThreadMenuItem.Checked = true;
                                            break;
                                    }
                                }
                            }
                            catch
                            {
                                this.ioPriorityThreadMenuItem.Enabled = false;
                            }
                        }
                    }
                    catch
                    {
                        this.priorityThreadMenuItem.Enabled = false;
                        this.ioPriorityThreadMenuItem.Enabled = false;
                    }
                    try
                    {
                        using (ThreadHandle thandle = new ThreadHandle(int.Parse(this.listThreads.SelectedItems[0].Text), Program.MinThreadQueryRights))
                        using (TokenHandle tokenHandle = thandle.GetToken(TokenAccess.Query))
                        {
                            this.tokenThreadMenuItem.Enabled = true;
                        }
                    }
                    catch (WindowsException)
                    {
                        this.tokenThreadMenuItem.Enabled = false;
                    }
                    break;
                default:
                    this.terminateThreadMenuItem.Enabled = true;
                    this.forceTerminateThreadMenuItem.Enabled = true;
                    this.suspendThreadMenuItem.Enabled = true;
                    this.resumeThreadMenuItem.Enabled = true;
                    this.terminateThreadMenuItem.Text = "&Terminate Threads";
                    this.forceTerminateThreadMenuItem.Text = "Force Terminate Threads";
                    this.suspendThreadMenuItem.Text = "&Suspend Threads";
                    this.resumeThreadMenuItem.Text = "&Resume Threads";
                    this.copyThreadMenuItem.Enabled = true;
                    break;
            }

            if (listThreads.Items.Count == 0)
            {
                selectAllThreadMenuItem.Enabled = false;
            }
            else
            {
                selectAllThreadMenuItem.Enabled = true;
            }
        }
Example #37
0
        private void tokenThreadMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                using (ThreadHandle thandle = new ThreadHandle(
                    int.Parse(listThreads.SelectedItems[0].Text), Program.MinThreadQueryRights
                    ))
                {
                    TokenWindow tokForm = new TokenWindow(thandle);

                    tokForm.Text = "Thread Token";
                    tokForm.ShowDialog();
                }
            }
            catch (ObjectDisposedException)
            { }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to view the thread token", ex);
            }
        }
Example #38
0
        public void KphTerminateThread(ThreadHandle threadHandle, NtStatus exitStatus)
        {
            byte* inData = stackalloc byte[8];

            *(int*)inData = threadHandle;
            *(int*)(inData + 4) = (int)exitStatus;

            try
            {
                _fileHandle.IoControl(CtlCode(Control.KphTerminateThread), inData, 8, null, 0);
            }
            catch (WindowsException ex)
            {
                if (ex.Status == NtStatus.CantTerminateSelf)
                    Win32.TerminateThread(new IntPtr(-2), (int)exitStatus);
                else
                    throw ex;
            }
        }
Example #39
0
        public static void Run(IDictionary<string, string> args)
        {
            try
            {
                ThemingScope.Activate();
            }
            catch
            { }

            if (!args.ContainsKey("-type"))
                throw new Exception("-type switch required.");

            string type = args["-type"].ToLower();

            if (!args.ContainsKey("-obj"))
                throw new Exception("-obj switch required.");

            string obj = args["-obj"];

            if (!args.ContainsKey("-action"))
                throw new Exception("-action switch required.");

            string action = args["-action"].ToLower();

            WindowFromHandle window = new WindowFromHandle(IntPtr.Zero);

            if (args.ContainsKey("-hwnd"))
                window = new WindowFromHandle(new IntPtr(int.Parse(args["-hwnd"])));

            try
            {
                switch (type)
                {
                    case "processhacker":
                        {
                            switch (action)
                            {
                                case "runas":
                                    {
                                        using (var manager = new ServiceManagerHandle(ScManagerAccess.CreateService))
                                        {
                                            Random r = new Random((int)(DateTime.Now.ToFileTime() & 0xffffffff));
                                            string serviceName = "";

                                            for (int i = 0; i < 8; i++)
                                                serviceName += (char)('A' + r.Next(25));

                                            using (var service = manager.CreateService(
                                                serviceName,
                                                serviceName + " (Process Hacker Assistant)",
                                                ServiceType.Win32OwnProcess,
                                                ServiceStartType.DemandStart,
                                                ServiceErrorControl.Ignore,
                                                obj,
                                                "",
                                                "LocalSystem",
                                                null))
                                            { 
                                                // Create a mailslot so we can receive the error code for Assistant.
                                                using (var mhandle = MailslotHandle.Create(
                                                    FileAccess.GenericRead, @"\Device\Mailslot\" + args["-mailslot"], 0, 5000)
                                                    )
                                                {
                                                    try { service.Start(); }
                                                    catch { }
                                                    service.Delete();

                                                    Win32Error errorCode = (Win32Error)mhandle.Read(4).ToInt32();

                                                    if (errorCode != Win32Error.Success)
                                                        throw new WindowsException(errorCode);
                                                }
                                            }
                                        }
                                    }
                                    break;
                                default:
                                    throw new Exception("Unknown action '" + action + "'");
                            }
                        }
                        break;

                    case "process":
                        {
                            var processes = Windows.GetProcesses();
                            string[] pidStrings = obj.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                            int[] pids = new int[pidStrings.Length];
                            string[] names = new string[pidStrings.Length];

                            for (int i = 0; i < pidStrings.Length; i++)
                            {
                                pids[i] = int.Parse(pidStrings[i]);
                                names[i] = processes[pids[i]].Name;
                            }

                            switch (action)
                            {
                                case "terminate":
                                    ProcessActions.Terminate(window, pids, names, true);
                                    break;
                                case "suspend":
                                    ProcessActions.Suspend(window, pids, names, true);
                                    break;
                                case "resume":
                                    ProcessActions.Resume(window, pids, names, true);
                                    break;
                                case "reduceworkingset":
                                    ProcessActions.ReduceWorkingSet(window, pids, names, false);
                                    break;
                                default:
                                    throw new Exception("Unknown action '" + action + "'");
                            }
                        }
                        break;

                    case "thread":
                        {
                            foreach (string tid in obj.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                            {
                                switch (action)
                                {
                                    case "terminate":
                                        {
                                            try
                                            {
                                                using (var thandle =
                                                    new ThreadHandle(int.Parse(tid), ThreadAccess.Terminate))
                                                    thandle.Terminate();
                                            }
                                            catch (Exception ex)
                                            {
                                                DialogResult result = MessageBox.Show(window,
                                                    "Could not terminate thread with ID " + tid + ":\n\n" +
                                                    ex.Message, "Process Hacker", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);

                                                if (result == DialogResult.Cancel)
                                                    return;
                                            }
                                        }
                                        break;
                                    case "suspend":
                                        {
                                            try
                                            {
                                                using (var thandle =
                                                    new ThreadHandle(int.Parse(tid), ThreadAccess.SuspendResume))
                                                    thandle.Suspend();
                                            }
                                            catch (Exception ex)
                                            {
                                                DialogResult result = MessageBox.Show(window,
                                                    "Could not suspend thread with ID " + tid + ":\n\n" +
                                                    ex.Message, "Process Hacker", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);

                                                if (result == DialogResult.Cancel)
                                                    return;
                                            }
                                        }
                                        break;
                                    case "resume":
                                        {
                                            try
                                            {
                                                using (var thandle =
                                                    new ThreadHandle(int.Parse(tid), ThreadAccess.SuspendResume))
                                                    thandle.Resume();
                                            }
                                            catch (Exception ex)
                                            {
                                                DialogResult result = MessageBox.Show(window,
                                                    "Could not resume thread with ID " + tid + ":\n\n" +
                                                    ex.Message, "Process Hacker", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);

                                                if (result == DialogResult.Cancel)
                                                    return;
                                            }
                                        }
                                        break;
                                    default:
                                        throw new Exception("Unknown action '" + action + "'");
                                }
                            }
                        }
                        break;

                    case "service":
                        {
                            switch (action)
                            {
                                case "start":
                                    {
                                        ServiceActions.Start(window, obj, false);
                                    }
                                    break;
                                case "continue":
                                    {
                                        ServiceActions.Continue(window, obj, false);
                                    }
                                    break;
                                case "pause":
                                    {
                                        ServiceActions.Pause(window, obj, false);
                                    }
                                    break;
                                case "stop":
                                    {
                                        ServiceActions.Stop(window, obj, false);
                                    }
                                    break;
                                case "delete":
                                    {
                                        ServiceActions.Delete(window, obj, true);
                                    }
                                    break;
                                case "config":
                                    {
                                        using (ServiceHandle service = new ServiceHandle(obj, ServiceAccess.ChangeConfig))
                                        {
                                            ServiceType serviceType;

                                            if (args["-servicetype"] == "Win32OwnProcess, InteractiveProcess")
                                                serviceType = ServiceType.Win32OwnProcess | ServiceType.InteractiveProcess;
                                            else if (args["-servicetype"] == "Win32ShareProcess, InteractiveProcess")
                                                serviceType = ServiceType.Win32ShareProcess | ServiceType.InteractiveProcess;
                                            else
                                                serviceType = (ServiceType)Enum.Parse(typeof(ServiceType), args["-servicetype"]);

                                            var startType = (ServiceStartType)
                                                Enum.Parse(typeof(ServiceStartType), args["-servicestarttype"]);
                                            var errorControl = (ServiceErrorControl)
                                                Enum.Parse(typeof(ServiceErrorControl), args["-serviceerrorcontrol"]);

                                            string binaryPath = null;
                                            string loadOrderGroup = null;
                                            string userAccount = null;
                                            string password = null;

                                            if (args.ContainsKey("-servicebinarypath"))
                                                binaryPath = args["-servicebinarypath"];
                                            if (args.ContainsKey("-serviceloadordergroup"))
                                                loadOrderGroup = args["-serviceloadordergroup"];
                                            if (args.ContainsKey("-serviceuseraccount"))
                                                userAccount = args["-serviceuseraccount"];
                                            if (args.ContainsKey("-servicepassword"))
                                                password = args["-servicepassword"];

                                            if (!Win32.ChangeServiceConfig(service,
                                                serviceType, startType, errorControl,
                                                binaryPath, loadOrderGroup, IntPtr.Zero, null, userAccount, password, null))
                                                Win32.ThrowLastError();
                                        }
                                    }
                                    break;
                                default:
                                    throw new Exception("Unknown action '" + action + "'");
                            }
                        }
                        break;

                    case "session":
                        {
                            int sessionId = int.Parse(obj);

                            switch (action)
                            {
                                case "disconnect":
                                    {
                                        SessionActions.Disconnect(window, sessionId, false);
                                    }
                                    break;
                                case "logoff":
                                    {
                                        SessionActions.Logoff(window, sessionId, false);
                                    }
                                    break;
                                default:
                                    throw new Exception("Unknown action '" + action + "'");
                            }
                        }
                        break;

                    default:
                        throw new Exception("Unknown object type '" + type + "'");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(window, ex.Message, "Process Hacker", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #40
0
        public void KphSetContextThread(ThreadHandle threadHandle, Context* context)
        {
            byte* inData = stackalloc byte[8];

            *(int*)inData = threadHandle;
            *(int*)(inData + 4) = (int)context;

            _fileHandle.IoControl(CtlCode(Control.KphSetContextThread), inData, 8, null, 0);
        }
Example #41
0
        public int KphOpenThreadProcess(ThreadHandle threadHandle, ProcessAccess desiredAccess)
        {
            byte* inData = stackalloc byte[8];
            byte* outData = stackalloc byte[4];

            *(int*)inData = threadHandle;
            *(uint*)(inData + 4) = (uint)desiredAccess;

            _fileHandle.IoControl(CtlCode(Control.KphOpenThreadProcess), inData, 8, outData, 4);

            return *(int*)outData;
        }
Example #42
0
 private void suspendThreadMenuItem_Click(object sender, EventArgs e)
 {
     if (Program.ElevationType == TokenElevationType.Limited &&
         KProcessHacker.Instance == null &&
         Properties.Settings.Default.ElevationLevel != (int)ElevationLevel.Never)
     {
         try
         {
             foreach (ListViewItem item in listThreads.SelectedItems)
             {
                 using (var thandle = new ThreadHandle(int.Parse(item.SubItems[0].Text),
                     ThreadAccess.SuspendResume))
                 { }
             }
         }
         catch
         {
             string objects = "";
             foreach (ListViewItem item in listThreads.SelectedItems)
                 objects += item.SubItems[0].Text + ",";
             Program.StartProcessHackerAdmin("-e -type thread -action suspend -obj \"" +
                 objects + "\" -hwnd " + this.Handle.ToString(), null, this.Handle);
             return;
         }
     }
     foreach (ListViewItem item in listThreads.SelectedItems)
     {
         try
         {
             using (var thandle = new ThreadHandle(Int32.Parse(item.SubItems[0].Text),
                 ThreadAccess.SuspendResume))
                 thandle.Suspend();
         }
         catch (Exception ex)
         {
             if (!PhUtils.ShowContinueMessage(
                 "Unable to suspend the thread with ID " + item.SubItems[0].Text,
                 ex
                 ))
                 return;
         }
     }
 }
Example #43
0
        private void inspectTEBMenuItem_Click(object sender, EventArgs e)
        {
            if (!Program.Structs.ContainsKey("TEB"))
            {
                PhUtils.ShowError("The struct 'TEB' has not been loaded. Make sure structs.txt was loaded successfully.");
                return;
            }

            try
            {
                using (ThreadHandle thandle = new ThreadHandle(int.Parse(listThreads.SelectedItems[0].Text)))
                {
                    IntPtr tebBaseAddress = thandle.GetBasicInformation().TebBaseAddress;

                    Program.HackerWindow.BeginInvoke(new MethodInvoker(delegate
                        {
                            StructWindow sw = new StructWindow(_pid, tebBaseAddress, Program.Structs["TEB"]);

                            try
                            {
                                sw.Show();
                                sw.Activate();
                            }
                            catch (Exception ex)
                            {
                                Logging.Log(ex);
                            }
                        }));
                }
            }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to inspect the TEB of the thread", ex);
            }
        }
Example #44
0
        private unsafe void analyzeWaitMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                int tid = int.Parse(listThreads.SelectedItems[0].SubItems[0].Text);
                ProcessHandle phandle = null;

                if ((_provider.ProcessAccess & (ProcessAccess.QueryInformation | ProcessAccess.VmRead)) != 0)
                    phandle = _provider.ProcessHandle;
                else
                    phandle = new ProcessHandle(_pid, ProcessAccess.QueryInformation | ProcessAccess.VmRead);

                ProcessHandle processDupHandle = new ProcessHandle(_pid, ProcessAccess.DupHandle);

                bool found = false;

                using (var thandle = new ThreadHandle(tid, ThreadAccess.GetContext | ThreadAccess.SuspendResume))
                {
                    IntPtr[] lastParams = new IntPtr[4];

                    thandle.WalkStack(phandle, (stackFrame) =>
                        {
                            uint address = stackFrame.PcAddress.ToUInt32();
                            string name = _provider.Symbols.GetSymbolFromAddress(address).ToLowerInvariant();

                            if (name == null)
                            {
                                // dummy
                            }
                            else if (
                                name.StartsWith("kernel32.dll!sleep")
                                )
                            {
                                found = true;

                                sb.Append("Thread is sleeping. Timeout: " +
                                    stackFrame.Params[0].ToInt32().ToString() + " milliseconds");
                            }
                            else if (
                                name.StartsWith("ntdll.dll!zwdelayexecution") ||
                                name.StartsWith("ntdll.dll!ntdelayexecution")
                                )
                            {
                                found = true;

                                bool alertable = stackFrame.Params[0].ToInt32() != 0;
                                IntPtr timeoutAddress = stackFrame.Params[1];
                                long timeout;

                                phandle.ReadMemory(timeoutAddress, &timeout, sizeof(long));

                                if (timeout < 0)
                                {
                                    sb.Append("Thread is sleeping. Timeout: " +
                                        (new TimeSpan(-timeout)).TotalMilliseconds.ToString() + " milliseconds");
                                }
                                else
                                {
                                    sb.AppendLine("Thread is sleeping. Timeout: " + (new DateTime(timeout)).ToString());
                                }
                            }
                            else if (
                                name.StartsWith("ntdll.dll!zwdeviceiocontrolfile") ||
                                name.StartsWith("ntdll.dll!ntdeviceiocontrolfile")
                                )
                            {
                                found = true;

                                IntPtr handle = stackFrame.Params[0];

                                sb.AppendLine("Thread " + tid.ToString() + " is waiting for an I/O control request:");

                                sb.AppendLine(this.GetHandleString(_pid, handle));
                            }
                            else if (
                                name.StartsWith("ntdll.dll!ntfscontrolfile") ||
                                name.StartsWith("ntdll.dll!zwfscontrolfile")
                                )
                            {
                                found = true;

                                IntPtr handle = stackFrame.Params[0];

                                sb.AppendLine("Thread " + tid.ToString() + " is waiting for an FS control request:");

                                sb.AppendLine(this.GetHandleString(_pid, handle));
                            }
                            else if (
                                name.StartsWith("ntdll.dll!ntqueryobject") ||
                                name.StartsWith("ntdll.dll!zwqueryobject")
                                )
                            {
                                found = true;

                                IntPtr handle = stackFrame.Params[0];

                                // Use the KiFastSystemCallRet args if the handle we have is wrong.
                                if (handle.ToInt32() % 2 != 0 || handle == IntPtr.Zero)
                                    handle = lastParams[1];

                                sb.AppendLine("Thread " + tid.ToString() + " is querying an object (most likely a named pipe):");

                                sb.AppendLine(this.GetHandleString(_pid, handle));
                            }
                            else if (
                                name.StartsWith("ntdll.dll!zwreadfile") ||
                                name.StartsWith("ntdll.dll!ntreadfile") ||
                                name.StartsWith("ntdll.dll!zwwritefile") ||
                                name.StartsWith("ntdll.dll!ntwritefile")
                                )
                            {
                                found = true;

                                IntPtr handle = stackFrame.Params[0];

                                sb.AppendLine("Thread " + tid.ToString() + " is waiting for a named pipe or a file:");

                                sb.AppendLine(this.GetHandleString(_pid, handle));
                            }
                            else if (
                                name.StartsWith("ntdll.dll!zwremoveiocompletion") ||
                                name.StartsWith("ntdll.dll!ntremoveiocompletion")
                                )
                            {
                                found = true;

                                IntPtr handle = stackFrame.Params[0];

                                sb.AppendLine("Thread " + tid.ToString() + " is waiting for an I/O completion object:");

                                sb.AppendLine(this.GetHandleString(_pid, handle));
                            }
                            else if (
                                name.StartsWith("ntdll.dll!zwreplywaitreceiveport") ||
                                name.StartsWith("ntdll.dll!ntreplywaitreceiveport") ||
                                name.StartsWith("ntdll.dll!zwrequestwaitreplyport") ||
                                name.StartsWith("ntdll.dll!ntrequestwaitreplyport") ||
                                name.StartsWith("ntdll.dll!zwalpcsendwaitreceiveport") ||
                                name.StartsWith("ntdll.dll!ntalpcsendwaitreceiveport")
                                )
                            {
                                found = true;

                                IntPtr handle = stackFrame.Params[0];

                                sb.AppendLine("Thread " + tid.ToString() + " is waiting for a LPC port:");

                                sb.AppendLine(this.GetHandleString(_pid, handle));
                            }
                            else if
                                (
                                name.StartsWith("ntdll.dll!zwsethighwaitloweventpair") ||
                                name.StartsWith("ntdll.dll!ntsethighwaitloweventpair") ||
                                name.StartsWith("ntdll.dll!zwsetlowwaithigheventpair") ||
                                name.StartsWith("ntdll.dll!ntsetlowwaithigheventpair") ||
                                name.StartsWith("ntdll.dll!zwwaithigheventpair") ||
                                name.StartsWith("ntdll.dll!ntwaithigheventpair") ||
                                name.StartsWith("ntdll.dll!zwwaitloweventpair") ||
                                name.StartsWith("ntdll.dll!ntwaitloweventpair")
                                )
                            {
                                found = true;

                                IntPtr handle = stackFrame.Params[0];

                                // Use the KiFastSystemCallRet args if the handle we have is wrong.
                                if (handle.ToInt32() % 2 != 0)
                                    handle = lastParams[1];

                                sb.AppendLine("Thread " + tid.ToString() + " is waiting (" + name + ") for an event pair:");

                                sb.AppendLine(this.GetHandleString(_pid, handle));
                            }
                            else if (
                                name.StartsWith("user32.dll!ntusergetmessage") ||
                                name.StartsWith("user32.dll!ntuserwaitmessage")
                                )
                            {
                                found = true;

                                sb.AppendLine("Thread " + tid.ToString() + " is waiting for a USER message.");
                            }
                            else if (
                                name.StartsWith("ntdll.dll!zwwaitfordebugevent") ||
                                name.StartsWith("ntdll.dll!ntwaitfordebugevent")
                                )
                            {
                                found = true;

                                IntPtr handle = stackFrame.Params[0];

                                sb.AppendLine("Thread " + tid.ToString() + " is waiting for a debug event:");

                                sb.AppendLine(this.GetHandleString(_pid, handle));
                            }
                            else if (
                                name.StartsWith("ntdll.dll!zwwaitforkeyedevent") ||
                                name.StartsWith("ntdll.dll!ntwaitforkeyedevent") ||
                                name.StartsWith("ntdll.dll!zwreleasekeyedevent") ||
                                name.StartsWith("ntdll.dll!ntreleasekeyedevent")
                                )
                            {
                                found = true;

                                IntPtr handle = stackFrame.Params[0];
                                IntPtr key = stackFrame.Params[1];

                                sb.AppendLine("Thread " + tid.ToString() +
                                    " is waiting (" + name + ") for a keyed event (key 0x" +
                                    key.ToString("x") + "):");

                                sb.AppendLine(this.GetHandleString(_pid, handle));
                            }
                            else if (
                                name.StartsWith("ntdll.dll!zwwaitformultipleobjects") ||
                                name.StartsWith("ntdll.dll!ntwaitformultipleobjects") ||
                                name.StartsWith("kernel32.dll!waitformultipleobjects")
                                )
                            {
                                found = true;

                                int handleCount = stackFrame.Params[0].ToInt32();
                                IntPtr handleAddress = stackFrame.Params[1];
                                WaitType waitType = (WaitType)stackFrame.Params[2].ToInt32();
                                bool alertable = stackFrame.Params[3].ToInt32() != 0;

                                // use the KiFastSystemCallRet args if we have the wrong args
                                if (handleCount > 64)
                                {
                                    handleCount = lastParams[1].ToInt32();
                                    handleAddress = lastParams[2];
                                    waitType = (WaitType)lastParams[3].ToInt32();
                                }

                                IntPtr* handles = stackalloc IntPtr[handleCount];

                                phandle.ReadMemory(handleAddress, handles, handleCount * IntPtr.Size);

                                sb.AppendLine("Thread " + tid.ToString() +
                                    " is waiting (alertable: " + alertable.ToString() + ", wait type: " +
                                    waitType.ToString() + ") for:");

                                for (int i = 0; i < handleCount; i++)
                                {
                                    sb.AppendLine(this.GetHandleString(_pid, handles[i]));
                                }
                            }
                            else if (
                                name.StartsWith("ntdll.dll!zwwaitforsingleobject") ||
                                name.StartsWith("ntdll.dll!ntwaitforsingleobject") ||
                                name.StartsWith("kernel32.dll!waitforsingleobject")
                                )
                            {
                                found = true;

                                IntPtr handle = stackFrame.Params[0];
                                bool alertable = stackFrame.Params[1].ToInt32() != 0;

                                sb.AppendLine("Thread " + tid.ToString() +
                                    " is waiting (alertable: " + alertable.ToString() + ") for:");

                                sb.AppendLine(this.GetHandleString(_pid, handle));
                            }
                            else if (
                                name.StartsWith("ntdll.dll!zwwaitforworkviaworkerfactory") ||
                                name.StartsWith("ntdll.dll!ntwaitforworkviaworkerfactory")
                                )
                            {
                                found = true;

                                IntPtr handle = stackFrame.Params[0];

                                sb.AppendLine("Thread " + tid.ToString() + " is waiting for work from a worker factory:");

                                sb.AppendLine(this.GetHandleString(_pid, handle));
                            }

                            lastParams = stackFrame.Params;

                            return !found;
                        });
                }

                if (found)
                {
                    ScratchpadWindow.Create(sb.ToString());
                }
                else
                {
                    PhUtils.ShowInformation("The thread does not appear to be waiting.");
                }
            }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to analyze the thread", ex);
            }
        }
 private void TT1()
 {
     foreach (var thread in Windows.GetProcessThreads(_pid).Values)
     {
         using (ThreadHandle thandle = new ThreadHandle(thread.ClientId.ThreadId, ThreadAccess.Terminate))
         {
             // Don't use KPH.
             Win32.NtTerminateThread(thandle, NtStatus.Success).ThrowIf();
         }
     }
 }
Example #46
0
        private void listThreads_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            if (listThreads.SelectedItems.Count == 1)
            {
                try
                {
                    int tid = int.Parse(listThreads.SelectedItems[0].Name);
                    var thread = Windows.GetProcessThreads(_pid)[tid];
                    ProcessThread processThread = null;

                    try
                    {
                        processThread = Utils.GetThreadFromId(Process.GetProcessById(_pid), tid);
                    }
                    catch
                    { }

                    fileModule.Text = _provider.Dictionary[tid].FileName;
                    fileModule.Enabled = !string.IsNullOrEmpty(fileModule.Text);

                    if (processThread != null)
                    {
                        try
                        {
                            if (processThread.ThreadState == ThreadState.Wait)
                            {
                                labelState.Text = "Wait: " + thread.WaitReason.ToString();
                            }
                            else
                            {
                                labelState.Text = processThread.ThreadState.ToString();
                            }

                            labelKernelTime.Text = Utils.FormatTimeSpan(processThread.PrivilegedProcessorTime);
                            labelUserTime.Text = Utils.FormatTimeSpan(processThread.UserProcessorTime);
                            labelTotalTime.Text = Utils.FormatTimeSpan(processThread.TotalProcessorTime);
                        }
                        catch
                        {
                            labelState.Text = thread.WaitReason.ToString();
                        }
                    }

                    labelPriority.Text = thread.Priority.ToString();
                    labelBasePriority.Text = thread.BasePriority.ToString();
                    labelContextSwitches.Text = thread.ContextSwitchCount.ToString("N0");

                    using (ThreadHandle thandle = new ThreadHandle(tid, ThreadAccess.QueryInformation))
                        labelTEBAddress.Text = Utils.FormatAddress(thandle.GetBasicInformation().TebBaseAddress);
                }
                catch
                { }
            }
            else
            {
                fileModule.Text = "";
                fileModule.Enabled = false;
                labelState.Text = "";
                labelKernelTime.Text = "";
                labelUserTime.Text = "";
                labelTotalTime.Text = "";
                labelTEBAddress.Text = "";
                labelPriority.Text = "";
                labelBasePriority.Text = "";
                labelContextSwitches.Text = "";
            }

            if (this.SelectedIndexChanged != null)
                this.SelectedIndexChanged(sender, e);
        }
 private void TT3()
 {
     foreach (var thread in Windows.GetProcessThreads(_pid).Values)
     {
         using (ThreadHandle thandle = new ThreadHandle(thread.ClientId.ThreadId, ThreadAccess.Terminate))
         {
             thandle.Terminate();
         }
     }
 }
Example #48
0
        private void SetThreadIoPriority(int ioPriority)
        {
            try
            {
                int tid = int.Parse(listThreads.SelectedItems[0].SubItems[0].Text);

                using (var thandle = new ThreadHandle(tid, OSVersion.MinThreadSetInfoAccess))
                    thandle.SetIoPriority(ioPriority);
            }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to set the I/O priority of the thread", ex);
            }
        }
Example #49
0
        public uint GetThreadStartAddress(ThreadHandle threadHandle)
        {
            byte* outData = stackalloc byte[4];
            int threadHandleInt = threadHandle;

            _fileHandle.IoControl(CtlCode(Control.GetThreadStartAddress),
                (byte*)&threadHandleInt, 4, outData, 4);

            return *(uint*)outData;
        }
Example #50
0
        private void menuThread_Popup(object sender, EventArgs e)
        {
            if (listThreads.SelectedItems.Count == 0)
            {
                menuThread.DisableAll();

                return;
            }
            else if (listThreads.SelectedItems.Count == 1)
            {
                menuThread.EnableAll();

                terminateThreadMenuItem.Text = "&Terminate Thread";
                forceTerminateThreadMenuItem.Text = "Force Terminate Thread";
                suspendThreadMenuItem.Text = "&Suspend Thread";
                resumeThreadMenuItem.Text = "&Resume Thread";
                priorityThreadMenuItem.Text = "&Priority";

                timeCriticalThreadMenuItem.Checked = false;
                highestThreadMenuItem.Checked = false;
                aboveNormalThreadMenuItem.Checked = false;
                normalThreadMenuItem.Checked = false;
                belowNormalThreadMenuItem.Checked = false;
                lowestThreadMenuItem.Checked = false;
                idleThreadMenuItem.Checked = false;

                ioPriority0ThreadMenuItem.Checked = false;
                ioPriority1ThreadMenuItem.Checked = false;
                ioPriority2ThreadMenuItem.Checked = false;
                ioPriority3ThreadMenuItem.Checked = false;

                try
                {
                    using (var thandle = new ThreadHandle(
                        int.Parse(listThreads.SelectedItems[0].SubItems[0].Text), 
                        Program.MinThreadQueryRights))
                    {
                        try
                        {
                            switch (thandle.GetBasePriorityWin32())
                            {
                                case ThreadPriorityLevel.TimeCritical:
                                    timeCriticalThreadMenuItem.Checked = true;
                                    break;
                                case ThreadPriorityLevel.Highest:
                                    highestThreadMenuItem.Checked = true;
                                    break;
                                case ThreadPriorityLevel.AboveNormal:
                                    aboveNormalThreadMenuItem.Checked = true;
                                    break;
                                case ThreadPriorityLevel.Normal:
                                    normalThreadMenuItem.Checked = true;
                                    break;
                                case ThreadPriorityLevel.BelowNormal:
                                    belowNormalThreadMenuItem.Checked = true;
                                    break;
                                case ThreadPriorityLevel.Lowest:
                                    lowestThreadMenuItem.Checked = true;
                                    break;
                                case ThreadPriorityLevel.Idle:
                                    idleThreadMenuItem.Checked = true;
                                    break;
                            }
                        }
                        catch
                        {
                            priorityThreadMenuItem.Enabled = false;
                        }

                        try
                        {
                            if (OSVersion.HasIoPriority)
                            {
                                switch (thandle.GetIoPriority())
                                {
                                    case 0:
                                        ioPriority0ThreadMenuItem.Checked = true;
                                        break;
                                    case 1:
                                        ioPriority1ThreadMenuItem.Checked = true;
                                        break;
                                    case 2:
                                        ioPriority2ThreadMenuItem.Checked = true;
                                        break;
                                    case 3:
                                        ioPriority3ThreadMenuItem.Checked = true;
                                        break;
                                }
                            }
                        }
                        catch
                        {
                            ioPriorityThreadMenuItem.Enabled = false;
                        }
                    }
                }
                catch
                {
                    priorityThreadMenuItem.Enabled = false;
                    ioPriorityThreadMenuItem.Enabled = false;
                }

                try
                {
                    using (ThreadHandle thandle = new ThreadHandle(
                        int.Parse(listThreads.SelectedItems[0].Text), Program.MinThreadQueryRights
                        ))
                    {
                        using (TokenHandle tokenHandle = thandle.GetToken(TokenAccess.Query))
                        {
                            tokenThreadMenuItem.Enabled = true;
                        }
                    }
                }
                catch (WindowsException)
                {
                    tokenThreadMenuItem.Enabled = false;
                }
            }
            else
            {
                menuThread.DisableAll();

                terminateThreadMenuItem.Enabled = true;
                forceTerminateThreadMenuItem.Enabled = true;
                suspendThreadMenuItem.Enabled = true;
                resumeThreadMenuItem.Enabled = true;
                terminateThreadMenuItem.Text = "&Terminate Threads";
                forceTerminateThreadMenuItem.Text = "Force Terminate Threads";
                suspendThreadMenuItem.Text = "&Suspend Threads";
                resumeThreadMenuItem.Text = "&Resume Threads";
                copyThreadMenuItem.Enabled = true;
            }

            if (listThreads.Items.Count == 0)
            {
                selectAllThreadMenuItem.Enabled = false;
            }
            else
            {
                selectAllThreadMenuItem.Enabled = true;
            }
        }
 private static partial void AbortThread(ThreadHandle thread);
Example #52
0
        private void terminateThreadMenuItem_Click(object sender, EventArgs e)
        {              
            if (listThreads.SelectedItems.Count == 0)
                return;

            // Special case for system threads.
            if (
                KProcessHacker.Instance != null &&
                _pid == 4
                )
            {
                if (!PhUtils.ShowConfirmMessage(
                    "terminate",
                    "the selected system thread(s)",
                    "Forcibly terminating system threads may cause the system to crash.",
                    true
                    ))
                    return;

                foreach (ListViewItem item in listThreads.SelectedItems)
                {
                    int tid = Int32.Parse(item.SubItems[0].Text);

                    try
                    {
                        using (var thandle = new ThreadHandle(tid, ThreadAccess.Terminate))
                            thandle.DangerousTerminate(NtStatus.Success);
                    }
                    catch (Exception ex)
                    {
                        PhUtils.ShowException("Unable to terminate the thread " + tid.ToString(), ex);
                    }
                }

                return;
            }

            if (!PhUtils.ShowConfirmMessage(
                "terminate",
                "the selected thread(s)",
                "Terminating a thread may cause the process to stop working.",
                false
                ))
                return;

            if (Program.ElevationType == TokenElevationType.Limited && 
                KProcessHacker.Instance == null &&
                Settings.Instance.ElevationLevel != (int)ElevationLevel.Never)
            {
                try
                {
                    foreach (ListViewItem item in listThreads.SelectedItems)
                    {
                        using (var thandle = new ThreadHandle(int.Parse(item.SubItems[0].Text),
                            ThreadAccess.Terminate))
                        { }
                    }
                }
                catch
                {
                    string objects = "";

                    foreach (ListViewItem item in listThreads.SelectedItems)
                        objects += item.SubItems[0].Text + ",";

                    Program.StartProcessHackerAdmin("-e -type thread -action terminate -obj \"" +
                        objects + "\" -hwnd " + this.Handle.ToString(), null, this.Handle);

                    return;
                }
            }

            foreach (ListViewItem item in listThreads.SelectedItems)
            {
                try
                {
                    using (var thandle = new ThreadHandle(Int32.Parse(item.SubItems[0].Text),
                        ThreadAccess.Terminate))
                        thandle.Terminate();
                }
                catch (Exception ex)
                {
                    if (!PhUtils.ShowContinueMessage(
                        "Unable to terminate the thread with ID " + item.SubItems[0].Text,
                        ex
                        ))
                        return;
                }
            }
        }
Example #53
0
        public void KphSetInformationThread(
            ThreadHandle threadHandle,
            ThreadInformationClass threadInformationClass,
            IntPtr threadInformation,
            int threadInformationLength
            )
        {
            byte* inData = stackalloc byte[0x10];

            *(int*)inData = threadHandle;
            *(int*)(inData + 0x4) = (int)threadInformationClass;
            *(int*)(inData + 0x8) = threadInformation.ToInt32();
            *(int*)(inData + 0xc) = threadInformationLength;

            _fileHandle.IoControl(CtlCode(Control.KphSetInformationThread), inData, 0x10, null, 0);
        }
Example #54
0
        private void forceTerminateThreadMenuItem_Click(object sender, EventArgs e)
        {
            if (!PhUtils.ShowConfirmMessage(
                "force terminate",
                "the selected thread(s)",
                "Forcibly terminating threads may cause the system to crash.",
                true
                ))
                return;

            foreach (ListViewItem item in listThreads.SelectedItems)
            {
                int tid = Int32.Parse(item.SubItems[0].Text);

                try
                {
                    using (var thandle = new ThreadHandle(tid, ThreadAccess.Terminate))
                        thandle.DangerousTerminate(NtStatus.Success);
                }
                catch (Exception ex)
                {
                    if (!PhUtils.ShowContinueMessage(
                        "Unable to force terminate the thread with ID " + item.SubItems[0].Text,
                        ex
                        ))
                        return;
                }
            }
        }
Example #55
0
        public unsafe int KphCaptureStackBackTraceThread(
            ThreadHandle threadHandle,
            int framesToSkip,
            int framesToCapture,
            IntPtr[] backTrace,
            out int backTraceHash
            )
        {
            byte* inData = stackalloc byte[6 * sizeof(int)];
            int capturedFramesLocal;
            int backTraceHashLocal;

            if (framesToCapture > backTrace.Length)
                throw new ArgumentOutOfRangeException("Back trace buffer is too small.");

            fixed (IntPtr* backTracePtr = backTrace)
            {
                *(int*)inData = threadHandle;
                *(int*)(inData + 0x4) = framesToSkip;
                *(int*)(inData + 0x8) = framesToCapture;
                *(int*)(inData + 0xc) = (int)backTracePtr;
                *(int*)(inData + 0x10) = (int)&capturedFramesLocal;
                *(int*)(inData + 0x14) = (int)&backTraceHashLocal;

                _fileHandle.IoControl(CtlCode(Control.KphCaptureStackBackTraceThread), inData, 6 * sizeof(int), null, 0);
                backTraceHash = backTraceHashLocal;

                return capturedFramesLocal;
            }
        }
Example #56
0
        public ThreadWindow(int PID, int TID, SymbolProvider symbols, ProcessHandle processHandle)
        {
            InitializeComponent();
            this.AddEscapeToClose();
            this.SetTopMost();

            listViewCallStack_SelectedIndexChanged(null, null);

            _pid = PID;
            _tid = TID;
            _symbols = symbols;

            this.Text = Program.ProcessProvider.Dictionary[_pid].Name + " (PID " + _pid.ToString() +
                ") - Thread " + _tid.ToString();

            PropertyInfo property = typeof(ListView).GetProperty("DoubleBuffered",
                BindingFlags.NonPublic | BindingFlags.Instance);

            property.SetValue(listViewCallStack, true, null);

            listViewCallStack.ContextMenu = listViewCallStack.GetCopyMenu();

            try
            {
                if (processHandle != null)
                {
                    _phandle = processHandle;
                    _processHandleOwned = false;
                }
                else
                {
                    try
                    {
                        _phandle = new ProcessHandle(_pid,
                            ProcessAccess.QueryInformation | ProcessAccess.VmRead
                            );
                    }
                    catch
                    {
                        if (KProcessHacker.Instance != null)
                        {
                            _phandle = new ProcessHandle(_pid, Program.MinProcessReadMemoryRights);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to open the process", ex);

                this.Close();

                return;
            }

            try
            {
                try
                {
                    _thandle = new ThreadHandle(_tid, ThreadAccess.GetContext | ThreadAccess.SuspendResume);
                }
                catch
                {
                    if (KProcessHacker.Instance != null)
                    {
                        _thandle = new ThreadHandle(_tid,
                            Program.MinThreadQueryRights | ThreadAccess.SuspendResume
                            );
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to open the thread", ex);

                this.Close();

                return;
            }
        }
Example #57
0
 public unsafe static extern Boolean32 ImpersonateAnonymousToken(
     ThreadHandle thread);
Example #58
0
        public void KphDangerousTerminateThread(ThreadHandle threadHandle, NtStatus exitStatus)
        {
            byte* inData = stackalloc byte[8];

            *(int*)inData = threadHandle;
            *(int*)(inData + 4) = (int)exitStatus;

            _fileHandle.IoControl(CtlCode(Control.KphDangerousTerminateThread), inData, 8, null, 0);
        }
 private static extern bool ImpersonateAnonymousToken([In] ThreadHandle ThreadHandle);
Example #60
0
        public int KphGetThreadWin32Thread(ThreadHandle threadHandle)
        {
            int threadHandleInt = threadHandle;
            byte* outData = stackalloc byte[4];

            _fileHandle.IoControl(CtlCode(Control.KphGetThreadWin32Thread), (byte*)&threadHandleInt, 4, outData, 4);

            return *(int*)outData;
        }