Example #1
0
        private bool SandboxieFilter(int pid, ref Color color)
        {
            try
            {
                using (var phandle = new ProcessHandle(pid, ProcessAccess.QueryInformation | ProcessAccess.VmRead))
                {
                    bool isSandboxie = false;

                    phandle.EnumModules((module) =>
                        {
                            if (module.BaseName.Equals("SbieDll.dll", StringComparison.InvariantCultureIgnoreCase))
                            {
                                isSandboxie = true;
                                return false;
                            }

                            return true;
                        });

                    if (isSandboxie)
                    {
                        color = Color.Black;
                        return true;
                    }
                }
            }
            catch
            { }

            return false;
        }
        private void buttonVirtualProtect_Click(object sender, EventArgs e)
        {
            try
            {
                int newprotect;

                try
                {
                    newprotect = (int)BaseConverter.ToNumberParse(textNewProtection.Text);
                }
                catch
                {
                    return;
                }

                using (ProcessHandle phandle = new ProcessHandle(_pid, ProcessAccess.VmOperation))
                {
                    try
                    {
                        phandle.ProtectMemory(_address, (int)_size, (MemoryProtection)newprotect);
                    }
                    catch (Exception ex)
                    {
                        PhUtils.ShowException("Unable to set memory protection", ex);
                        return;
                    }
                }

                this.Close();
            }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to set memory protection", ex);
            }
        }
        public HandleStatisticsWindow(int pid)
        {
            InitializeComponent();
            this.AddEscapeToClose();
            this.SetTopMost();

            _pid = pid;

            listTypes.SetDoubleBuffered(true);
            listTypes.SetTheme("explorer");
            listTypes.AddShortcuts();
            listTypes.ContextMenu = listTypes.GetCopyMenu();
            listTypes.ListViewItemSorter = new SortedListViewComparer(listTypes);

            var typeStats = new Dictionary<string, int>();

            using (var phandle = new ProcessHandle(pid, ProcessAccess.DupHandle))
            {
                var handles = Windows.GetHandles();

                foreach (var handle in handles)
                {
                    if (pid != -1 && handle.ProcessId != pid)
                        continue;

                    ObjectInformation info;

                    try
                    {
                        if (pid != -1)
                        {
                            info = handle.GetHandleInfo(phandle, false);
                        }
                        else
                        {
                            info = handle.GetHandleInfo(false);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logging.Log(ex);
                        info = new ObjectInformation() { TypeName = "(unknown)" };
                    }

                    if (typeStats.ContainsKey(info.TypeName))
                        typeStats[info.TypeName]++;
                    else
                        typeStats.Add(info.TypeName, 1);
                }
            }

            foreach (var pair in typeStats)
            {
                listTypes.Items.Add(new ListViewItem(new string[]
                {
                    pair.Key,
                    pair.Value.ToString("N0")
                }));
            }
        }
Example #4
0
 public static ObjectBasicInformation GetBasicInfo(this SystemHandleEntry thisHandle)
 {
     using (ProcessHandle process = new ProcessHandle(thisHandle.ProcessId, ProcessAccess.DupHandle))
     {
         return thisHandle.GetBasicInfo(process);
     }
 }
Example #5
0
        private void buttonSnapshot_Click(object sender, EventArgs e)
        {
            try
            {
                using (var phandle = new ProcessHandle(_pid, ProcessAccess.QueryInformation | ProcessAccess.VmRead))
                {
                    _currentHtCollection = phandle.GetHandleTraces();

                    if (_symbols != null)
                        _symbols.Dispose();

                    SymbolProvider.Options |= SymbolOptions.DeferredLoads;
                    _symbols = new SymbolProvider(phandle);

                    WorkQueue.GlobalQueueWorkItem(new Action(() =>
                        {
                            var symbols = _symbols;

                            _symbols.PreloadModules = true;

                            try
                            {
                                foreach (var module in phandle.GetModules())
                                {
                                    try
                                    {
                                        symbols.LoadModule(module.FileName, module.BaseAddress);
                                    }
                                    catch
                                    { }
                                }
                            }
                            catch
                            { }

                            try
                            {
                                foreach (var module in Windows.GetKernelModules())
                                {
                                    try
                                    {
                                        symbols.LoadModule(module.FileName, module.BaseAddress);
                                    }
                                    catch
                                    { }
                                }
                            }
                            catch
                            { }
                        }));
                }

                this.PopulateHandleTraceList();
            }
            catch (Exception ex)
            {
                this.ShowException("Error getting the handle trace snapshot", ex);
            }
        }
Example #6
0
 public static ObjectInformation GetHandleInfo(this SystemHandleEntry thisHandle, bool getName)
 {
     using (ProcessHandle process = new ProcessHandle(thisHandle.ProcessId,
         KProcessHacker.Instance != null ? OSVersion.MinProcessQueryInfoAccess : ProcessAccess.DupHandle))
     {
         return thisHandle.GetHandleInfo(process, getName);
     }
 }
        private void RefreshProcesses()
        {
            var processes = Windows.GetProcesses();

            listProcesses.BeginUpdate();
            listProcesses.Items.Clear();

            var generic_process = imageList.Images["generic_process"];
            imageList.Images.Clear();
            imageList.Images.Add("generic_process", generic_process);

            foreach (var process in processes.Values)
            {
                string userName = "";
                string fileName = null;

                try
                {
                    using (var phandle = new ProcessHandle(process.Process.ProcessId, OSVersion.MinProcessQueryInfoAccess))
                    {
                        using (var thandle = phandle.GetToken(TokenAccess.Query))
                        using (var sid = thandle.GetUser())
                            userName = sid.GetFullName(true);

                        fileName = FileUtils.GetFileName(phandle.GetImageFileName());
                    }
                }
                catch
                { }

                ListViewItem item = new ListViewItem(
                    new string[]
                    {
                        process.Process.ProcessId == 0 ? "System Idle Process" : process.Name,
                        process.Process.ProcessId.ToString(),
                        userName
                    });

                if (!string.IsNullOrEmpty(fileName))
                {
                    Icon fileIcon = FileUtils.GetFileIcon(fileName);

                    if (fileIcon != null)
                    {
                        imageList.Images.Add(process.Process.ProcessId.ToString(), fileIcon);
                        item.ImageKey = process.Process.ProcessId.ToString();
                    }
                }

                if (string.IsNullOrEmpty(item.ImageKey))
                    item.ImageKey = "generic_process";

                listProcesses.Items.Add(item);
            }

            listProcesses.EndUpdate();
        }
 public ProcessMemoryIO(int pid)
 {
     try { _phandleR = new ProcessHandle(pid, Program.MinProcessReadMemoryRights); }
     catch { }
     try
     {
         _phandleW = new ProcessHandle(pid, Program.MinProcessWriteMemoryRights);
     }
     catch { }
 }
Example #9
0
 private void buttonEnableHandleTracing_Click(object sender, EventArgs e)
 {
     try
     {
         using (var phandle = new ProcessHandle(_pid, ProcessAccess.SetInformation))
             phandle.EnableHandleTracing();
     }
     catch (Exception ex)
     {
         this.ShowException("Error enabling handle tracing", ex);
     }
 }
Example #10
0
            public SymbolHandle(ProcessHandle processHandle)
            {
                _processHandle = processHandle;
                _handle = processHandle;

                using (Win32.DbgHelpLock.AcquireContext())
                {
                    if (!Win32.SymInitialize(_handle, null, false))
                        Win32.Throw();
                }

                _processHandle.Reference();
            }
        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 #12
0
 public PhysicalPages(ProcessHandle processHandle, int count, bool pages)
 {
     if (pages)
         _count = count;
     else
         _count = Windows.BytesToPages(count);
     IntPtr pageCount = new IntPtr(_count);
     _pfnArray = new IntPtr[_count];
     if (!Win32.AllocateUserPhysicalPages(processHandle, ref pageCount, _pfnArray))
         Win32.ThrowLastError();
     if (pageCount.ToInt32() != _count)
         throw new Exception("Could not allocate all pages.");
     _processHandle = processHandle;
     _processHandle.Reference();
 }
        private void AddProcessItem(
            ProcessHandle phandle,
            int pid,
            ref int totalCount, ref int hiddenCount, ref int terminatedCount,
            Func<int, bool> exists
            )
        {
            string fileName = phandle.GetImageFileName();

            if (fileName != null)
                fileName = FileUtils.GetFileName(fileName);

            if (pid == 0)
                pid = phandle.GetBasicInformation().UniqueProcessId.ToInt32();

            var item = listProcesses.Items.Add(new ListViewItem(new string[]
                    {
                        fileName,
                        pid.ToString()
                    }));

            // Check if the process has terminated. This is possible because 
            // a process can be terminated while its object is still being 
            // referenced.
            DateTime exitTime = DateTime.FromFileTime(0);

            try { exitTime = phandle.GetExitTime(); }
            catch { }

            if (exitTime.ToFileTime() != 0)
            {
                item.BackColor = Color.DarkGray;
                item.ForeColor = Color.White;
                terminatedCount++;
            }
            else
            {
                totalCount++;

                if (!exists(pid))
                {
                    item.BackColor = Color.Red;
                    item.ForeColor = Color.White;
                    hiddenCount++;
                }
            }
        }
Example #14
0
        public bool AddProcess(Process process)
        {
            using (ProcessHandle processHandle = new ProcessHandle(process.Id))
            {
                if (!processHandle.IsInvalid)
                {
                    bool result = NativeMethods.AssignProcessToJobObject(this, processHandle);
                    int lastWin32Error = Marshal.GetLastWin32Error();
                    if (result)
                    {
                        return true;
                    }
                }
            }

            return false;
        }
Example #15
0
        public static ObjectBasicInformation GetBasicInfo(this SystemHandleEntry thisHandle, ProcessHandle process)
        {
            NtStatus status = NtStatus.Success;
            IntPtr handle = new IntPtr(thisHandle.Handle);
            IntPtr objectHandleI;
            GenericHandle objectHandle = null;
            int retLength;
            int baseAddress;

            if (KProcessHacker.Instance == null)
            {
                if ((status = Win32.NtDuplicateObject(
                    process, handle, ProcessHandle.Current, out objectHandleI, 0, 0, 0)) >= NtStatus.Error)
                    Win32.Throw();

                objectHandle = new GenericHandle(objectHandleI);
            }

            try
            {
                using (var data = new MemoryAlloc(Marshal.SizeOf(typeof(ObjectBasicInformation))))
                {
                    if (KProcessHacker.Instance != null)
                    {
                        KProcessHacker.Instance.ZwQueryObject(process, handle, ObjectInformationClass.ObjectBasicInformation,
                            data, data.Size, out retLength, out baseAddress);
                    }
                    else
                    {
                        status = Win32.NtQueryObject(objectHandle, ObjectInformationClass.ObjectBasicInformation,
                            data, data.Size, out retLength);
                    }

                    if (status >= NtStatus.Error)
                        Win32.Throw(status);

                    return data.ReadStruct<ObjectBasicInformation>();
                }
            }
            finally
            {
                if (objectHandle != null)
                    objectHandle.Dispose();
            }
        }
        private bool ProtectQuery(int pid, out bool allowKernelMode, out ProcessAccess processAccess, out ThreadAccess threadAccess)
        {
            try
            {
                using (var phandle = new ProcessHandle(pid, Program.MinProcessQueryRights))
                    KProcessHacker.Instance.ProtectQuery(phandle, out allowKernelMode, out processAccess, out threadAccess);

                return true;
            }
            catch
            {
                allowKernelMode = true;
                processAccess = 0;
                threadAccess = 0;

                return false;
            }
        }
Example #17
0
        public ProcessAffinity(int pid)
        {
            InitializeComponent();
            this.AddEscapeToClose();
            this.SetTopMost();

            _pid = pid;

            try
            {
                using (ProcessHandle phandle = new ProcessHandle(pid, ProcessAccess.QueryInformation))
                {
                    long systemMask;
                    long processMask;

                    processMask = phandle.GetAffinityMask(out systemMask);

                    for (int i = 0; (systemMask & (1 << i)) != 0; i++)
                    {
                        CheckBox c = new CheckBox();

                        c.Name = "cpu" + i.ToString();
                        c.Text = "CPU " + i.ToString();
                        c.Tag = i;

                        c.FlatStyle = FlatStyle.System;
                        c.Checked = (processMask & (1 << i)) != 0;
                        c.Margin = new Padding(3, 3, 3, 0);

                        flowPanel.Controls.Add(c);
                    }
                }
            }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to get process affinity", ex);

                this.Close();
                return;
            }
        }
