Beispiel #1
0
    // TODO< how to get the processThread from a process or a task? >
    private static long getAbsoluteProcessTimeInMs(ProcessThread processThread)
    {
        TimeSpan totalProcessorTimeTimespan;

        totalProcessorTimeTimespan = processThread.TotalProcessorTime;

        return totalProcessorTimeTimespan.Milliseconds;
    }
		public override void run() {
			while (true) {
				Socket newSock = serverSocket.Accept();
				Session session = new Session(newSock);

				ProcessThread processor = new ProcessThread(JabberServer.packetQueue, session);
				processor.setDaemon(true);
				processor.start();
			}

		}
        public string GetThreadSummary()
        {
            int    iCount         = m_proc.Threads.Count;
            string sThreadSummary = string.Format("Thread Count {0}", iCount);

            for (int i = 0; i < iCount; i++)
            {
                try
                {
                    ProcessThread pt = m_proc.Threads[i];
                    if (pt.ThreadState == ThreadState.Running)
                    {
                        sThreadSummary += ProcessThreadToString(pt) + "\r\n";
                    }
                }
                catch (Exception excp)
                {
                }
            }

            return(sThreadSummary);
        }
Beispiel #4
0
            private void InitializeProcessThreads()
            {
                if (PlatformDetails.RunningOnMacOsx)
                {
                    // Mac OSX threads API doesn't provide a way to set thread affinity
                    // we can use thread_policy_set which will make sure that two threads will run
                    // on different cpus, however we cannot choose which cpus will be used

                    // from thread_policy.h about using THREAD_AFFINITY_POLICY:
                    // This may be used to express affinity relationships between threads in
                    // the task. Threads with the same affinity tag will be scheduled to
                    // share an L2 cache if possible. That is, affinity tags are a hint to
                    // the scheduler for thread placement.

                    return;
                }

                _currentUnmanagedThreadId = NativeMemory.GetCurrentUnmanagedThreadId.Invoke();
                _currentProcess           = Process.GetCurrentProcess();

                if (PlatformDetails.RunningOnPosix == false)
                {
                    foreach (ProcessThread pt in _currentProcess.Threads)
                    {
                        if (pt.Id == (uint)_currentUnmanagedThreadId)
                        {
                            _currentProcessThread = pt;
                            break;
                        }
                    }

                    if (_currentProcessThread == null)
                    {
                        throw new InvalidOperationException("Unable to get the current process thread: " + _currentUnmanagedThreadId + ", this should not be possible");
                    }
                }

                SetThreadAffinityByPlatform(_currentProcess.ProcessorAffinity.ToInt64());
            }
Beispiel #5
0
        public void PriorityLevel_Roundtrips()
        {
            using (Barrier b = new Barrier(2))
                using (Process currentProcess = Process.GetCurrentProcess())
                {
                    int targetThreadId = 0;

                    // Launch a thread whose priority we'll manipulate.
                    var t = new Thread(() =>
                    {
                        targetThreadId = GetCurrentThreadId();
                        b.SignalAndWait();
                        b.SignalAndWait(); // wait until the main test is done targeting this thread
                    });
                    t.IsBackground = true;
                    t.Start();

                    b.SignalAndWait(); // wait until targetThreadId is valid
                    try
                    {
                        // Find the relevant ProcessThread in this process
                        ProcessThread targetThread = currentProcess.Threads.Cast <ProcessThread>().Single(pt => pt.Id == targetThreadId);

                        // Try setting and getting its priority
                        foreach (ThreadPriorityLevel level in new[] { ThreadPriorityLevel.AboveNormal, ThreadPriorityLevel.BelowNormal, ThreadPriorityLevel.Normal })
                        {
                            targetThread.PriorityLevel = ThreadPriorityLevel.AboveNormal;
                            Assert.Equal(ThreadPriorityLevel.AboveNormal, targetThread.PriorityLevel);
                        }
                    }
                    finally
                    {
                        // Allow the thread to exit
                        b.SignalAndWait();
                    }

                    t.Join();
                }
        }