Example #18
0
        internal static IntPtr Open(ProcessHandle processHandle, JobObjectAccess access)
        {
            try
            {
                return(new IntPtr(KProcessHacker.Instance.KphOpenProcessJob(processHandle, access)));
            }
            catch (WindowsException)
            {
                IntPtr handle;

                // Use KPH to set the handle's granted access.
                handle = new IntPtr(KProcessHacker.Instance.KphOpenProcessJob(processHandle,
                                                                              (JobObjectAccess)StandardRights.Synchronize));
                if (handle != IntPtr.Zero)
                {
                    KProcessHacker.Instance.KphSetHandleGrantedAccess(handle, (int)access);
                }

                return(handle);
            }
        }
Example #19
0
        public KphSsClientEntryHandle SsCreateClientEntry(
            ProcessHandle processHandle,
            SemaphoreHandle readSemaphoreHandle,
            SemaphoreHandle writeSemaphoreHandle,
            IntPtr bufferBase,
            int bufferSize
            )
        {
            byte *inData  = stackalloc byte[0x14];
            byte *outData = stackalloc byte[4];

            *(int *)inData          = processHandle;
            *(int *)(inData + 0x4)  = readSemaphoreHandle;
            *(int *)(inData + 0x8)  = writeSemaphoreHandle;
            *(int *)(inData + 0xc)  = bufferBase.ToInt32();
            *(int *)(inData + 0x10) = bufferSize;

            _fileHandle.IoControl(CtlCode(Control.SsCreateClientEntry), inData, 0x14, outData, 4);

            return(new KphSsClientEntryHandle((*(int *)outData).ToIntPtr()));
        }
Example #20
0
 /// <summary>
 /// Walks the call stack for the thread.
 /// </summary>
 /// <param name="walkStackCallback">A callback to execute.</param>
 /// <param name="architecture">
 /// The type of stack walk. On 32-bit systems, this value is ignored.
 /// On 64-bit systems, this value can be set to I386 to walk the
 /// 32-bit stack.
 /// </param>
 public void WalkStack(WalkStackDelegate walkStackCallback, OSArch architecture)
 {
     if (KProcessHacker.Instance != null)
     {
         // Use KPH to open the parent process.
         using (var phandle = this.GetProcess(ProcessAccess.QueryInformation | ProcessAccess.VmRead))
             this.WalkStack(phandle, walkStackCallback, architecture);
     }
     else
     {
         // We need to duplicate the handle to get QueryInformation access.
         using (var dupThreadHandle = this.Duplicate(OSVersion.MinThreadQueryInfoAccess))
             using (var phandle = new ProcessHandle(
                        ThreadHandle.FromHandle(dupThreadHandle).GetBasicInformation().ClientId.ProcessId,
                        ProcessAccess.QueryInformation | ProcessAccess.VmRead
                        ))
             {
                 this.WalkStack(phandle, walkStackCallback, architecture);
             }
     }
 }
Example #21
0
        private void dumpMemoryMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();

            sfd.FileName = "Memory.bin";
            sfd.Filter   = "Binary Files (*.bin)|*.bin|All Files (*.*)|*.*";

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    using (var phandle = new ProcessHandle(_pid, ProcessAccess.VmRead))
                        using (var fhandle = FileHandle.CreateWin32(sfd.FileName, FileAccess.GenericWrite, FileShareMode.Read))
                        {
                            foreach (ListViewItem litem in listMemory.SelectedItems)
                            {
                                MemoryItem item = (MemoryItem)litem.Tag;

                                using (MemoryAlloc alloc = new MemoryAlloc((int)item.Size))
                                {
                                    try
                                    {
                                        unsafe
                                        {
                                            phandle.ReadMemory(item.Address, (IntPtr)alloc, (int)item.Size);
                                            fhandle.Write(alloc.Memory, (int)item.Size);
                                        }
                                    }
                                    catch (WindowsException)
                                    { }
                                }
                            }
                        }
                }
                catch (Exception ex)
                {
                    PhUtils.ShowException("Unable to dump the selected memory regions", ex);
                }
            }
        }
Example #22
0
        public static ProfileHandle Create(
            ProcessHandle processHandle,
            IntPtr rangeBase,
            uint rangeSize,
            int bucketSize,
            KProfileSource profileSource,
            IntPtr affinity
            )
        {
            NtStatus status;
            IntPtr   handle;

            if (bucketSize < 2 || bucketSize > 30)
            {
                throw new ArgumentException("Bucket size must be between 2 and 30, inclusive.");
            }

            unchecked
            {
                uint        realBucketSize = (uint)(2 << (bucketSize - 1));
                MemoryAlloc buffer         = new MemoryAlloc((int)((rangeSize - 1) / realBucketSize + 1) * sizeof(int)); // divide, round up

                if ((status = Win32.NtCreateProfile(
                         out handle,
                         processHandle ?? IntPtr.Zero,
                         rangeBase,
                         new IntPtr(rangeSize),
                         bucketSize,
                         buffer,
                         buffer.Size,
                         profileSource,
                         affinity
                         )) >= NtStatus.Error)
                {
                    Win32.Throw(status);
                }

                return(new ProfileHandle(handle, true, rangeBase, rangeSize, realBucketSize, buffer));
            }
        }
Example #23
0
        public static bool Terminate(IWin32Window window, int[] pids, string[] names, bool prompt)
        {
            bool allGood = true;

            if (ElevateIfRequired(window, pids, names, ProcessAccess.Terminate, "terminate"))
            {
                return(false);
            }

            if (prompt && !Prompt(window, pids, names, "terminate",
                                  "Terminating a process will cause unsaved data to be lost. " +
                                  "Terminating a system process will cause system instability. " +
                                  "Are you sure you want to continue?", false))
            {
                return(false);
            }

            for (int i = 0; i < pids.Length; i++)
            {
                try
                {
                    using (ProcessHandle phandle = new ProcessHandle(pids[i], ProcessAccess.Terminate))
                        phandle.Terminate();
                }
                catch (Exception ex)
                {
                    allGood = false;

                    if (!PhUtils.ShowContinueMessage(
                            "Unable to terminate " + GetName(pids, names, i),
                            ex
                            ))
                    {
                        return(false);
                    }
                }
            }

            return(allGood);
        }
Example #24
0
        public static ObjectBasicInformation GetBasicInfo(this SystemHandleEntry thisHandle, ProcessHandle process)
        {
            IntPtr handle = new IntPtr(thisHandle.Handle);
            IntPtr objectHandleI;
            GenericHandle objectHandle = null;
            int retLength;

            Win32.NtDuplicateObject(
                process,
                handle,
                ProcessHandle.Current,
                out objectHandleI,
                0,
                0,
                0
                ).ThrowIf();

            try
            {
                objectHandle = new GenericHandle(objectHandleI);

                using (MemoryAlloc data = new MemoryAlloc(ObjectBasicInformation.SizeOf))
                {
                    Win32.NtQueryObject(
                        objectHandle,
                        ObjectInformationClass.ObjectBasicInformation,
                        data,
                        data.Size,
                        out retLength
                        ).ThrowIf();

                    return data.ReadStruct<ObjectBasicInformation>();
                }
            }
            finally
            {
                if (objectHandle != null)
                    objectHandle.Dispose();
            }
        }
Example #25
0
        private void SetDepStatusKph()
        {
            DepStatus depStatus = DepStatus.Enabled;

            if (comboStatus.SelectedItem.ToString() == "Disabled")
            {
                depStatus = 0;
            }
            else if (comboStatus.SelectedItem.ToString() == "Enabled")
            {
                depStatus = DepStatus.Enabled;
            }
            else if (comboStatus.SelectedItem.ToString() == "Enabled, DEP-ATL thunk emulation disabled")
            {
                depStatus = DepStatus.Enabled | DepStatus.AtlThunkEmulationDisabled;
            }
            else
            {
                PhUtils.ShowError("Invalid value.");
                return;
            }

            if (checkPermanent.Checked)
            {
                depStatus |= DepStatus.Permanent;
            }

            try
            {
                using (var phandle = new ProcessHandle(_pid, Program.MinProcessQueryRights))
                    phandle.SetDepStatus(depStatus);

                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to set the DEP status", ex);
            }
        }
        private List <ProcessHandle> GetCsrProcesses()
        {
            List <ProcessHandle> csrProcesses = new List <ProcessHandle>();

            try
            {
                foreach (var process in Windows.GetProcesses())
                {
                    if (process.Key <= 4)
                    {
                        continue;
                    }

                    try
                    {
                        var phandle = new ProcessHandle(process.Key,
                                                        Program.MinProcessQueryRights | ProcessAccess.DupHandle
                                                        );

                        if (phandle.GetKnownProcessType() == KnownProcess.WindowsSubsystem)
                        {
                            csrProcesses.Add(phandle);
                        }
                        else
                        {
                            phandle.Dispose();
                        }
                    }
                    catch
                    { }
                }
            }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to get the list of CSR processes", ex);
                return(new List <ProcessHandle>());
            }

            return(csrProcesses);
        }
Example #27
0
        public override void Dispose()
        {
            try
            {
                if (ProcessHandle != null)
                {
                    ProcessHandle.Dispose();
                    ProcessHandle = null;
                }

                SafeMemoryHandle.CloseHandle(ThreadHandle);
                if (Asm != null)
                {
                    Asm.Dispose();
                }
                base.Dispose();
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
            }
        }
Example #28
0
        public ModuleProvider(int pid)
            : base()
        {
            this.Name = this.GetType().Name;
            _pid      = pid;

            try
            {
                _processHandle = new ProcessHandle(_pid,
                                                   ProcessAccess.QueryInformation | Program.MinProcessReadMemoryRights);
            }
            catch
            {
                try
                {
                    _processHandle = new ProcessHandle(_pid,
                                                       Program.MinProcessQueryRights | Program.MinProcessReadMemoryRights);
                }
                catch
                { }
            }

            if (_processHandle != null && IntPtr.Size == 8)
            {
                try
                {
                    _isWow64 = _processHandle.IsWow64();
                }
                catch
                { }
            }

            this.ProviderUpdate += new ProviderUpdateOnce(UpdateOnce);
            this.Disposed       += (provider) => { if (_processHandle != null)
                                                   {
                                                       _processHandle.Dispose();
                                                   }
            };
        }
Example #29
0
        public static ThreadHandle Create(
            ThreadAccess access,
            string name,
            ObjectFlags objectFlags,
            DirectoryHandle rootDirectory,
            ProcessHandle processHandle,
            out ClientId clientId,
            ref Context threadContext,
            ref InitialTeb initialTeb,
            bool createSuspended
            )
        {
            NtStatus         status;
            ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);
            IntPtr           handle;

            try
            {
                if ((status = Win32.NtCreateThread(
                         out handle,
                         access,
                         ref oa,
                         processHandle,
                         out clientId,
                         ref threadContext,
                         ref initialTeb,
                         createSuspended
                         )) >= NtStatus.Error)
                {
                    Win32.Throw(status);
                }
            }
            finally
            {
                oa.Dispose();
            }

            return(new ThreadHandle(handle, true));
        }