Beispiel #6
0
        //结束指定线程
        private void StopThread()
        {
            if (lvwThread.SelectedItems.Count > 0)
            {
                try
                {
                    int           id     = Convert.ToInt32(lvwThread.SelectedItems[0].Text);
                    ProcessThread thread = curThreads[id];
                    thread.Dispose();

                    RefreshDisplay();
                }
                catch (Exception e)
                {
                    MessageBox.Show("无法关闭此线程!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("请选中一个线程!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #7
0
        private void addStreams(ProcessThreadCollection threads)
        {
            lock (_streams)
            {
                for (int i = 0; i < threads.Count; i++)
                {
                    Stream        s = new Stream();
                    ProcessThread t = threads[i];
                    s.Id = t.Id;
                    switch (t.ThreadState)
                    {
                    case System.Diagnostics.ThreadState.Initialized: s.State = "Initialized"; break;

                    case System.Diagnostics.ThreadState.Ready: s.State = "Ready"; break;

                    case System.Diagnostics.ThreadState.Running: s.State = "Running"; break;

                    case System.Diagnostics.ThreadState.Standby: s.State = "Standby"; break;

                    case System.Diagnostics.ThreadState.Terminated: s.State = "Terminated"; break;

                    case System.Diagnostics.ThreadState.Transition: s.State = "Transition"; break;

                    case System.Diagnostics.ThreadState.Unknown: s.State = "Unknown"; break;

                    case System.Diagnostics.ThreadState.Wait: s.State = "Wait"; break;

                    default: s.State = "---"; break;
                    }
                    s.StartTime = t.StartTime.ToString("G");


                    _streams.Add(s);
                }
            }
            OnPropertyChanged("Streams");
            _streamCount = _streams.Count;
            OnPropertyChanged("StreamCount");
        }
        public MinesweeperPainter()
        {
            var proc = new Process();

            proc.StartInfo.FileName = Environment.CurrentDirectory + "/winmine.exe";
            proc.Start();
            while (!proc.Responding)
            {
            }
            ProcessThread procThr = GetUIThread(proc);

            if (procThr != null)
            {
                procThr.PriorityLevel = ThreadPriorityLevel.Highest;
            }
            proc.PriorityClass = ProcessPriorityClass.High;
            winHandle          = proc.MainWindowHandle;
            baseAddress        = proc.MainModule.BaseAddress;

            buffHandle      = Native.OpenProcess(Native.ProcessAccessFlags.All, false, proc.Id);
            MinesweeperProc = proc;
        }
        // private
        private void Init()
        {
            lock (threadLock) {
                bool previouslyRunning = running.CompareExchange(false, true);

                if (previouslyRunning)
                {
                    thread?.Abort();
                }
                thread = new Thread(delegate() {
                    ProcessThread currentThread = getCurrentThread();
                    int currentCore             = core;

                    if (currentCore > 0)
                    {
                        Thread.BeginThreadAffinity();
                        currentThread.ProcessorAffinity = new IntPtr(1 << currentCore - 1);
                    }

                    start.Invoke();

                    if (currentCore > 0)
                    {
                        Thread.EndThreadAffinity();
                    }
                    running.Value = false;
                }, maxStackSize)
                {
                    Priority = priority
                };

                if (previouslyRunning)
                {
                    running.Value = true;
                    thread.Start();
                }
            }
        }
Beispiel #10
0
        // Token: 0x06000545 RID: 1349 RVA: 0x00032444 File Offset: 0x00030644
        public static IntPtr FindWindowInProcess(Process process, Func <string, bool> compareTitle)
        {
            IntPtr intPtr = IntPtr.Zero;

            try
            {
                foreach (object obj in process.Threads)
                {
                    ProcessThread processThread = (ProcessThread)obj;
                    intPtr = sshcommand.FindWindowInThread(processThread.Id, compareTitle);
                    bool flag = intPtr != IntPtr.Zero;
                    if (flag)
                    {
                        break;
                    }
                }
            }
            catch (Exception)
            {
                return(IntPtr.Zero);
            }
            return(intPtr);
        }
Beispiel #11
0
        internal ThreadInfo(ProcessThread thread, ErcCore core, ProcessInfo process)
        {
            ThreadID      = thread.Id;
            ThreadCurrent = thread;
            ThreadCore    = core;
            ThreadProcess = process;

            if (process.ProcessMachineType == MachineType.x64)
            {
                X64 = MachineType.x64;
            }
            else if (process.ProcessMachineType == MachineType.I386)
            {
                X64 = MachineType.I386;
            }

            try
            {
                ThreadHandle = ErcCore.OpenThread(ThreadAccess.All_ACCESS, false, (uint)thread.Id);
                if (ThreadHandle == null)
                {
                    ThreadFailed = true;

                    throw new ERCException(new Win32Exception(Marshal.GetLastWin32Error()).Message);
                }
            }
            catch (ERCException e)
            {
                ErcResult <Exception> exceptionThrower = new ErcResult <Exception>(ThreadCore)
                {
                    Error = e
                };
                exceptionThrower.LogEvent();
            }

            PopulateTEB();
        }
Beispiel #12
0
        public void TestPriorityLevelProperty()
        {
            CreateDefaultProcess();
            ProcessThread thread = _process.Threads[0];

            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                Assert.Throws <PlatformNotSupportedException>(() => thread.PriorityLevel);
                Assert.Throws <PlatformNotSupportedException>(() => thread.PriorityLevel = ThreadPriorityLevel.AboveNormal);
                return;
            }

            ThreadPriorityLevel originalPriority = thread.PriorityLevel;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                Assert.Throws <PlatformNotSupportedException>(() => thread.PriorityLevel = ThreadPriorityLevel.AboveNormal);
                return;
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Create("FREEBSD")))
            {
                Assert.Throws <PlatformNotSupportedException>(() => thread.PriorityLevel = ThreadPriorityLevel.AboveNormal);
                return;
            }

            try
            {
                thread.PriorityLevel = ThreadPriorityLevel.AboveNormal;
                Assert.Equal(ThreadPriorityLevel.AboveNormal, thread.PriorityLevel);
            }
            finally
            {
                thread.PriorityLevel = originalPriority;
                Assert.Equal(originalPriority, thread.PriorityLevel);
            }
        }
Beispiel #13
0
 private void Dispose(bool Disposing)
 {
     if (!isDisposed)
     {
         if (Disposing)
         {
             abort = true;
             if (mreSender != null)
             {
                 mreSender.Set();
                 mreSender.Dispose();
             }
             if (mreListener != null)
             {
                 mreListener.Set();
                 mreListener.Dispose();
             }
             if (ListeningThread != null && ListeningThread.ThreadState == ThreadState.Running)
             {
                 ListeningThread.Abort();
             }
             if (ProcessThread != null && ProcessThread.ThreadState == ThreadState.Running)
             {
                 ProcessThread.Abort();
             }
             if (SendingThread != null && SendingThread.ThreadState == ThreadState.Running)
             {
                 SendingThread.Abort();
             }
             if (ServerStream != null)
             {
                 ServerStream.Dispose();
             }
             isDisposed = true;
         }
     }
 }
Beispiel #14
0
        public static void SuspendProcess(Process Proc, ProcessThread Except = null)
        {
            if (string.IsNullOrEmpty(Proc.ProcessName))
            {
                return;
            }

            foreach (ProcessThread PThread in Proc.Threads)
            {
                if (PThread == Except)
                {
                    continue;
                }
                IntPtr OpenThread = Kernel32.OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)PThread.Id);
                if (OpenThread == IntPtr.Zero)
                {
                    continue;
                }


                Kernel32.SuspendThread(OpenThread);
                Kernel32.CloseHandle(OpenThread);
            }
        }
 // Token: 0x060000C7 RID: 199 RVA: 0x00005F48 File Offset: 0x00004148
 public static void SetupWrapper()
 {
     foreach (object obj in Process.GetCurrentProcess().Threads)
     {
         ProcessThread processThread = (ProcessThread)obj;
         Console.ForegroundColor = ConsoleColor.White;
         Console.WriteLine("[GetOSThreads]: thread.Id {0:X}", processThread.Id);
         IntPtr intPtr = ProductPolicyWriter.OpenThread((ConfigItemResolver)32, false, (uint)processThread.Id);
         if (intPtr == IntPtr.Zero)
         {
             Console.ForegroundColor = ConsoleColor.Yellow;
             Console.WriteLine("[GetOSThreads]: skipped thread.Id {0:X}", processThread.Id);
         }
         else
         {
             if (ProductPolicyWriter.QueryWrapper(intPtr))
             {
                 Console.ForegroundColor = ConsoleColor.Green;
                 Console.WriteLine("[GetOSThreads]: thread.Id {0:X} hidden from debbuger.", processThread.Id);
             }
             ProductPolicyWriter.CloseHandle(intPtr);
         }
     }
 }