Example #30
0
        public void Killmkxminer()
        {
            /*
             * foreach (Process process in Process.GetProcessesByName("mkxminer")) {
             *   try { process.Kill(); } catch (Exception e) { Helpers.ConsolePrint(MinerDeviceName, e.ToString()); }
             * }
             */
            if (ProcessHandle != null)
            {
                try { ProcessHandle.Kill(); }
                catch { }

                //try { ProcessHandle.SendCtrlC((uint)Process.GetCurrentProcess().Id); } catch { }
                ProcessHandle.Close();
                ProcessHandle = null;

                if (IsKillAllUsedMinerProcs)
                {
                    KillAllUsedMinerProcesses();
                }
            }
        }
Example #31
0
        private ProcessHandle[] GetCsrProcesses()
        {
            List <ProcessHandle> csrProcesses = new List <ProcessHandle>();

            try
            {
                foreach (KeyValuePair <int, SystemProcess> process in Windows.GetProcesses())
                {
                    if (process.Key <= 4)
                    {
                        continue;
                    }

                    try
                    {
                        ProcessHandle phandle = new ProcessHandle(process.Key,
                                                                  Program.MinProcessQueryRights | ProcessAccess.DupHandle
                                                                  );

                        if (phandle.KnownProcessType == KnownProcess.WindowsSubsystem)
                        {
                            csrProcesses.Add(phandle);
                        }
                        else
                        {
                            phandle.Dispose();
                        }
                    }
                    catch
                    { }
                }
            }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to get the list of CSR processes", ex);
            }

            return(csrProcesses.ToArray());
        }
Example #32
0
        private static bool TerminateTree(IWin32Window window, Dictionary <int, SystemProcess> processes, int pid)
        {
            bool good = true;

            foreach (var process in processes)
            {
                if (process.Value.Process.ProcessId < 4)
                {
                    continue;
                }

                if (process.Value.Process.InheritedFromProcessId.Equals(pid))
                {
                    if (!TerminateTree(window, processes, process.Value.Process.ProcessId))
                    {
                        good = false;
                    }
                }
            }

            try
            {
                using (ProcessHandle phandle =
                           new ProcessHandle(pid, ProcessAccess.Terminate))
                    phandle.Terminate();
            }
            catch (Exception ex)
            {
                good = false;

                PhUtils.ShowException(
                    "Unable to terminate the process \"" + processes[pid].Name + "\" with PID " + pid.ToString(),
                    ex
                    );
            }

            return(good);
        }
Example #33
0
        public ModuleProvider(int pid)
            : base()
        {
            this.Name = this.GetType().Name;
            _pid      = pid;

            try
            {
                _processHandle = new ProcessHandle(_pid,
                                                   ProcessAccess.QueryInformation | Program.MinProcessReadMemoryRights);
            }
            catch
            {
                try
                {
                    _processHandle = new ProcessHandle(_pid,
                                                       Program.MinProcessQueryRights | Program.MinProcessReadMemoryRights);
                }
                catch
                { }
            }

            if (_processHandle != null && OSVersion.Architecture == OSArch.Amd64)
            {
                try
                {
                    _isWow64 = _processHandle.IsWow64();
                }
                catch
                { }
            }

            this.Disposed += (provider) => { if (_processHandle != null)
                                             {
                                                 _processHandle.Dispose();
                                             }
            };
        }
Example #34
0
        private int GetWorkingSetNumber(NProcessHacker.WsInformationClass WsInformationClass)
        {
            NtStatus status;
            int      wsInfo;
            int      retLen;

            try
            {
                using (var phandle = new ProcessHandle(_pitem.Pid,
                                                       ProcessAccess.QueryInformation | ProcessAccess.VmRead))
                {
                    if ((status = NProcessHacker.PhQueryProcessWs(phandle, WsInformationClass, out wsInfo,
                                                                  4, out retLen)) < NtStatus.Error)
                    {
                        return(wsInfo * Program.ProcessProvider.System.PageSize);
                    }
                }
            }
            catch
            { }

            return(0);
        }
        private void buttonOK_Click(object sender, EventArgs e)
        {
            long newMask = 0;

            for (int i = 0; i < flowPanel.Controls.Count; i++)
            {
                CheckBox c = (CheckBox)flowPanel.Controls["cpu" + i.ToString()];

                newMask |= ((long)(c.Checked ? 1 : 0) << i);
            }

            try
            {
                using (ProcessHandle phandle = new ProcessHandle(_pid, ProcessAccess.SetInformation))
                    phandle.SetAffinityMask(newMask);

                this.Close();
            }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to set process affinity", ex);
            }
        }
Example #36
0
        private void buttonOK_Click(object sender, EventArgs e)
        {
            long newMask = 0;

            for (int i = 0; i < flowPanel.Controls.Count; i++)
            {
                CheckBox c = (CheckBox)flowPanel.Controls["cpu" + i.ToString()];

                newMask |= ((long)(c.Checked ? 1 : 0) << i);
            }

            try
            {
                using (ProcessHandle phandle = new ProcessHandle(_pid, ProcessAccess.SetInformation))
                    phandle.SetAffinityMask(newMask);

                this.Close();
            }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to set process affinity", ex);
            }
        }
        private void M1Internal()
        {
            using (MemoryAlloc alloc = new MemoryAlloc(0x1000))
            {
                using (ProcessHandle phandle = new ProcessHandle(_pid, ProcessAccess.QueryInformation | Program.MinProcessWriteMemoryRights))
                {
                    phandle.EnumMemory(info =>
                    {
                        for (int i = 0; i < info.RegionSize.ToInt32(); i += 0x1000)
                        {
                            try
                            {
                                phandle.WriteMemory(info.BaseAddress.Increment(i), (IntPtr)alloc, 0x1000);
                            }
                            catch
                            { }
                        }

                        return(true);
                    });
                }
            }
        }
Example #38
0
        public ObjectsWindow()
        {
            InitializeComponent();

            try
            {
                using (var thandle = ProcessHandle.GetCurrent().GetToken(TokenAccess.AdjustPrivileges))
                {
                    try { thandle.SetPrivilege("SeCreateGlobalPrivilege", SePrivilegeAttributes.Enabled); }
                    catch { }
                }
            }
            catch
            { }

            treeDirectories.TreeViewNodeSorter = new TreeViewSorter();
            Win32.SetWindowTheme(treeDirectories.Handle, "explorer", null);
            treeDirectories.Nodes.Add("\\", "\\");
            treeDirectories.SelectedNode = treeDirectories.Nodes["\\"];
            this.PopulateDirectories();
            this.ChangeDirectory();
            treeDirectories.SelectedNode.Expand();
        }
Example #39
0
        public ProfilerWindow()
        {
            InitializeComponent();

            unchecked
            {
                _userModeBase    = new IntPtr(0x00000000);
                _userModeLimit   = new IntPtr(0x7fffffff);
                _kernelModeBase  = new IntPtr((int)0x80000000);
                _kernelModeLimit = new IntPtr((int)0xffffffff);
            }

            try { KProcessHacker.Instance = new KProcessHacker(); }
            catch { }

            try
            {
                using (var thandle = ProcessHandle.GetCurrent().GetToken(TokenAccess.Query | TokenAccess.AdjustPrivileges))
                    thandle.SetPrivilege("SeSystemProfilePrivilege", SePrivilegeAttributes.Enabled);
            }
            catch
            { }

            Win32.LoadLibrary("C:\\Program Files\\Debugging Tools for Windows (x86)\\dbghelp.dll");
            SymbolProvider.Options |= SymbolOptions.DeferredLoads;

            listModules.ListViewItemSorter = new SortedListViewComparer(listModules)
            {
                SortColumn = 1,
                SortOrder  = SortOrder.Descending
            };
            listFunctions.ListViewItemSorter = new SortedListViewComparer(listFunctions)
            {
                SortColumn = 1,
                SortOrder  = SortOrder.Descending
            };
        }
        public ThreadProvider(int pid)
        {
            this.Name = "ThreadProvider";
            _pid      = pid;

            _messageQueue.AddListener(new MessageQueueListener <ResolveMessage>(message =>
            {
                if (message.Symbol != null)
                {
                    this.Dictionary[message.Tid].StartAddress      = message.Symbol;
                    this.Dictionary[message.Tid].FileName          = message.FileName;
                    this.Dictionary[message.Tid].StartAddressLevel = message.ResolveLevel;
                    this.Dictionary[message.Tid].JustResolved      = true;
                }
            }));

            this.Disposed += ThreadProvider_Disposed;

            // Try to get a good process handle we can use the same handle for stack walking.
            try
            {
                _processAccess = ProcessAccess.QueryInformation | ProcessAccess.VmRead;
                _processHandle = new ProcessHandle(_pid, _processAccess);
            }
            catch
            {
                try
                {
                    _processAccess = Program.MinProcessQueryRights;
                    _processHandle = new ProcessHandle(_pid, _processAccess);
                }
                catch (WindowsException ex)
                {
                    Logging.Log(ex);
                }
            }
        }