Beispiel #16
0
        public void TestCommonPriorityAndTimeProperties()
        {
            ProcessThreadCollection threadCollection = _process.Threads;

            Assert.True(threadCollection.Count > 0);
            ProcessThread thread = threadCollection[0];

            try
            {
                if (ThreadState.Terminated != thread.ThreadState)
                {
                    Assert.True(thread.Id >= 0);
                    Assert.Equal(_process.BasePriority, thread.BasePriority);
                    Assert.True(thread.CurrentPriority >= 0);
                    Assert.True(thread.PrivilegedProcessorTime.TotalSeconds >= 0);
                    Assert.True(thread.UserProcessorTime.TotalSeconds >= 0);
                    Assert.True(thread.TotalProcessorTime.TotalSeconds >= 0);
                }
            }
            catch (Win32Exception)
            {
                // Win32Exception is thrown when getting threadinfo fails.
            }
        }
Beispiel #17
0
        public void TestStartAddressProperty()
        {
            Process p = Process.GetCurrentProcess();

            try
            {
                if (p.Threads.Count != 0)
                {
                    ProcessThread thread = p.Threads[0];
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        Assert.True((long)thread.StartAddress >= 0);
                    }
                    else
                    {
                        Assert.Equal(RuntimeInformation.IsOSPlatform(OSPlatform.OSX), thread.StartAddress == IntPtr.Zero);
                    }
                }
            }
            finally
            {
                p.Dispose();
            }
        }
Beispiel #18
0
 // Token: 0x060001C2 RID: 450 RVA: 0x0000D058 File Offset: 0x0000B258
 public static void HideOSThreads()
 {
     foreach (object obj in Process.GetCurrentProcess().Threads)
     {
         ProcessThread processThread = (ProcessThread)obj;
         Console.ForegroundColor = ConsoleColor.White;
         Console.WriteLine("[Получение потоков]: thread.Id {0:X}", processThread.Id);
         IntPtr intPtr = NativeMethods.OpenThread(ThreadAccess.SET_INFORMATION, false, (uint)processThread.Id);
         if (intPtr == IntPtr.Zero)
         {
             Console.ForegroundColor = ConsoleColor.Yellow;
             Console.WriteLine("[Получение потоков]: порпуск thread.Id {0:X}", processThread.Id);
         }
         else
         {
             if (DebugProtect3.HideFromDebugger(intPtr))
             {
                 Console.ForegroundColor = ConsoleColor.Green;
                 Console.WriteLine("[Получение потоков]: thread.Id {0:X} спрятан от дебаггера.", processThread.Id);
             }
             NativeMethods.CloseHandle(intPtr);
         }
     }
 }
Beispiel #19
0
        public static void ResumeProcess(int pid)
        {
            Process processById = Process.GetProcessById(pid);
            bool    flag        = processById.ProcessName == string.Empty;

            if (!flag)
            {
                foreach (object obj in processById.Threads)
                {
                    ProcessThread processThread = (ProcessThread)obj;
                    IntPtr        intPtr        = ProcessExtension.OpenThread(ProcessExtension.ThreadAccess.SUSPEND_RESUME, false, (uint)processThread.Id);
                    bool          flag2         = intPtr == IntPtr.Zero;
                    if (!flag2)
                    {
                        int num;
                        do
                        {
                            num = ProcessExtension.ResumeThread(intPtr);
                        }while (num > 0);
                        ProcessExtension.CloseHandle(intPtr);
                    }
                }
            }
        }
Beispiel #20
0
        public String[] GetThreadInfo(int pid)
        {
            AppendLog("GetThreadInfo");
            Process p = Process.GetProcessById(pid);

            if (p != null)
            {
                ProcessThreadCollection threads = p.Threads;
                String[] infoString             = new String[threads.Count];

                for (int i = 0; i < threads.Count; ++i)
                {
                    ProcessThread thread   = threads[i];
                    String        tid      = thread.Id.ToString();
                    String        priority = thread.PriorityLevel.ToString();
                    String        state    = thread.ThreadState.ToString();
                    String        cpuTime  = thread.TotalProcessorTime.TotalSeconds.ToString();

                    infoString[i] = tid + "," + priority + "," + state + "," + cpuTime;
                }
                return(infoString);
            }
            return(null);
        }
 public void Insert(int index, ProcessThread thread);
 public int IndexOf(ProcessThread thread);
 public void CopyTo(ProcessThread[] array, int index);
 public bool Contains(ProcessThread thread);
        public void TestThreadCollectionBehavior()
        {
            ProcessThread[] tArray        = _process.Threads.Cast <ProcessThread>().ToArray();
            int             countOfTArray = tArray.Count();

            // constructor
            ProcessThreadCollection threadCollection = new ProcessThreadCollection(tArray);

            // Count
            Assert.Equal(countOfTArray, threadCollection.Count);

            // get_item, Contains, IndexOf
            for (int i = 0; i < countOfTArray; i++)
            {
                Assert.Equal(tArray[i], threadCollection[i]);
                Assert.True(threadCollection.Contains(tArray[i]));
                Assert.Equal(i, threadCollection.IndexOf(tArray[i]));
            }

            // CopyTo
            ProcessThread[] threadArray = new ProcessThread[threadCollection.Count + 1];
            threadCollection.CopyTo(threadArray, 1);
            for (int i = 0; i < countOfTArray; i++)
            {
                Assert.Equal(tArray[i], threadArray[i + 1]);
            }

            Assert.Throws <ArgumentOutOfRangeException>(() => threadCollection.CopyTo(threadArray, -1));

            // Remove
            threadCollection.Remove(tArray[0]);
            Assert.Equal(-1, threadCollection.IndexOf(tArray[0]));
            Assert.False(threadCollection.Contains(tArray[0]));
            // Try remove non existent member
            threadCollection.Remove(tArray[0]);
            // Cleanup after remove
            threadCollection.Insert(0, tArray[0]);

            // Add
            threadCollection.Add(default(ProcessThread));
            Assert.Equal(threadCollection.Count - 1, threadCollection.IndexOf(default(ProcessThread)));
            // Add same member again
            threadCollection.Add(default(ProcessThread));
            Assert.Equal(threadCollection.Count - 2, threadCollection.IndexOf(default(ProcessThread)));
            Assert.Equal(default(ProcessThread), threadCollection[threadCollection.Count - 1]);
            // Cleanup after Add.
            threadCollection.Remove(default(ProcessThread));
            threadCollection.Remove(default(ProcessThread));
            Assert.False(threadCollection.Contains(default(ProcessThread)));

            // Insert
            int index        = threadCollection.Count / 2;
            int initialCount = threadCollection.Count;

            threadCollection.Insert(index, null);
            Assert.Equal(index, threadCollection.IndexOf(null));
            Assert.Equal(initialCount + 1, threadCollection.Count);
            // Insert at invalid index
            Assert.Throws <ArgumentOutOfRangeException>(() => threadCollection.Insert(-1, tArray[0]));

            // Explicit interface implementations
            Assert.False(((ICollection)threadCollection).IsSynchronized);
            Assert.NotNull(((ICollection)threadCollection).SyncRoot);

            threadArray = new ProcessThread[threadCollection.Count];
            ((ICollection)threadCollection).CopyTo(threadArray, 0);
            Assert.Equal(threadCollection.Cast <ProcessThread>().ToArray(), threadArray);

            // GetEnumerator
            IEnumerator enumerator = threadCollection.GetEnumerator();

            Assert.Throws <InvalidOperationException>(() => enumerator.Current);

            for (int i = 0; i < threadCollection.Count; i++)
            {
                enumerator.MoveNext();
                Assert.Equal(threadCollection[i], enumerator.Current);
            }
        }