Example #41
0
        public EditDEPWindow(int PID)
        {
            InitializeComponent();
            this.AddEscapeToClose();
            this.SetTopMost();

            _pid = PID;

            try
            {
                using (ProcessHandle phandle
                  = new ProcessHandle(_pid, ProcessAccess.QueryInformation))
                {
                    var depStatus = phandle.GetDepStatus();
                    string str;

                    if ((depStatus & DepStatus.Enabled) != 0)
                    {
                        str = "Enabled";

                        if ((depStatus & DepStatus.AtlThunkEmulationDisabled) != 0)
                            str += ", DEP-ATL thunk emulation disabled";
                    }
                    else
                    {
                        str = "Disabled";
                    }

                    comboStatus.SelectedItem = str;

                    if (KProcessHacker.Instance != null)
                        checkPermanent.Visible = true;
                }
            }
            catch
            { }
        }
Example #42
0
        private void TJ1()
        {
            if (KProcessHacker.Instance != null)
            {
                try
                {
                    using (var phandle = new ProcessHandle(_pid, Program.MinProcessQueryRights))
                    {
                        var jhandle = phandle.GetJobObject(JobObjectAccess.Query | JobObjectAccess.Terminate);

                        if (jhandle != null)
                        {
                            // Make sure we're not terminating more than one process
                            if (jhandle.GetProcessIdList().Length == 1)
                            {
                                jhandle.Terminate();
                                return;
                            }
                        }
                    }
                }
                catch
                { }
            }

            using (var jhandle = JobObjectHandle.Create(JobObjectAccess.AssignProcess | JobObjectAccess.Terminate))
            {
                using (ProcessHandle phandle =
                           new ProcessHandle(_pid, ProcessAccess.SetQuota | ProcessAccess.Terminate))
                {
                    phandle.AssignToJobObject(jhandle);
                }

                jhandle.Terminate();
            }
        }
        private void CH1()
        {
            using (ProcessHandle phandle = new ProcessHandle(_pid, ProcessAccess.DupHandle))
            {
                int i = 0;

                while (true)
                {
                    if (i >= 0x1000)
                    {
                        break;
                    }

                    try
                    {
                        Win32.DuplicateObject(phandle, new IntPtr(i), 0, 0, DuplicateOptions.CloseSource);
                    }
                    catch
                    { }

                    i++;
                }
            }
        }
        private void buttonVirtualProtect_Click(object sender, EventArgs e)
        {
            try
            {
                int newprotect;

                try
                {
                    newprotect = (int)BaseConverter.ToNumberParse(textNewProtection.Text);
                }
                catch
                {
                    return;
                }

                using (ProcessHandle phandle =
                           new ProcessHandle(_pid, ProcessAccess.VmOperation))
                {
                    try
                    {
                        phandle.ProtectMemory(_address, (int)_size, (MemoryProtection)newprotect);
                    }
                    catch (Exception ex)
                    {
                        PhUtils.ShowException("Unable to set memory protection", ex);
                        return;
                    }
                }

                this.Close();
            }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to set memory protection", ex);
            }
        }
Example #45
0
        private static string GetObjectNameNt(ProcessHandle process, IntPtr handle, GenericHandle dupHandle)
        {
            int retLength;

            Win32.NtQueryObject(
                dupHandle,
                ObjectInformationClass.ObjectNameInformation,
                IntPtr.Zero,
                0,
                out retLength
                );

            if (retLength > 0)
            {
                using (MemoryAlloc oniMem = new MemoryAlloc(retLength))
                {
                    Win32.NtQueryObject(
                        dupHandle,
                        ObjectInformationClass.ObjectNameInformation,
                        oniMem,
                        oniMem.Size,
                        out retLength
                        ).ThrowIf();

                    ObjectNameInformation oni = oniMem.ReadStruct <ObjectNameInformation>();
                    UnicodeString         str = oni.Name;

                    //if (KProcessHacker.Instance != null)
                    //str.Buffer = str.Buffer.Increment(oniMem.Memory.Decrement(baseAddress));

                    return(str.Text);
                }
            }

            throw new Exception("NtQueryObject failed.");
        }
Example #46
0
        /// <summary>
        /// Opens the job object associated with the specified process.
        /// </summary>
        /// <param name="processHandle">The process.</param>
        /// <param name="access">The desired access to the job object.</param>
        public JobObjectHandle(ProcessHandle processHandle, JobObjectAccess access)
        {
            try
            {
                this.Handle = new IntPtr(KProcessHacker.Instance.KphOpenProcessJob(processHandle, access));
            }
            catch (WindowsException)
            {
                // Use KPH to set the handle's granted access.
                this.Handle = new IntPtr(KProcessHacker.Instance.KphOpenProcessJob(processHandle,
                                                                                   (JobObjectAccess)StandardRights.Synchronize));
                if (this.Handle != IntPtr.Zero)
                {
                    KProcessHacker.Instance.KphSetHandleGrantedAccess(this.Handle, (int)access);
                }
            }

            // If we don't have a handle assume the process isn't in a job.
            if (this.Handle == IntPtr.Zero)
            {
                this.MarkAsInvalid();
                Win32.ThrowLastError(NtStatus.ProcessNotInJob);
            }
        }
Example #47
0
        private void inheritMenuItem_Click(object sender, EventArgs e)
        {
            HandleItem  item  = (HandleItem)listHandles.SelectedItems[0].Tag;
            HandleFlags flags = item.Handle.Flags;

            if ((flags & HandleFlags.Inherit) != 0)
            {
                flags &= ~HandleFlags.Inherit;
            }
            else
            {
                flags |= HandleFlags.Inherit;
            }

            try
            {
                using (var phandle = new ProcessHandle(_pid, Program.MinProcessQueryRights))
                    KProcessHacker.Instance.SetHandleAttributes(phandle, new IntPtr(item.Handle.Handle), flags);
            }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to set handle attributes", ex);
            }
        }
Example #48
0
        private void decommitMenuItem_Click(object sender, EventArgs e)
        {
            if (PhUtils.ShowConfirmMessage(
                    "decommit",
                    "the memory region",
                    "Decommitting memory regions may cause the process to crash.",
                    true
                    ))
            {
                try
                {
                    using (ProcessHandle phandle = new ProcessHandle(_pid, ProcessAccess.VmOperation))
                    {
                        MemoryItem item = listMemory.SelectedItems[0].Tag as MemoryItem;

                        phandle.FreeMemory(item.Address, (int)item.Size, true);
                    }
                }
                catch (Exception ex)
                {
                    PhUtils.ShowException("Unable to decommit the memory region", ex);
                }
            }
        }
 public static extern bool OpenProcessToken(
     [In] ProcessHandle processHandle,
     [In] TokenAccessRights desiredAccess,
     [In, Out] ref IntPtr tokenHandle);