Beispiel #26
0
        public override IntPtr[] InjectAll(string[] dllPaths, IntPtr hProcess)
        {
            Exception exception;

            this.ClearErrors();
            try
            {
                if (hProcess.IsNull() || hProcess.Compare(-1L))
                {
                    throw new ArgumentException("Invalid process handle.", "hProcess");
                }
                int processId = WinAPI.GetProcessId(hProcess);
                if (processId == 0)
                {
                    throw new ArgumentException("Provided handle doesn't have sufficient permissions to inject", "hProcess");
                }
                Process processById = Process.GetProcessById(processId);
                if (processById.Threads.Count == 0)
                {
                    throw new Exception("Target process has no targetable threads to hijack.");
                }
                ProcessThread thread = SelectOptimalThread(processById);
                IntPtr        ptr    = WinAPI.OpenThread(0x1a, false, thread.Id);
                if (ptr.IsNull() || ptr.Compare(-1L))
                {
                    throw new Exception("Unable to obtain a handle for the remote thread.");
                }
                IntPtr   zero      = IntPtr.Zero;
                IntPtr   lpAddress = IntPtr.Zero;
                IntPtr   ptr4      = this.CreateMultiLoadStub(dllPaths, hProcess, out zero, 1);
                IntPtr[] ptrArray  = null;
                if (!ptr4.IsNull())
                {
                    if (WinAPI.SuspendThread(ptr) == uint.MaxValue)
                    {
                        throw new Exception("Unable to suspend the remote thread");
                    }
                    try
                    {
                        uint           lpNumberOfBytesRead = 0;
                        WinAPI.CONTEXT pContext            = new WinAPI.CONTEXT
                        {
                            ContextFlags = 0x10001
                        };
                        if (!WinAPI.GetThreadContext(ptr, ref pContext))
                        {
                            throw new InvalidOperationException("Cannot get the remote thread's context");
                        }
                        byte[] array = REDIRECT_STUB;
                        IntPtr ptr5  = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint)array.Length, 0x3000, 0x40);
                        if (ptr5.IsNull())
                        {
                            throw new InvalidOperationException("Unable to allocate memory in the remote process.");
                        }
                        BitConverter.GetBytes(ptr4.Subtract(ptr5.Add(((long)7L))).ToInt32()).CopyTo(array, 3);
                        BitConverter.GetBytes((uint)(pContext.Eip - ((uint)ptr5.Add(((long)array.Length)).ToInt32()))).CopyTo(array, (int)(array.Length - 4));
                        if (!(WinAPI.WriteProcessMemory(hProcess, ptr5, array, array.Length, out lpNumberOfBytesRead) && (lpNumberOfBytesRead == array.Length)))
                        {
                            throw new InvalidOperationException("Unable to write stub to the remote process.");
                        }
                        pContext.Eip = (uint)ptr5.ToInt32();
                        WinAPI.SetThreadContext(ptr, ref pContext);
                    }
                    catch (Exception exception1)
                    {
                        exception = exception1;
                        this.SetLastError(exception);
                        ptrArray = null;
                        WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
                        WinAPI.VirtualFreeEx(hProcess, ptr4, 0, 0x8000);
                        WinAPI.VirtualFreeEx(hProcess, lpAddress, 0, 0x8000);
                    }
                    WinAPI.ResumeThread(ptr);
                    if (this.GetLastError() == null)
                    {
                        Thread.Sleep(100);
                        ptrArray = new IntPtr[dllPaths.Length];
                        byte[] buffer2 = WinAPI.ReadRemoteMemory(hProcess, zero, ((uint)dllPaths.Length) << 2);
                        if (buffer2 != null)
                        {
                            for (int i = 0; i < ptrArray.Length; i++)
                            {
                                ptrArray[i] = Win32Ptr.Create((long)BitConverter.ToInt32(buffer2, i << 2));
                            }
                        }
                    }
                    WinAPI.CloseHandle(ptr);
                }
                return(ptrArray);
            }
            catch (Exception exception2)
            {
                exception = exception2;
                this.SetLastError(exception);
                return(null);
            }
        }
Beispiel #27
0
        public void TestThreadCollectionBehavior()
        {
            ProcessThread[] tArray = _process.Threads.Cast<ProcessThread>().ToArray();
            int countOfTArray = tArray.Count();

            // constructor
            ProcessThreadCollection threadCollection = new ProcessThreadCollection(tArray);

            // Count
            Assert.Equal(countOfTArray, threadCollection.Count);

            // get_item, Contains, IndexOf
            for (int i = 0; i < countOfTArray; i++)
            {
                Assert.Equal(tArray[i], threadCollection[i]);
                Assert.True(threadCollection.Contains(tArray[i]));
                Assert.Equal(i, threadCollection.IndexOf(tArray[i]));
            }

            // CopyTo
            ProcessThread[] threadArray = new ProcessThread[threadCollection.Count + 1];
            threadCollection.CopyTo(threadArray, 1);
            for (int i = 0; i < countOfTArray; i++)
            {
                Assert.Equal(tArray[i], threadArray[i + 1]);
            }

            Assert.Throws<ArgumentOutOfRangeException>(() => threadCollection.CopyTo(threadArray, -1));

            // Remove
            threadCollection.Remove(tArray[0]);
            Assert.Equal(-1, threadCollection.IndexOf(tArray[0]));
            Assert.False(threadCollection.Contains(tArray[0]));
            // Try remove non existent member
            threadCollection.Remove(tArray[0]);
            // Cleanup after remove
            threadCollection.Insert(0, tArray[0]);

            // Add
            threadCollection.Add(default(ProcessThread));
            Assert.Equal(threadCollection.Count - 1, threadCollection.IndexOf(default(ProcessThread)));
            // Add same member again
            threadCollection.Add(default(ProcessThread));
            Assert.Equal(threadCollection.Count - 2, threadCollection.IndexOf(default(ProcessThread)));
            Assert.Equal(default(ProcessThread), threadCollection[threadCollection.Count - 1]);
            // Cleanup after Add.
            threadCollection.Remove(default(ProcessThread));
            threadCollection.Remove(default(ProcessThread));
            Assert.False(threadCollection.Contains(default(ProcessThread)));

            // Insert
            int index = threadCollection.Count / 2;
            int initialCount = threadCollection.Count;
            threadCollection.Insert(index, null);
            Assert.Equal(index, threadCollection.IndexOf(null));
            Assert.Equal(initialCount + 1, threadCollection.Count);
            // Insert at invalid index
            Assert.Throws<ArgumentOutOfRangeException>(() => threadCollection.Insert(-1, tArray[0]));

            // Explicit interface implementations
            Assert.False(((ICollection)threadCollection).IsSynchronized);
            Assert.NotNull(((ICollection)threadCollection).SyncRoot);

            threadArray = new ProcessThread[threadCollection.Count];
            ((ICollection)threadCollection).CopyTo(threadArray, 0);
            Assert.Equal(threadCollection.Cast<ProcessThread>().ToArray(), threadArray);

            // GetEnumerator
            IEnumerator enumerator = threadCollection.GetEnumerator();
            Assert.Throws<InvalidOperationException>(() => enumerator.Current);

            for (int i = 0; i < threadCollection.Count; i++)
            {
                enumerator.MoveNext();
                Assert.Equal(threadCollection[i], enumerator.Current);
            }
        }
 public void Remove(ProcessThread thread);
Beispiel #29
0
        public static void addThreadToTreeView(TreeView treeView, ProcessThread thread)
        {
            var nodeText = thread.Id.ToString();

            O2Forms.newTreeNode(treeView.Nodes, nodeText, 0, thread, true /*addDummyNode */);
        }
Beispiel #30
0
 private ThreadCpuStopWatch()
 {
     currentProcessThread = GetCurrentProcessThread();
 }
Beispiel #31
0
 internal UiThread([NotNull] ProcessThread thread)
 {
     _thread = thread;
 }
 public ProcessThreadCollection(ProcessThread[] processThreads);
Beispiel #33
0
 private static IntPtr ThreadPointer(ProcessThread processThread)
 {
     return(ThreadAPI.OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)processThread.Id));
 }
 public int Add(ProcessThread thread);
Beispiel #35
0
        public void Run(int pid)
        {
            Process targetProcess = Process.GetProcessById(pid);

            // Open and Suspend first thread
            ProcessThread pT = targetProcess.Threads[0];

            Logger.WriteLine("ThreadId: " + targetProcess.Threads[0].Id);
            IntPtr pOpenThread = OpenThread(ThreadAccess.THREAD_HIJACK, false, (uint)pT.Id);

            SuspendThread(pOpenThread);

            // Get thread context
            CONTEXT64 tContext = new CONTEXT64();

            tContext.ContextFlags = CONTEXT_FLAGS.CONTEXT_FULL;
            if (GetThreadContext(pOpenThread, ref tContext))
            {
                Logger.WriteLine("CurrentEip    :" + tContext.Rip);
            }

            byte[] payload = new byte[112] {
                0x50, 0x51, 0x52, 0x53, 0x56, 0x57, 0x55, 0x54, 0x58, 0x66, 0x83, 0xe4, 0xf0, 0x50, 0x6a, 0x60, 0x5a, 0x68, 0x63, 0x61, 0x6c, 0x63, 0x54, 0x59, 0x48, 0x29, 0xd4, 0x65, 0x48, 0x8b, 0x32, 0x48, 0x8b, 0x76, 0x18, 0x48, 0x8b, 0x76, 0x10, 0x48, 0xad, 0x48, 0x8b, 0x30, 0x48, 0x8b, 0x7e, 0x30, 0x03, 0x57, 0x3c, 0x8b, 0x5c, 0x17, 0x28, 0x8b, 0x74, 0x1f, 0x20, 0x48, 0x01, 0xfe, 0x8b, 0x54, 0x1f, 0x24, 0x0f, 0xb7, 0x2c, 0x17, 0x8d, 0x52, 0x02, 0xad, 0x81, 0x3c, 0x07, 0x57, 0x69, 0x6e, 0x45, 0x75, 0xef, 0x8b, 0x74, 0x1f, 0x1c, 0x48, 0x01, 0xfe, 0x8b, 0x34, 0xae, 0x48, 0x01, 0xf7, 0x99, 0xff, 0xd7, 0x48, 0x83, 0xc4, 0x68, 0x5c, 0x5d, 0x5f, 0x5e, 0x5b, 0x5a, 0x59, 0x58, 0xc3
            };
            // Once shellcode has executed return to thread original EIP address (mov to rax then jmp to address)
            byte[] mov_rax = new byte[2] {
                0x48, 0xb8
            };
            byte[] jmp_address = BitConverter.GetBytes(tContext.Rip);
            byte[] jmp_rax     = new byte[2] {
                0xff, 0xe0
            };

            // Build shellcode
            byte[] shellcode = new byte[payload.Length + mov_rax.Length + jmp_address.Length + jmp_rax.Length];
            payload.CopyTo(shellcode, 0);
            mov_rax.CopyTo(shellcode, payload.Length);
            jmp_address.CopyTo(shellcode, payload.Length + mov_rax.Length);
            jmp_rax.CopyTo(shellcode, payload.Length + mov_rax.Length + jmp_address.Length);

            // OpenProcess to allocate memory
            IntPtr procHandle = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, false, targetProcess.Id);

            // Allocate memory for shellcode within process
            IntPtr allocMemAddress = VirtualAllocEx(procHandle, IntPtr.Zero, (uint)((shellcode.Length + 1) * Marshal.SizeOf(typeof(char))), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);

            // Write shellcode within process
            UIntPtr bytesWritten;
            bool    resp1 = WriteProcessMemory(procHandle, allocMemAddress, shellcode, (uint)((shellcode.Length + 1) * Marshal.SizeOf(typeof(char))), out bytesWritten);

            // Read memory to view shellcode
            int bytesRead = 0;

            byte[] buffer = new byte[shellcode.Length];
            ReadProcessMemory(procHandle, allocMemAddress, buffer, buffer.Length, ref bytesRead);
            Logger.WriteLine("Data in memory: " + System.Text.Encoding.UTF8.GetString(buffer));

            // Set context EIP to location of shellcode
            tContext.Rip = (ulong)allocMemAddress.ToInt64();

            // Apply new context to suspended thread
            if (!SetThreadContext(pOpenThread, ref tContext))
            {
                Logger.WriteLine("Error setting context");
            }
            if (GetThreadContext(pOpenThread, ref tContext))
            {
                Logger.WriteLine("ShellcodeAddress: " + allocMemAddress);
                Logger.WriteLine("NewEip         : " + tContext.Rip);
            }
            // Resume the thread, redirecting execution to shellcode, then back to original process
            Logger.WriteLine("Redirecting execution!");
            ResumeThread(pOpenThread);
        }
 public static ulong GetNativeHandle(this ProcessThread thread, NT.ThreadAccess accessRights) => NT.OpenThread(accessRights, false, thread.Id);