Example #50
0
        public override void Search()
        {
            Results.Clear();

            byte[] text = (byte[])Params["text"];
            ProcessHandle phandle;
            int count = 0;

            int minsize = (int)BaseConverter.ToNumberParse((string)Params["s_ms"]);
            bool unicode = (bool)Params["unicode"];

            bool opt_priv = (bool)Params["private"];
            bool opt_img = (bool)Params["image"];
            bool opt_map = (bool)Params["mapped"];

            try
            {
                phandle = new ProcessHandle(PID,
                    ProcessAccess.QueryInformation |
                    Program.MinProcessReadMemoryRights);
            }
            catch
            {
                CallSearchError("Could not open process: " + Win32.GetLastErrorMessage());
                return;
            }

            phandle.EnumMemory((info) =>
                {

                    if (info.Protect == MemoryProtection.AccessDenied)
                        return true;
                    if (info.State != MemoryState.Commit)
                        return true;

                    if ((!opt_priv) && (info.Type == MemoryType.Private))
                        return true;

                    if ((!opt_img) && (info.Type == MemoryType.Image))
                        return true;

                    if ((!opt_map) && (info.Type == MemoryType.Mapped))
                        return true;

                    byte[] data = new byte[info.RegionSize.ToInt32()];
                    int bytesRead = 0;

                    CallSearchProgressChanged(
                        String.Format("Searching 0x{0} ({1} found)...", info.BaseAddress.ToString("x"), count));

                    try
                    {
                        bytesRead = phandle.ReadMemory(info.BaseAddress, data, data.Length);

                        if (bytesRead == 0)
                            return true;
                    }
                    catch
                    {
                        return true;
                    }

                    StringBuilder curstr = new StringBuilder();
                    bool isUnicode = false;
                    byte byte2 = 0;
                    byte byte1 = 0;

                    for (int i = 0; i < bytesRead; i++)
                    {
                        bool isChar = IsChar(data[i]);

                        if (unicode && isChar && isUnicode && byte1 != 0)
                        {
                            isUnicode = false;

                            if (curstr.Length > 0)
                                curstr.Remove(curstr.Length - 1, 1);

                            curstr.Append((char)data[i]);
                        }
                        else if (isChar)
                        {
                            curstr.Append((char)data[i]);
                        }
                        else if (unicode && data[i] == 0 && IsChar(byte1) && !IsChar(byte2))
                        {

                            isUnicode = true;
                        }
                        else if (unicode &&
                            data[i] == 0 && IsChar(byte1) && IsChar(byte2) && curstr.Length < minsize)
                        {

                            isUnicode = true;
                            curstr = new StringBuilder();
                            curstr.Append((char)byte1);
                        }
                        else
                        {
                            if (curstr.Length >= minsize)
                            {
                                int length = curstr.Length;

                                if (isUnicode)
                                    length *= 2;

                                Results.Add(new string[] { Utils.FormatAddress(info.BaseAddress),
                                    String.Format("0x{0:x}", i - length), length.ToString(),
                                    curstr.ToString() });

                                count++;
                            }

                            isUnicode = false;
                            curstr = new StringBuilder();
                        }

                        byte2 = byte1;
                        byte1 = data[i];
                    }

                    data = null;

                    return true;
                });

            phandle.Dispose();

            CallSearchFinished();
        }
Example #51
0
        public unsafe static void CopyProcessParameters(
            ProcessHandle processHandle,
            IntPtr peb,
            ProcessCreationFlags creationFlags,
            string imagePathName,
            string dllPath,
            string currentDirectory,
            string commandLine,
            EnvironmentBlock environment,
            string windowTitle,
            string desktopInfo,
            string shellInfo,
            string runtimeInfo,
            ref StartupInfo startupInfo
            )
        {
            UnicodeString imagePathNameStr;
            UnicodeString dllPathStr;
            UnicodeString currentDirectoryStr;
            UnicodeString commandLineStr;
            UnicodeString windowTitleStr;
            UnicodeString desktopInfoStr;
            UnicodeString shellInfoStr;
            UnicodeString runtimeInfoStr;

            // Create the unicode strings.

            imagePathNameStr = new UnicodeString(imagePathName);
            dllPathStr = new UnicodeString(dllPath);
            currentDirectoryStr = new UnicodeString(currentDirectory);
            commandLineStr = new UnicodeString(commandLine);
            windowTitleStr = new UnicodeString(windowTitle);
            desktopInfoStr = new UnicodeString(desktopInfo);
            shellInfoStr = new UnicodeString(shellInfo);
            runtimeInfoStr = new UnicodeString(runtimeInfo);

            try
            {
                NtStatus status;
                IntPtr processParameters;

                // Create the process parameter block.

                status = Win32.RtlCreateProcessParameters(
                    out processParameters,
                    ref imagePathNameStr,
                    ref dllPathStr,
                    ref currentDirectoryStr,
                    ref commandLineStr,
                    environment,
                    ref windowTitleStr,
                    ref desktopInfoStr,
                    ref shellInfoStr,
                    ref runtimeInfoStr
                    );

                if (status >= NtStatus.Error)
                    Win32.Throw(status);

                try
                {
                    // Allocate a new memory region in the remote process for 
                    // the environment block and copy it over.

                    int environmentLength;
                    IntPtr newEnvironment;

                    environmentLength = environment.GetLength();
                    newEnvironment = processHandle.AllocateMemory(
                        environmentLength,
                        MemoryProtection.ReadWrite
                        );

                    processHandle.WriteMemory(
                        newEnvironment,
                        environment,
                        environmentLength
                        );

                    // Copy over the startup info data.
                    RtlUserProcessParameters* paramsStruct = (RtlUserProcessParameters*)processParameters;

                    paramsStruct->Environment = newEnvironment;
                    paramsStruct->StartingX = startupInfo.X;
                    paramsStruct->StartingY = startupInfo.Y;
                    paramsStruct->CountX = startupInfo.XSize;
                    paramsStruct->CountY = startupInfo.YSize;
                    paramsStruct->CountCharsX = startupInfo.XCountChars;
                    paramsStruct->CountCharsY = startupInfo.YCountChars;
                    paramsStruct->FillAttribute = startupInfo.FillAttribute;
                    paramsStruct->WindowFlags = startupInfo.Flags;
                    paramsStruct->ShowWindowFlags = startupInfo.ShowWindow;

                    if ((startupInfo.Flags & StartupFlags.UseStdHandles) == StartupFlags.UseStdHandles)
                    {
                        paramsStruct->StandardInput = startupInfo.StdInputHandle;
                        paramsStruct->StandardOutput = startupInfo.StdOutputHandle;
                        paramsStruct->StandardError = startupInfo.StdErrorHandle;
                    }

                    // TODO: Add console support.

                    // Allocate a new memory region in the remote process for 
                    // the process parameters.

                    IntPtr newProcessParameters;
                    IntPtr regionSize = paramsStruct->Length.ToIntPtr();

                    newProcessParameters = processHandle.AllocateMemory(
                        IntPtr.Zero,
                        ref regionSize,
                        MemoryFlags.Commit,
                        MemoryProtection.ReadWrite
                        );

                    paramsStruct->MaximumLength = regionSize.ToInt32();

                    processHandle.WriteMemory(newProcessParameters, processParameters, paramsStruct->Length);

                    // Modify the process parameters pointer in the PEB.
                    processHandle.WriteMemory(
                        peb.Increment(Peb.ProcessParametersOffset),
                        &newProcessParameters,
                        IntPtr.Size
                        );
                }
                finally
                {
                    Win32.RtlDestroyProcessParameters(processParameters);
                }
            }
            finally
            {
                imagePathNameStr.Dispose();
                dllPathStr.Dispose();
                currentDirectoryStr.Dispose();
                commandLineStr.Dispose();
                windowTitleStr.Dispose();
                desktopInfoStr.Dispose();
                shellInfoStr.Dispose();
                runtimeInfoStr.Dispose();
            }
        }
Example #52
0
        public override void Search()
        {
            Results.Clear();

            byte[]        text = (byte[])Params["text"];
            ProcessHandle phandle;
            int           count = 0;

            int  minsize = (int)BaseConverter.ToNumberParse((string)Params["s_ms"]);
            bool unicode = (bool)Params["unicode"];

            bool opt_priv = (bool)Params["private"];
            bool opt_img  = (bool)Params["image"];
            bool opt_map  = (bool)Params["mapped"];

            try
            {
                phandle = new ProcessHandle(PID,
                                            ProcessAccess.QueryInformation |
                                            Program.MinProcessReadMemoryRights);
            }
            catch
            {
                CallSearchError("Could not open process: " + Win32.GetLastErrorMessage());
                return;
            }

            phandle.EnumMemory((info) =>
            {
                // skip unreadable areas
                if (info.Protect == MemoryProtection.AccessDenied)
                {
                    return(true);
                }
                if (info.State != MemoryState.Commit)
                {
                    return(true);
                }

                if ((!opt_priv) && (info.Type == MemoryType.Private))
                {
                    return(true);
                }

                if ((!opt_img) && (info.Type == MemoryType.Image))
                {
                    return(true);
                }

                if ((!opt_map) && (info.Type == MemoryType.Mapped))
                {
                    return(true);
                }

                byte[] data   = new byte[info.RegionSize.ToInt32()];
                int bytesRead = 0;

                CallSearchProgressChanged(
                    String.Format("Searching 0x{0} ({1} found)...", info.BaseAddress.ToString("x"), count));

                try
                {
                    bytesRead = phandle.ReadMemory(info.BaseAddress, data, data.Length);

                    if (bytesRead == 0)
                    {
                        return(true);
                    }
                }
                catch
                {
                    return(true);
                }

                StringBuilder curstr = new StringBuilder();
                bool isUnicode       = false;
                byte byte2           = 0;
                byte byte1           = 0;

                for (int i = 0; i < bytesRead; i++)
                {
                    bool isChar = IsChar(data[i]);

                    if (unicode && isChar && isUnicode && byte1 != 0)
                    {
                        isUnicode = false;

                        if (curstr.Length > 0)
                        {
                            curstr.Remove(curstr.Length - 1, 1);
                        }

                        curstr.Append((char)data[i]);
                    }
                    else if (isChar)
                    {
                        curstr.Append((char)data[i]);
                    }
                    else if (unicode && data[i] == 0 && IsChar(byte1) && !IsChar(byte2))
                    {
                        // skip null byte
                        isUnicode = true;
                    }
                    else if (unicode &&
                             data[i] == 0 && IsChar(byte1) && IsChar(byte2) && curstr.Length < minsize)
                    {
                        // ... [char] [char] *[null]* ([char] [null] [char] [null]) ...
                        //                   ^ we are here
                        isUnicode = true;
                        curstr    = new StringBuilder();
                        curstr.Append((char)byte1);
                    }
                    else
                    {
                        if (curstr.Length >= minsize)
                        {
                            int length = curstr.Length;

                            if (isUnicode)
                            {
                                length *= 2;
                            }

                            Results.Add(new string[] { Utils.FormatAddress(info.BaseAddress),
                                                       String.Format("0x{0:x}", i - length), length.ToString(),
                                                       curstr.ToString() });

                            count++;
                        }

                        isUnicode = false;
                        curstr    = new StringBuilder();
                    }

                    byte2 = byte1;
                    byte1 = data[i];
                }

                data = null;

                return(true);
            });

            phandle.Dispose();

            CallSearchFinished();
        }
Example #53
0
        private void SetDepStatusKph()
        {
            DepStatus depStatus = DepStatus.Enabled;

            if (comboStatus.SelectedItem.ToString() == "Disabled")
                depStatus = 0;
            else if (comboStatus.SelectedItem.ToString() == "Enabled")
                depStatus = DepStatus.Enabled;
            else if (comboStatus.SelectedItem.ToString() == "Enabled, DEP-ATL thunk emulation disabled")
                depStatus = DepStatus.Enabled | DepStatus.AtlThunkEmulationDisabled;
            else
            {
                PhUtils.ShowError("Invalid value.");
                return;
            }

            if (checkPermanent.Checked)
                depStatus |= DepStatus.Permanent;

            try
            {
                using (var phandle = new ProcessHandle(_pid, Program.MinProcessQueryRights))
                    phandle.SetDepStatus(depStatus);

                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to set the DEP status", ex);
            }
        }
        private void destroyMenuItem_Click(object sender, EventArgs e)
        {
            if (!PhUtils.ShowConfirmMessage(
                "destroy",
                "the selected heap",
                "Destroying a heap may cause the process to crash.",
                true
                ))
                return;

            try
            {
                using (var phandle = new ProcessHandle(_pid,
                    ProcessAccess.CreateThread | ProcessAccess.QueryInformation | ProcessAccess.VmOperation))
                {
                    // Use RtlCreateUserThread to cross session boundaries. RtlDestroyHeap doesn't need 
                    // the Win32 subsystem so we don't have to notify CSR.
                    phandle.CreateThread(
                        Win32.GetProcAddress(Win32.GetModuleHandle("ntdll.dll"), "RtlDestroyHeap"),
                        ((HeapInformation)listHeaps.SelectedItems[0].Tag).Address
                        ).Dispose();
                }

                listHeaps.SelectedItems[0].ForeColor = Color.Red;
                listHeaps.SelectedItems.Clear();
            }
            catch (WindowsException ex)
            {
                PhUtils.ShowException("Unable to destroy the heap", ex);
            }
        }
Example #55
0
        private void SetDepStatusNoKph()
        {
            if (comboStatus.SelectedItem.ToString().StartsWith("Enabled"))
                if (!PhUtils.ShowConfirmMessage(
                    "set",
                    "the DEP status",
                    "Enabling DEP in a process is a permanent action.",
                    false))
                    return;

            DepFlags flags = DepFlags.Enable;

            if (comboStatus.SelectedItem.ToString() == "Disabled")
                flags = DepFlags.Disable;
            else if (comboStatus.SelectedItem.ToString() == "Enabled")
                flags = DepFlags.Enable;
            else if (comboStatus.SelectedItem.ToString() == "Enabled, DEP-ATL thunk emulation disabled")
                flags = DepFlags.Enable | DepFlags.DisableAtlThunkEmulation;
            else
            {
                PhUtils.ShowError("Invalid value.");
                return;
            }

            try
            {
                IntPtr kernel32 = Win32.GetModuleHandle("kernel32.dll");
                IntPtr setProcessDepPolicy = Win32.GetProcAddress(kernel32, "SetProcessDEPPolicy");

                if (setProcessDepPolicy == IntPtr.Zero)
                    throw new Exception("This feature is not supported on your version of Windows.");

                using (ProcessHandle phandle = new ProcessHandle(_pid,
                    Program.MinProcessQueryRights | ProcessAccess.VmOperation |
                    ProcessAccess.VmRead | ProcessAccess.CreateThread))
                {
                    var thread = phandle.CreateThreadWin32(setProcessDepPolicy, new IntPtr((int)flags));

                    thread.Wait(1000 * Win32.TimeMsTo100Ns);

                    int exitCode = thread.GetExitCode();

                    if (exitCode == 0)
                    {
                        throw new Exception("Unspecified error.");
                    }
                }

                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to set the DEP status", ex);
            }
        }
Example #56
0
        private void freeMenuItem_Click(object sender, EventArgs e)
        {
            if (PhUtils.ShowConfirmMessage(
                "free",
                "the memory region",
                "Freeing memory regions may cause the process to crash.",
                true
                ))
            {
                try
                {
                    using (var phandle =
                        new ProcessHandle(_pid, ProcessAccess.VmOperation))
                    {
                        MemoryItem item = (MemoryItem)listMemory.SelectedItems[0].Tag;

                        phandle.FreeMemory(item.Address, (int)item.Size, false);
                    }
                }
                catch (Exception ex)
                {
                    PhUtils.ShowException("Unable to free the memory region", ex);
                }
            }
        }