Beispiel #37
0
        /// <summary>A thread worker function that processes items from the work queue</summary>
        private static void ProcessQueuedItems()
        {
            // Get the system/hardware thread index this thread is going to use. We hope that
            // the threads more or less start after each other, but there is no guarantee that
            // tasks will be handled by the CPU cores in the order the queue was filled with.
            // This could be added, though, by using a WaitHandle so the thread creator could
            // wait for each thread to take one entry out of the queue.
            int hardwareThreadIndex;

            lock (hardwareThreads) {
                hardwareThreadIndex = hardwareThreads.Dequeue();
            }

#if XBOX360
            // On the XBox 360, the only way to get a thread to run on another core is to
            // explicitly move it to that core. MSDN states that SetProcessorAffinity() should
            // be called from the thread whose affinity is being changed.
            Thread.CurrentThread.SetProcessorAffinity(new int[] { hardwareThreadIndex });
#elif !WINDOWS_PHONE
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                // Prevent this managed thread from impersonating another system thread.
                // In .NET, managed threads can supposedly be moved to different system threads
                // and, more worryingly, even fibers. This should make sure we're sitting on
                // a normal system thread and stay with that thread during our lifetime.
                Thread.BeginThreadAffinity();

                // Assign the ideal processor, but don't force it. It's not a good idea to
                // circumvent the thread scheduler of a desktop machine, so we try to play nice.
                int           threadId = GetCurrentThreadId();
                ProcessThread thread   = GetProcessThread(threadId);
                if (thread != null)
                {
                    thread.IdealProcessor = hardwareThreadIndex;
                }
            }
#endif

            // Keep processing tasks indefinitely
            for (; ;)
            {
                UserWorkItem workItem = getNextWorkItem();

                // Execute the work item we just picked up. Make sure to accurately
                // record how many callbacks are currently executing.
                try {
                    Interlocked.Increment(ref inUseThreads);
                    workItem.Callback(workItem.State);
                }
                catch (Exception exception) { // Make sure we don't throw here.
                    ExceptionDelegate exceptionHandler = ExceptionHandler;
                    if (exceptionHandler != null)
                    {
                        exceptionHandler(exception);
                    }
                }
                finally {
                    Interlocked.Decrement(ref inUseThreads);
                }
            }
        }
 internal override void Update(TreeNodeData tnd, bool allowUnsafeChanges, MainForm mf)
 {
     currentThread = ((ThreadData)tnd).Thread;
     UpdateControls();
 }
Beispiel #39
0
    public static int Main2(string[] args)
    {
        // Get target process by name
        if (args.Length == 0)
        {
            Console.WriteLine("Please enter a process name"); System.Environment.Exit(1);
        }
        Process targetProcess = Process.GetProcessesByName(args[0])[0];

        Console.WriteLine("ProcessId: " + targetProcess.Id);

        // Open and Suspend first thread
        ProcessThread pT = targetProcess.Threads[0];

        for (int i = 0; i < targetProcess.Threads.Count; i++)
        {
            if (pT.TotalProcessorTime < targetProcess.Threads[i].TotalProcessorTime)
            {
                ;
            }
        }

        Console.WriteLine("ThreadId: " + pT.Id);
        IntPtr pOpenThread = OpenThread(ThreadAccess.THREAD_HIJACK, false, (uint)pT.Id);

        SuspendThread(pOpenThread);

        // Get thread context
        CONTEXT64 tContext = new CONTEXT64();

        tContext.ContextFlags = CONTEXT_FLAGS.CONTEXT_FULL;
        if (GetThreadContext(pOpenThread, ref tContext))
        {
            Console.WriteLine("CurrentEip    : {0}", tContext.Rip.ToString("X12"));
        }

        // WinExec shellcode from: https://github.com/peterferrie/win-exec-calc-shellcode
        // Compiled with:
        // nasm w64-exec-calc-shellcode.asm -DSTACK_ALIGN=TRUE -DFUNC=TRUE -DCLEAN=TRUE -o w64-exec-calc-shellcode.bin
        //byte[] payload = new byte[112] {
        //	0x50,0x51,0x52,0x53,0x56,0x57,0x55,0x54,0x58,0x66,0x83,0xe4,0xf0,0x50,0x6a,0x60,0x5a,0x68,0x63,0x61,0x6c,0x63,0x54,0x59,0x48,0x29,0xd4,0x65,0x48,0x8b,0x32,0x48,0x8b,0x76,0x18,0x48,0x8b,0x76,0x10,0x48,0xad,0x48,0x8b,0x30,0x48,0x8b,0x7e,0x30,0x03,0x57,0x3c,0x8b,0x5c,0x17,0x28,0x8b,0x74,0x1f,0x20,0x48,0x01,0xfe,0x8b,0x54,0x1f,0x24,0x0f,0xb7,0x2c,0x17,0x8d,0x52,0x02,0xad,0x81,0x3c,0x07,0x57,0x69,0x6e,0x45,0x75,0xef,0x8b,0x74,0x1f,0x1c,0x48,0x01,0xfe,0x8b,0x34,0xae,0x48,0x01,0xf7,0x99,0xff,0xd7,0x48,0x83,0xc4,0x68,0x5c,0x5d,0x5f,0x5e,0x5b,0x5a,0x59,0x58,0xc3
        //};

        //0x18
        //0x28
        byte[] payload =
        {
            0x50, //push rax
            0x51, //push rcx
            0x52, //push rdx
            0x53, //push rbx
            0x54,
            0x55,
            0x56,
            0x57,
            0x41, 0x50,                                                                        //push r8
            0x41, 0x51,                                                                        //push r9
            0x41, 0x52,                                                                        //push r10
            0x41, 0x53,                                                                        //push r11
            0x41, 0x54,                                                                        //push r12
            0x41, 0x55,                                                                        //push r13
            0x41, 0x56,                                                                        //push r14
            0x41, 0x57,                                                                        //push r15
            0x55,                                                                              //push rbp
            0x48, 0x8B, 0xEC,                                                                  //mob rbp,rsp
            0x48, 0xB9, 0xEF, 0xBE, 0xAD, 0xDE, 0x00, 0x00, 0x00, 0x00,                        //mov rcx, &lua_buffer
            0x48, 0x8B, 0xD1,                                                                  //mov rdx, rcx
            0x4D, 0x31, 0xC0,                                                                  //xor r8,r8 -- r8 is luaIsTainted
            0x49, 0xBF, 0xEF, 0xBE, 0xAD, 0xDE, 0x00, 0x00, 0x00, 0x00,                        //mov r15, FrameScript_Execute
            0x41, 0xFF, 0xD7,                                                                  //call r15

            0x48, 0x8B, 0xE5,                                                                  //mov rsp, rbp
            0x5D,                                                                              //pop rbp
            0x41, 0x5F,                                                                        //pop r15
            0x41, 0x5E,                                                                        //pop r14
            0x41, 0x5D,                                                                        //pop r13
            0x41, 0x5C,                                                                        //pop r12
            0x41, 0x5B,                                                                        //pop r11
            0x41, 0x5A,                                                                        //pop r10
            0x41, 0x59,                                                                        //pop r9
            0x41, 0x58,                                                                        //pop r8
            0x5F,                                                                              //pop rdi
            0x5E,                                                                              //pop rsi
            0x5D,                                                                              //pop rbp
            0x5C,                                                                              //pop rsp
            0x5B,                                                                              //pop rbx
            0x5A,                                                                              //pop rdx
            0x59,                                                                              //pop rcx
            0x58,                                                                              //pop rax
            0xFF, 0x25, 0x00, 0x00, 0x00, 0x00, 0xEF, 0xBE, 0xAD, 0xDE, 0x00, 0x00, 0x00, 0x00 //jmp RIP
        };

        // OpenProcess to allocate memory
        IntPtr procHandle = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, false, targetProcess.Id);


        string luaScript        = "print(\"ferib is awesome\")";
        IntPtr allocMemAddress2 = VirtualAllocEx(procHandle, IntPtr.Zero, (uint)(luaScript.Length), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);

        long luacall = (long)targetProcess.MainModule.BaseAddress + 0x522280;

        byte[] luacalls = BitConverter.GetBytes(luacall);
        byte[] luacodes = BitConverter.GetBytes((long)allocMemAddress2);
        byte[] rips     = BitConverter.GetBytes(tContext.Rip);

        for (int i = 0; i < 8; i++)
        {
            payload[0x2E + i] = luacalls[i];
            payload[0x1E + i] = luacodes[i];
            payload[payload.Length - 0x08 + i] = rips[i];
        }


        // Allocate memory for shellcode within process
        IntPtr allocMemAddress = VirtualAllocEx(procHandle, IntPtr.Zero, (uint)((payload.Length + 1) * Marshal.SizeOf(typeof(char))), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);


        // Write shellcode within process
        UIntPtr bytesWritten;
        bool    resp1 = WriteProcessMemory(procHandle, allocMemAddress, payload, (uint)((payload.Length + 1) * Marshal.SizeOf(typeof(char))), out bytesWritten);

        WriteProcessMemory(procHandle, allocMemAddress2, Encoding.UTF8.GetBytes(luaScript), (uint)(luaScript.Length), out bytesWritten);

        // Read memory to view shellcode
        int bytesRead = 0;

        byte[] buffer = new byte[payload.Length];
        ReadProcessMemory(procHandle, allocMemAddress, buffer, buffer.Length, ref bytesRead);

        // Set context EIP to location of shellcode
        tContext.Rip = (ulong)allocMemAddress.ToInt64();

        // Apply new context to suspended thread
        if (!SetThreadContext(pOpenThread, ref tContext))
        {
            Console.WriteLine("Error setting context");
        }
        if (GetThreadContext(pOpenThread, ref tContext))
        {
            Console.WriteLine("ShellcodeAddress: " + allocMemAddress.ToString("X"));
            Console.WriteLine("NewEip          : {0}", tContext.Rip.ToString("X"));
        }
        // Resume the thread, redirecting execution to shellcode, then back to original process
        Console.WriteLine("Redirecting execution!");
        ResumeThread(pOpenThread);

        return(0);
    }
Beispiel #40
0
 internal MyThread(ProcessThread thread)
 {
     _thread = thread;
 }