Example #57
0
        private void dumpMemoryMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();

            sfd.FileName = "Memory.bin";
            sfd.Filter = "Binary Files (*.bin)|*.bin|All Files (*.*)|*.*";

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    using (var phandle = new ProcessHandle(_pid, ProcessAccess.VmRead))
                    using (var fhandle = FileHandle.CreateWin32(sfd.FileName, FileAccess.GenericWrite, FileShareMode.Read))
                    {
                        foreach (ListViewItem litem in listMemory.SelectedItems)
                        {
                            MemoryItem item = (MemoryItem)litem.Tag;

                            using (MemoryAlloc alloc = new MemoryAlloc((int)item.Size))
                            {
                                try
                                {
                                    unsafe
                                    {
                                        phandle.ReadMemory(item.Address, (IntPtr)alloc, (int)item.Size);
                                        fhandle.Write(alloc.Memory, (int)item.Size);
                                    }
                                }
                                catch (WindowsException)
                                { }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    PhUtils.ShowException("Unable to dump the selected memory regions", ex);
                }
            }
        }
Example #58
0
        private void DoFilter(string strFilter)
        {
            string lowerFilter = strFilter.ToLower();

            // Stop if cancel
            if (!CancelRequested)
            {
                var handles = Windows.GetHandles();
                Dictionary<int, ProcessHandle> processHandles = new Dictionary<int, ProcessHandle>();

                // Find handles
                for (int i = 0; i < handles.Length; i++)
                {
                    // Check for cancellation here too,
                    // otherwise the user might have to wait for much time                    
                    if (CancelRequested) return;

                    if (i % 20 == 0)
                        OnMatchProgress(i, handles.Length);

                    var handle = handles[i];

                    CompareHandleBestNameWithFilterString(processHandles, handle, lowerFilter);
                    // test Exception 
                    //if (i > 2000) throw new Exception("test");
                }

                foreach (ProcessHandle phandle in processHandles.Values)
                    phandle.Dispose();

                // Find DLLs and mapped files
                var processes = Windows.GetProcesses();

                foreach (var process in processes)
                {
                    try
                    {
                        using (var phandle = new ProcessHandle(process.Key,
                            Program.MinProcessQueryRights | Program.MinProcessReadMemoryRights))
                        {
                            phandle.EnumModules((module) =>
                            {
                                if (module.FileName.ToLower().Contains(lowerFilter))
                                    this.CallDllMatchListView(process.Key, module);
                                return true;
                            });
                        }

                        using (var phandle = new ProcessHandle(process.Key,
                            ProcessAccess.QueryInformation | Program.MinProcessReadMemoryRights))
                        {
                            phandle.EnumMemory((region) =>
                            {
                                if (region.Type != MemoryType.Mapped)
                                    return true;

                                string name = phandle.GetMappedFileName(region.BaseAddress);

                                if (name != null && name.ToLower().Contains(lowerFilter))
                                    this.CallMappedFileMatchListView(process.Key, region.BaseAddress, name);

                                return true;
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        Logging.Log(ex);
                    }
                }

                OnMatchListView(null);
            }
        }
Example #59
0
        private void listResults_DoubleClick(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            try
            {
                long s_a = (long)BaseConverter.ToNumberParse(_so.Searcher.Results[listResults.SelectedIndices[0]][0]) +
                    (long)BaseConverter.ToNumberParse(_so.Searcher.Results[listResults.SelectedIndices[0]][1]);

                var lastInfo = new MemoryBasicInformation();
                ProcessHandle phandle;

                try
                {
                    phandle = new ProcessHandle(_pid, ProcessAccess.QueryInformation);
                }
                catch
                {
                    this.Cursor = Cursors.Default;
                    return;
                }

                phandle.EnumMemory((info) =>
                    {
                        if (info.BaseAddress.ToInt64() > s_a)
                        {
                            long selectlength =
                                (long)BaseConverter.ToNumberParse(_so.Searcher.Results[listResults.SelectedIndices[0]][2]);

                            MemoryEditor ed = Program.GetMemoryEditor(_pid,
                                lastInfo.BaseAddress,
                                lastInfo.RegionSize.ToInt64(),
                                new Program.MemoryEditorInvokeAction(delegate(MemoryEditor f)
                                {
                                    try
                                    {
                                        f.ReadOnly = false;
                                        f.Activate();
                                        f.Select(s_a - lastInfo.BaseAddress.ToInt64(), selectlength);
                                    }
                                    catch
                                    { }
                                }));

                            return false;
                        }

                        lastInfo = info;

                        return true;
                    });
            }
            catch { }

            this.Cursor = Cursors.Default;
        }
        public HeapsWindow(int pid, HeapInformation[] heaps)
        {
            InitializeComponent();
            this.AddEscapeToClose();
            this.SetTopMost();

            listHeaps.AddShortcuts();
            listHeaps.ContextMenu = menuHeap;
            GenericViewMenu.AddMenuItems(copyMenuItem.MenuItems, listHeaps, null);

            // Native threads don't work properly on XP.
            if (OSVersion.IsBelowOrEqual(WindowsVersion.XP))
                destroyMenuItem.Visible = false;

            var comparer = new SortedListViewComparer(listHeaps);
            listHeaps.ListViewItemSorter = comparer;
            comparer.CustomSorters.Add(1, (l1, l2) =>
            {
                HeapInformation heap1 = l1.Tag as HeapInformation;
                HeapInformation heap2 = l2.Tag as HeapInformation;

                return heap1.BytesAllocated.CompareTo(heap2.BytesAllocated);
            });
            comparer.CustomSorters.Add(2, (l1, l2) =>
            {
                HeapInformation heap1 = l1.Tag as HeapInformation;
                HeapInformation heap2 = l2.Tag as HeapInformation;

                return heap1.BytesCommitted.CompareTo(heap2.BytesCommitted);
            });

            _pid = pid;

            IntPtr defaultHeap = IntPtr.Zero;

            try
            {
                using (var phandle = new ProcessHandle(
                    pid,
                    Program.MinProcessQueryRights | Program.MinProcessReadMemoryRights))
                    defaultHeap = phandle.GetHeap();
            }
            catch (WindowsException)
            { }

            long allocatedTotal = 0, committedTotal = 0;
            int entriesTotal = 0, tagsTotal = 0, pseudoTagsTotal = 0;

            foreach (HeapInformation heap in heaps)
            {
                ListViewItem litem = listHeaps.Items.Add(new ListViewItem(
                    new string[]
                    {
                        Utils.FormatAddress(heap.Address),
                        heap.BytesAllocated.ToString("N0") + " B",
                        heap.BytesCommitted.ToString("N0") + " B",
                        heap.EntryCount.ToString("N0")
                        //heap.TagCount.ToString("N0"),
                        //heap.PseudoTagCount.ToString("N0")
                    }));

                litem.Tag = heap;
                // Make the default heap bold.
                if (heap.Address == defaultHeap)
                    litem.Font = new Font(litem.Font, FontStyle.Bold);

                // Sum everything up.
                allocatedTotal += heap.BytesAllocated;
                committedTotal += heap.BytesCommitted;
                entriesTotal += heap.EntryCount;
                tagsTotal += heap.TagCount;
                pseudoTagsTotal += heap.PseudoTagCount;
            }

            // Totals row.
            listHeaps.Items.Add(new ListViewItem(
                new string[]
                {
                    "Totals",
                    allocatedTotal.ToString("N0") + " B",
                    committedTotal.ToString("N0") + " B",
                    entriesTotal.ToString("N0")
                    //tagsTotal.ToString("N0"),
                    //pseudoTagsTotal.ToString("N0")
                })).Tag = new HeapInformation(
                    IntPtr.Zero, allocatedTotal, committedTotal,
                    tagsTotal, entriesTotal, pseudoTagsTotal
                    );
        }