Esempio n. 1
0
        public ProcessMemoryStream(int processId, ProcessAccess desiredAccess = ProcessAccess.ReadWrite, int bufferSize = 4096, bool leaveOpen = false)
        {
            if (processId < 0)
                throw new ArgumentOutOfRangeException("Process ID must be a positive value");

            if (bufferSize < 1)
                throw new ArgumentOutOfRangeException("Buffer size must be at least 1 byte");

            var win32Flags = Win32ProcessAccess.VmOperation;

            // If read mode was requested, bitwise OR the flag
            if (desiredAccess.HasFlag(ProcessAccess.Read))
                win32Flags |= Win32ProcessAccess.VmRead;

            // If write mode was requested, bitwise OR the flag
            if (desiredAccess.HasFlag(ProcessAccess.Write))
                win32Flags |= Win32ProcessAccess.VmWrite;

            // Open the process and check if the handle is valid
            this.processAccess = desiredAccess;
            this.processHandle = NativeMethods.OpenProcess(win32Flags, false, processId);
            this.leaveOpen = leaveOpen;

            // Check if handle is valid
            if (this.processHandle.IsInvalid)
            {
                var errorCode = NativeMethods.GetLastError();
                throw new IOException("Unable to open process", errorCode);
            }

            // Allocate read and write buffers
            this.readBuffer = new byte[bufferSize];
            this.writeBuffer = new byte[bufferSize];
        }
Esempio n. 2
0
 public ProcessMemoryStream(int processId, ProcessAccess access)
 {
     this.access = access;
     this.ProcessId = processId;
     this.hProcess = Kernel32.OpenProcess(access, false, processId);
     if (this.hProcess == IntPtr.Zero)
     {
         throw new ArgumentException("Unable to open the process.");
     }
 }
        public ProcessMemoryAccessor(int processId, ProcessAccess access = ProcessAccess.ReadWrite)
        {
            this.processId = processId;
              this.processHandle = NativeMethods.OpenProcess(access.ToWin32Flags(), false, processId);

              if (processHandle == IntPtr.Zero)
              {
            var error = NativeMethods.GetLastError();
            throw new Win32Exception(error, "Unable to open process.");
              }

              this.access = access;
        }
        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;
            }
        }
Esempio n. 5
0
        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);
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Получение хандла с получением загруженных модулей процесса
        /// </summary>
        /// <param name="ProcessName">Имя процесса</param>
        /// <param name="Modules">Колекция модулей</param>
        public HMemory(string ProcessName, out Dictionary <string, HANDLE> Modules, ProcessAccess ProcessAccess)
        {
            this.ProcessName   = ProcessName;
            this.ProcessAccess = ProcessAccess;

            ProcessMemory = Process.GetProcessesByName(ProcessName);

            if (IsProcessActive())
            {
                ProcessHandle       = KernelAPI.OpenProcess(ProcessAccess, false, ProcessMemory[0].Id);
                ProcessWindowHandle = ProcessMemory[0].MainWindowHandle;

                Modules = GetProcessModule();
            }
            else
            {
                throw new Exception("Процесс не запущен!");
            }
        }
Esempio n. 7
0
        public ProcessMemoryStream(int processId, ProcessAccess desiredAccess = ProcessAccess.ReadWrite, int bufferSize = 4096, bool leaveOpen = false)
        {
            if (processId < 0)
            {
                throw new ArgumentOutOfRangeException("Process ID must be a positive value");
            }

            if (bufferSize < 1)
            {
                throw new ArgumentOutOfRangeException("Buffer size must be at least 1 byte");
            }

            var win32Flags = Win32ProcessAccess.VmOperation;

            // If read mode was requested, bitwise OR the flag
            if (desiredAccess.HasFlag(ProcessAccess.Read))
            {
                win32Flags |= Win32ProcessAccess.VmRead;
            }

            // If write mode was requested, bitwise OR the flag
            if (desiredAccess.HasFlag(ProcessAccess.Write))
            {
                win32Flags |= Win32ProcessAccess.VmWrite;
            }

            // Open the process and check if the handle is valid
            this.processAccess = desiredAccess;
            this.processHandle = NativeMethods.OpenProcess(win32Flags, false, processId);
            this.leaveOpen     = leaveOpen;

            // Check if handle is valid
            if (this.processHandle.IsInvalid)
            {
                var errorCode = NativeMethods.GetLastError();
                throw new IOException("Unable to open process", errorCode);
            }

            // Allocate read and write buffers
            this.readBuffer  = new byte[bufferSize];
            this.writeBuffer = new byte[bufferSize];
        }
Esempio n. 8
0
        static OSVersion()
        {
            System.Version version = Environment.OSVersion.Version;

            if (version.Major == 5 && version.Minor == 1)
                _windowsVersion = WindowsVersion.XP;
            else if (version.Major == 5 && version.Minor == 2)
                _windowsVersion = WindowsVersion.Server2003;
            else if (version.Major == 6 && version.Minor == 0)
                _windowsVersion = WindowsVersion.Vista;
            else if (version.Major == 6 && version.Minor == 1)
                _windowsVersion = WindowsVersion.Seven;
            else if ((version.Major == 6 && version.Minor > 1) || version.Major > 6)
                _windowsVersion = WindowsVersion.Unreleased;

            if (IsBelow(WindowsVersion.Vista))
            {
                _hasSetAccessToken = true;
            }

            if (IsAboveOrEqual(WindowsVersion.Vista))
            {
                _minProcessQueryInfoAccess = ProcessAccess.QueryLimitedInformation;
                _minThreadQueryInfoAccess = ThreadAccess.QueryLimitedInformation;
                _minThreadSetInfoAccess = ThreadAccess.SetLimitedInformation;

                _hasCycleTime = true;
                _hasProtectedProcesses = true;
                _hasPsSuspendResumeProcess = true;
                _hasQueryLimitedInformation = true;
                _hasTaskDialogs = true;
                _hasUac = true;
                _hasWin32ImageFileName = true;
            }

            if (IsAboveOrEqual(WindowsVersion.Seven))
            {
                _hasExtendedTaskbar = true;
            }
        }
Esempio n. 9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="dwAccess"></param>
        /// <param name="bInherit"></param>
        /// <param name="dwProcessId"></param>
        /// <returns></returns>
        public static IntPtr OpenProcess(ProcessAccess dwAccess, bool bInherit, int dwProcessId, [CallerMemberName] string callerName = "")
        {
            if (!PInvokeDebugger.LoggingEnabled)
            {
                return(PInvoke_OpenProcess(dwAccess, bInherit, dwProcessId));
            }

            IntPtr           returnValue = PInvoke_OpenProcess(dwAccess, bInherit, dwProcessId);
            PInvokeDebugInfo debugInfo   = PInvokeDebugInfo.TraceDebugInfo(
                ModuleName,
                nameof(OpenProcess),
                callerName,
                returnValue,
                IntPtr.Zero,
                nameof(dwAccess), dwAccess,
                nameof(bInherit), bInherit,
                nameof(dwProcessId), dwProcessId
                );

            PInvokeDebugger.SafeCapture(debugInfo);
            return(returnValue);
        }
Esempio n. 10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ProcessHandle"></param>
        /// <param name="Access"></param>
        /// <param name="ObjectAttributes"></param>
        /// <param name="Cid"></param>
        /// <returns></returns>
        public static NTSTATUS NtOpenProcess(ref IntPtr ProcessHandle, ProcessAccess Access, ref ObjectAttributes ObjectAttributes, ref ClientId Cid, [CallerMemberName] string callerName = "")
        {
            if (!PInvokeDebugger.LoggingEnabled)
            {
                return(PInvoke_NtOpenProcess(ref ProcessHandle, Access, ref ObjectAttributes, ref Cid));
            }

            NTSTATUS         returnValue = PInvoke_NtOpenProcess(ref ProcessHandle, Access, ref ObjectAttributes, ref Cid);
            PInvokeDebugInfo debugInfo   = PInvokeDebugInfo.TraceDebugInfo(
                ModuleName,
                nameof(NtOpenProcess),
                callerName,
                returnValue,
                nameof(ProcessHandle), ProcessHandle,
                nameof(Access), Access,
                nameof(ObjectAttributes), ObjectAttributes,
                nameof(Cid), Cid
                );

            PInvokeDebugger.SafeCapture(debugInfo);
            return(returnValue);
        }
Esempio n. 11
0
        public WindowsProcessRamIO(Process process, Emulator emulator) : base()
        {
            _process  = process;
            _emulator = emulator;

            _process.EnableRaisingEvents = true;

            ProcessAccess accessFlags = ProcessAccess.PROCESS_QUERY_LIMITED_INFORMATION | ProcessAccess.SUSPEND_RESUME
                                        | ProcessAccess.VM_OPERATION | ProcessAccess.VM_READ | ProcessAccess.VM_WRITE;

            _processHandle = ProcessGetHandleFromId(accessFlags, false, _process.Id);
            try
            {
                CalculateOffset();
            }
            catch (Exception e)
            {
                CloseProcess(_processHandle);
                throw e;
            }

            _process.Exited += _process_Exited;
        }
        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);
                }
            }
        }
Esempio n. 13
0
        static OSVersion()
        {
            System.Version version = Environment.OSVersion.Version;

            if (version.Major == 5 && version.Minor == 0)
                _windowsVersion = WindowsVersion.TwoThousand;
            else if (version.Major == 5 && version.Minor == 1)
                _windowsVersion = WindowsVersion.XP;
            else if (version.Major == 5 && version.Minor == 2)
                _windowsVersion = WindowsVersion.Server2003;
            else if (version.Major == 6 && version.Minor == 0)
                _windowsVersion = WindowsVersion.Vista;
            else if (version.Major == 6 && version.Minor == 1)
                _windowsVersion = WindowsVersion.Seven;
            else
                _windowsVersion = WindowsVersion.Unknown;

            if (_windowsVersion != WindowsVersion.Unknown)
            {
                if (IsAboveOrEqual(WindowsVersion.XP))
                {
                    _hasThemes = true;
                }

                if (IsBelow(WindowsVersion.Vista))
                {
                    _hasSetAccessToken = true;
                }

                if (IsAboveOrEqual(WindowsVersion.Vista))
                {
                    _minProcessQueryInfoAccess = ProcessAccess.QueryLimitedInformation;
                    _minThreadQueryInfoAccess = ThreadAccess.QueryLimitedInformation;
                    _minThreadSetInfoAccess = ThreadAccess.SetLimitedInformation;

                    _hasCycleTime = true;
                    _hasIoPriority = true;
                    _hasPagePriority = true;
                    _hasProtectedProcesses = true;
                    _hasPsSuspendResumeProcess = true;
                    _hasQueryLimitedInformation = true;
                    _hasTaskDialogs = true;
                    _hasUac = true;
                    _hasWin32ImageFileName = true;
                }

                if (IsAboveOrEqual(WindowsVersion.Seven))
                {
                    _hasExtendedTaskbar = true;
                }
            }

            _versionString = Environment.OSVersion.VersionString;
        }
Esempio n. 14
0
 private static extern IntPtr OpenProcess(ProcessAccess processAccess, Boolean bInheritHandle, Int32 processId);
Esempio n. 15
0
 internal static IntPtr OpenProcess(Process proc, ProcessAccess flags = ProcessAccess.All)
 {
     return(OpenProcess(flags, false, proc.Id));
 }
Esempio n. 16
0
 public static extern IntPtr OpenProcess(ProcessAccess dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, int dwProcessId);
Esempio n. 17
0
        private static bool ElevateIfRequired(IWin32Window window, int[] pids, string[] names,
            ProcessAccess access, string action)
        {
            ElevationAction result;

            result = PromptForElevation(window, pids, names, access, "elevate the action", action);

            if (result == ElevationAction.NotRequired || result == ElevationAction.DontElevate)
            {
                return false;
            }
            else if (result == ElevationAction.Cancel)
            {
                return true;
            }
            else if (result == ElevationAction.Elevate)
            {
                string objects = "";

                foreach (int pid in pids)
                    objects += pid + ",";

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

                return true;
            }
            else
            {
                return false;
            }
        }
Esempio n. 18
0
 public ProcessMemoryStream(IntPtr processHandle, ProcessAccess access = ProcessAccess.ReadWrite, bool leaveOpen = true)
 {
     this.access = access;
       this.processHandle = processHandle;
       this.leaveOpen = leaveOpen;
 }
Esempio n. 19
0
        public void ProtectAdd(ProcessHandle processHandle, bool allowKernelMode, ProcessAccess ProcessAllowMask, ThreadAccess ThreadAllowMask)
        {
            byte* inData = stackalloc byte[16];

            *(int*)inData = processHandle;
            *(int*)(inData + 0x4) = allowKernelMode ? 1 : 0;
            *(int*)(inData + 0x8) = (int)ProcessAllowMask;
            *(int*)(inData + 0xc) = (int)ThreadAllowMask;

            _fileHandle.IoControl(CtlCode(Control.ProtectAdd), inData, 16, null, 0);
        }
Esempio n. 20
0
 public static extern IntPtr OpenProcess(ProcessAccess dwDesiredAccess, bool bInheritHandle, int dwProcessId);
Esempio n. 21
0
        public void ProtectQuery(ProcessHandle processHandle, out bool AllowKernelMode, out ProcessAccess ProcessAllowMask, out ThreadAccess ThreadAllowMask)
        {
            byte* inData = stackalloc byte[16];
            int allowKernelMode;
            ProcessAccess processAllowMask;
            ThreadAccess threadAllowMask;

            *(int*)inData = processHandle;
            *(int*)(inData + 0x4) = (int)&allowKernelMode;
            *(int*)(inData + 0x8) = (int)&processAllowMask;
            *(int*)(inData + 0xc) = (int)&threadAllowMask;

            _fileHandle.IoControl(CtlCode(Control.ProtectQuery), inData, 16, null, 0);

            AllowKernelMode = allowKernelMode != 0;
            ProcessAllowMask = processAllowMask;
            ThreadAllowMask = threadAllowMask;
        }
Esempio n. 22
0
        public int KphOpenThreadProcess(ThreadHandle threadHandle, ProcessAccess desiredAccess)
        {
            byte* inData = stackalloc byte[8];
            byte* outData = stackalloc byte[4];

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

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

            return *(int*)outData;
        }
 public IntPtr OpenRemoteProcess(IntPtr pid, ProcessAccess desiredAccess)
 {
     return(openRemoteProcessDelegate(pid, desiredAccess));
 }
Esempio n. 24
0
		public SafeObjectHandle OpenProcess(
            ProcessAccess dwDesiredAccess,
            bool bInheritHandle,
            uint dwProcessId)
			=> OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId);
Esempio n. 25
0
 public static extern IntPtr OpenProcess(ProcessAccess access, bool inherit, int processId);
Esempio n. 26
0
 public static extern SafeObjectHandle OpenProcess(
     ProcessAccess dwDesiredAccess,
     bool bInheritHandle,
     int dwProcessId);
Esempio n. 27
0
 public static extern IntPtr OpenProcess(ProcessAccess Access, bool InheritHandle, int PID);
Esempio n. 28
0
 public static IntPtr OpenProcess(ProcessAccess processAccess, bool v, int id)
 => OpenProcess((int)processAccess, v, id);
Esempio n. 29
0
        private static ElevationAction PromptForElevation(IWin32Window window, int[] pids, string[] names,
                                                          ProcessAccess access, string elevateAction, string action)
        {
            if (Settings.Instance.ElevationLevel == (int)ElevationLevel.Never)
            {
                return(ElevationAction.NotRequired);
            }

            if (
                OSVersion.HasUac &&
                Program.ElevationType == ProcessHacker.Native.Api.TokenElevationType.Limited &&
                KProcessHacker.Instance == null
                )
            {
                try
                {
                    foreach (int pid in pids)
                    {
                        using (var phandle = new ProcessHandle(pid, access))
                        { }
                    }
                }
                catch (WindowsException ex)
                {
                    if (ex.ErrorCode != Win32Error.AccessDenied)
                    {
                        return(ElevationAction.NotRequired);
                    }

                    if (Settings.Instance.ElevationLevel == (int)ElevationLevel.Elevate)
                    {
                        return(ElevationAction.Elevate);
                    }

                    TaskDialog td = new TaskDialog();

                    td.WindowTitle     = "Process Hacker";
                    td.MainIcon        = TaskDialogIcon.Warning;
                    td.MainInstruction = "Do you want to " + elevateAction + "?";
                    td.Content         = "The action cannot be performed in the current security context. " +
                                         "Do you want Process Hacker to prompt for the appropriate credentials and " + elevateAction + "?";

                    td.ExpandedInformation = "Error: " + ex.Message + " (0x" + ex.ErrorCode.ToString("x") + ")";
                    td.ExpandFooterArea    = true;

                    td.Buttons = new TaskDialogButton[]
                    {
                        new TaskDialogButton((int)DialogResult.Yes, "Elevate\nPrompt for credentials and " + elevateAction + "."),
                        new TaskDialogButton((int)DialogResult.No, "Continue\nAttempt to perform the action without elevation.")
                    };
                    td.CommonButtons   = TaskDialogCommonButtons.Cancel;
                    td.UseCommandLinks = true;
                    td.Callback        = (taskDialog, args, userData) =>
                    {
                        if (args.Notification == TaskDialogNotification.Created)
                        {
                            taskDialog.SetButtonElevationRequiredState((int)DialogResult.Yes, true);
                        }

                        return(false);
                    };

                    DialogResult result = (DialogResult)td.Show(window);

                    if (result == DialogResult.Yes)
                    {
                        return(ElevationAction.Elevate);
                    }
                    else if (result == DialogResult.No)
                    {
                        return(ElevationAction.DontElevate);
                    }
                    else if (result == DialogResult.Cancel)
                    {
                        return(ElevationAction.Cancel);
                    }
                }
            }

            return(ElevationAction.NotRequired);
        }
Esempio n. 30
0
        private static ElevationAction PromptForElevation(IWin32Window window, int[] pids, string[] names,
            ProcessAccess access, string elevateAction, string action)
        {
            if (Settings.Instance.ElevationLevel == (int)ElevationLevel.Never)
                return ElevationAction.NotRequired;

            if (
                OSVersion.HasUac &&
                Program.ElevationType == ProcessHacker.Native.Api.TokenElevationType.Limited &&
                KProcessHacker.Instance == null
                )
            {
                try
                {
                    foreach (int pid in pids)
                    {
                        using (var phandle = new ProcessHandle(pid, access))
                        { }
                    }
                }
                catch (WindowsException ex)
                {
                    if (ex.ErrorCode != Win32Error.AccessDenied)
                        return ElevationAction.NotRequired;

                    if (Settings.Instance.ElevationLevel == (int)ElevationLevel.Elevate)
                        return ElevationAction.Elevate;

                    TaskDialog td = new TaskDialog();

                    td.WindowTitle = "Process Hacker";
                    td.MainIcon = TaskDialogIcon.Warning;
                    td.MainInstruction = "Do you want to " + elevateAction + "?";
                    td.Content = "The action cannot be performed in the current security context. " +
                        "Do you want Process Hacker to prompt for the appropriate credentials and " + elevateAction + "?";

                    td.ExpandedInformation = "Error: " + ex.Message + " (0x" + ex.ErrorCode.ToString("x") + ")";
                    td.ExpandFooterArea = true;

                    td.Buttons = new TaskDialogButton[]
                    {
                        new TaskDialogButton((int)DialogResult.Yes, "Elevate\nPrompt for credentials and " + elevateAction + "."),
                        new TaskDialogButton((int)DialogResult.No, "Continue\nAttempt to perform the action without elevation.")
                    };
                    td.CommonButtons = TaskDialogCommonButtons.Cancel;
                    td.UseCommandLinks = true;
                    td.Callback = (taskDialog, args, userData) =>
                    {
                        if (args.Notification == TaskDialogNotification.Created)
                        {
                            taskDialog.SetButtonElevationRequiredState((int)DialogResult.Yes, true);
                        }

                        return false;
                    };

                    DialogResult result = (DialogResult)td.Show(window);

                    if (result == DialogResult.Yes)
                    {
                        return ElevationAction.Elevate;
                    }
                    else if (result == DialogResult.No)
                    {
                        return ElevationAction.DontElevate;
                    }
                    else if (result == DialogResult.Cancel)
                    {
                        return ElevationAction.Cancel;
                    }
                }
            }

            return ElevationAction.NotRequired;
        }
Esempio n. 31
0
 internal static extern IntPtr OpenProcess(ProcessAccess desiredAccess, bool inheritHandle, int processId);
Esempio n. 32
0
        public static void Main(string[] args)
        {
            Dictionary<string, string> pArgs;

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

            if (Environment.Version.Major < 2)
            {
                PhUtils.ShowError("You must have .NET Framework 2.0 or higher to use Process Hacker.");
                Environment.Exit(1);
            }

            // Check OS support.
            if (OSVersion.IsBelow(WindowsVersion.TwoThousand) || OSVersion.IsAbove(WindowsVersion.Eight))
            {
                PhUtils.ShowWarning("Your operating system is not supported by Process Hacker.");
            }
#if !DEBUG
            // Setup exception handling at first opportunity.
            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException, true);
#endif
            try
            {
                pArgs = ParseArgs(args);
            }
            catch
            {
                ShowCommandLineUsage();
                pArgs = new Dictionary<string, string>();
            }

            try
            {
                if (
                    // Only load KPH if it's enabled.
                    Settings.Instance.EnableKPH && !NoKph &&
                    // Don't load KPH if we're going to install/uninstall it.
                    !pArgs.ContainsKey("-installkph") && !pArgs.ContainsKey("-uninstallkph")
                    )
                    KProcessHacker2.Instance = new KProcessHacker2();
            }
            catch
            { }


            if (pArgs.ContainsKey("-h") || pArgs.ContainsKey("-help") || pArgs.ContainsKey("-?"))
            {
                ShowCommandLineUsage();
                return;
            }

            if (pArgs.ContainsKey("-elevate"))
            {
                // Propagate arguments.
                pArgs.Remove("-elevate");
                StartProcessHackerAdmin(Utils.JoinCommandLine(pArgs), null);
                return;
            }

            LoadSettings(!pArgs.ContainsKey("-nosettings"), pArgs.ContainsKey("-settings") ? pArgs["-settings"] : null);

            try
            {
                if (pArgs.ContainsKey("-nokph"))
                    NoKph = true;
                if (Settings.Instance.AllowOnlyOneInstance && 
                    !(pArgs.ContainsKey("-e") || pArgs.ContainsKey("-o") ||
                    pArgs.ContainsKey("-pw") || pArgs.ContainsKey("-pt"))
                    )
                    ActivatePreviousInstance();
            }
            catch
            { }

            WorkQueue.GlobalWorkQueue.MaxWorkerThreads = Environment.ProcessorCount;

            // Create or open the Process Hacker mutex, used only by the installer.
            try
            {
                GlobalMutex = new ProcessHacker.Native.Threading.Mutant(GlobalMutexName);
            }
            catch (Exception ex)
            {
                Logging.Log(ex);
            }

            try
            {
                using (TokenHandle thandle = ProcessHandle.Current.GetToken())
                {
                    thandle.TrySetPrivilege("SeDebugPrivilege", SePrivilegeAttributes.Enabled);
                    thandle.TrySetPrivilege("SeIncreaseBasePriorityPrivilege", SePrivilegeAttributes.Enabled);
                    thandle.TrySetPrivilege("SeLoadDriverPrivilege", SePrivilegeAttributes.Enabled);
                    thandle.TrySetPrivilege("SeRestorePrivilege", SePrivilegeAttributes.Enabled);
                    thandle.TrySetPrivilege("SeShutdownPrivilege", SePrivilegeAttributes.Enabled);
                    thandle.TrySetPrivilege("SeTakeOwnershipPrivilege", SePrivilegeAttributes.Enabled);

                    if (OSVersion.HasUac)
                    {
                        try { ElevationType = thandle.ElevationType; }
                        catch { ElevationType = TokenElevationType.Full; }

                        if (ElevationType == TokenElevationType.Default &&
                            !(new WindowsPrincipal(WindowsIdentity.GetCurrent())).
                                IsInRole(WindowsBuiltInRole.Administrator))
                            ElevationType = TokenElevationType.Limited;
                        else if (ElevationType == TokenElevationType.Default)
                            ElevationType = TokenElevationType.Full;
                    }
                    else
                    {
                        ElevationType = TokenElevationType.Full;
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.Log(ex);
            }

            MinProcessQueryRights = OSVersion.MinProcessQueryInfoAccess;
            MinThreadQueryRights = OSVersion.MinThreadQueryInfoAccess;

            //if (KProcessHacker2.Instance != null)
            //{
            //    MinProcessGetHandleInformationRights = MinProcessQueryRights;
            //    MinProcessReadMemoryRights = MinProcessQueryRights;
            //    MinProcessWriteMemoryRights = MinProcessQueryRights;
            //}

            try
            {
                CurrentUsername = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            }
            catch (Exception ex)
            {
                Logging.Log(ex);
            }

            try
            {
                CurrentProcessId = Win32.GetCurrentProcessId();
                CurrentSessionId = Win32.GetProcessSessionId(Win32.GetCurrentProcessId());
                Thread.CurrentThread.Priority = ThreadPriority.Highest;
            }
            catch (Exception ex)
            {
                Logging.Log(ex);
            }

            if (ProcessCommandLine(pArgs))
                return;

            Win32.FileIconInit(true);
            LoadProviders();
            Windows.GetProcessName = pid => 
                ProcessProvider.Dictionary.ContainsKey(pid) ? 
                ProcessProvider.Dictionary[pid].Name :
                null;

            // Create the shared waiter.
            SharedWaiter = new ProcessHacker.Native.Threading.Waiter();

            HackerWindow = new HackerWindow();
            Application.Run();
        }
Esempio n. 33
0
 internal static extern IntPtr PInvoke_OpenProcess(ProcessAccess dwAccess, bool bInherit, int dwProcessId);
Esempio n. 34
0
 private static extern IntPtr OpenProcess(ProcessAccess dwDesiredAccess, bool bInheritHandle,
                                          int processId);
        private ProcessHandle OpenProcess(int pid, ProcessAccess access)
        {
            switch (comboMethod.SelectedItem.ToString())
            {
                case "Brute Force":
                    return new ProcessHandle(pid, access);
                case "CSR Handles":
                    return this.OpenProcessCsr(pid, access);
            }

            return null;
        }
Esempio n. 36
0
 internal static IntPtr OpenCurrentProcess(ProcessAccess flags = ProcessAccess.All)
 {
     return(OpenProcess(Process.GetCurrentProcess(), flags));
 }
Esempio n. 37
0
 private static extern IntPtr TryOpenProcessNative(ProcessAccess dwDesiredAccess,
                                                   [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, int dwProcessId);
        private ProcessHandle OpenProcessCsr(int pid, ProcessAccess access)
        {
            var csrProcesses = this.GetCsrProcesses();

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

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

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

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

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

                csrProcess.Dispose();
            }

            throw new Exception("Could not find process (hidden from handle table).");
        }
Esempio n. 39
0
        static OSVersion()
        {
            System.Version version = Environment.OSVersion.Version;

            if (version.Major == 5 && version.Minor == 0)
            {
                _windowsVersion = WindowsVersion.TwoThousand;
            }
            else if (version.Major == 5 && version.Minor == 1)
            {
                _windowsVersion = WindowsVersion.XP;
            }
            else if (version.Major == 5 && version.Minor == 2)
            {
                _windowsVersion = WindowsVersion.Server2003;
            }
            else if (version.Major == 6 && version.Minor == 0)
            {
                _windowsVersion = WindowsVersion.Vista;
            }
            else if (version.Major == 6 && version.Minor == 1)
            {
                _windowsVersion = WindowsVersion.Seven;
            }
            else
            {
                _windowsVersion = WindowsVersion.Unknown;
            }

            if (_windowsVersion != WindowsVersion.Unknown)
            {
                if (IsAboveOrEqual(WindowsVersion.XP))
                {
                    _hasThemes = true;
                }

                if (IsBelow(WindowsVersion.Vista))
                {
                    _hasSetAccessToken = true;
                }

                if (IsAboveOrEqual(WindowsVersion.Vista))
                {
                    _minProcessQueryInfoAccess = ProcessAccess.QueryLimitedInformation;
                    _minThreadQueryInfoAccess  = ThreadAccess.QueryLimitedInformation;
                    _minThreadSetInfoAccess    = ThreadAccess.SetLimitedInformation;

                    _hasCycleTime               = true;
                    _hasIoPriority              = true;
                    _hasPagePriority            = true;
                    _hasProtectedProcesses      = true;
                    _hasPsSuspendResumeProcess  = true;
                    _hasQueryLimitedInformation = true;
                    _hasTaskDialogs             = true;
                    _hasUac = true;
                    _hasWin32ImageFileName = true;
                }

                if (IsAboveOrEqual(WindowsVersion.Seven))
                {
                    _hasExtendedTaskbar = true;
                }
            }

            _versionString = Environment.OSVersion.VersionString;
        }
        private ProcessHandle OpenProcessCsr(int pid, ProcessAccess access)
        {
            var csrProcesses = this.GetCsrProcesses();

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

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

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

            //                if (tid == 0)
            //                    throw new Exception();

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

                csrProcess.Dispose();
            }

            throw new Exception("Could not find process (hidden from handle table).");
        }
Esempio n. 41
0
 private static extern SafeMemoryHandle OpenProcess(
     ProcessAccess dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, int dwProcessId);
Esempio n. 42
0
 public static IntPtr OpenProcess(ProcessAccess dwDesiredAccess,
                                  [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, int dwProcessId)
 {
     return(TryOpenProcessNative(dwDesiredAccess, bInheritHandle, dwProcessId));
 }
Esempio n. 43
0
 /// <summary>
 /// Получение хандла с получением загруженных модулей процесса
 /// </summary>
 /// <param name="ProcessName">Имя процесса</param>
 /// <param name="Modules">Колекция модулей</param>
 public OldMemory(string ProcessName, out Dictionary <string, HANDLE> Modules, ProcessAccess ProcessAccess) : base(ProcessName, out Modules, ProcessAccess)
 {
 }
Esempio n. 44
0
 internal static extern NTSTATUS PInvoke_NtOpenProcess(ref IntPtr ProcessHandle, ProcessAccess Access, ref ObjectAttributes ObjectAttributes, ref ClientId Cid);
Esempio n. 45
0
 public static extern IntPtr OpenProcess(ProcessAccess access, bool inheritHandle, int processId);
Esempio n. 46
0
        public static void Main(string[] args)
        {
            Dictionary<string, string> pArgs = null;

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

            if (Environment.Version.Major < 2)
            {
                PhUtils.ShowError("You must have .NET Framework 2.0 or higher to use Process Hacker.");
                Environment.Exit(1);
            }

            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException, true);

            try
            {
                pArgs = ParseArgs(args);
            }
            catch
            {
                ShowCommandLineUsage();
                pArgs = new Dictionary<string, string>();
            }

            if (pArgs.ContainsKey("-h") || pArgs.ContainsKey("-help") || pArgs.ContainsKey("-?"))
            {
                ShowCommandLineUsage();
                return;
            }

            if (pArgs.ContainsKey("-recovered"))
            {
                ProcessHackerRestartRecovery.ApplicationRestartRecoveryManager.RecoverLastSession();
            }

            if (pArgs.ContainsKey("-elevate"))
            {
                StartProcessHackerAdmin();
                return;
            }

            try
            {
                if (pArgs.ContainsKey("-nokph"))
                    NoKph = true;
                if (Properties.Settings.Default.AllowOnlyOneInstance &&
                    !(pArgs.ContainsKey("-e") || pArgs.ContainsKey("-o") ||
                    pArgs.ContainsKey("-pw") || pArgs.ContainsKey("-pt"))
                    )
                    CheckForPreviousInstance();
            }
            catch
            { }

            try
            {
                if (Properties.Settings.Default.NeedsUpgrade)
                {
                    try
                    {
                        Properties.Settings.Default.Upgrade();
                    }
                    catch (Exception ex)
                    {
                        Logging.Log(ex);
                        PhUtils.ShowWarning("Process Hacker could not upgrade its settings from a previous version.");
                    }

                    Properties.Settings.Default.NeedsUpgrade = false;
                }
            }
            catch
            { }

            VerifySettings();

            ThreadPool.SetMinThreads(1, 1);
            ThreadPool.SetMaxThreads(2, 2);
            WorkQueue.GlobalWorkQueue.MaxWorkerThreads = 3;

            try
            {
                GlobalMutex = new ProcessHacker.Native.Threading.Mutant(GlobalMutexName);
            }
            catch (Exception ex)
            {
                Logging.Log(ex);
            }

            try
            {
                using (var thandle = ProcessHandle.GetCurrent().GetToken())
                {
                    try { thandle.SetPrivilege("SeDebugPrivilege", SePrivilegeAttributes.Enabled); }
                    catch { }
                    try { thandle.SetPrivilege("SeIncreaseBasePriorityPrivilege", SePrivilegeAttributes.Enabled); }
                    catch { }
                    try { thandle.SetPrivilege("SeLoadDriverPrivilege", SePrivilegeAttributes.Enabled); }
                    catch { }
                    try { thandle.SetPrivilege("SeRestorePrivilege", SePrivilegeAttributes.Enabled); }
                    catch { }
                    try { thandle.SetPrivilege("SeShutdownPrivilege", SePrivilegeAttributes.Enabled); }
                    catch { }
                    try { thandle.SetPrivilege("SeTakeOwnershipPrivilege", SePrivilegeAttributes.Enabled); }
                    catch { }

                    if (OSVersion.HasUac)
                    {
                        try { ElevationType = thandle.GetElevationType(); }
                        catch { ElevationType = TokenElevationType.Full; }

                        if (ElevationType == TokenElevationType.Default &&
                            !(new WindowsPrincipal(WindowsIdentity.GetCurrent())).
                                IsInRole(WindowsBuiltInRole.Administrator))
                            ElevationType = TokenElevationType.Limited;
                        else if (ElevationType == TokenElevationType.Default)
                            ElevationType = TokenElevationType.Full;
                    }
                    else
                    {
                        ElevationType = TokenElevationType.Full;
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.Log(ex);
            }

            try
            {
                if (

                    IntPtr.Size == 4 &&
                    Properties.Settings.Default.EnableKPH &&
                    !NoKph &&

                    !pArgs.ContainsKey("-installkph") && !pArgs.ContainsKey("-uninstallkph")
                    )
                    KProcessHacker.Instance = new KProcessHacker("KProcessHacker");
            }
            catch
            { }

            MinProcessQueryRights = OSVersion.MinProcessQueryInfoAccess;
            MinThreadQueryRights = OSVersion.MinThreadQueryInfoAccess;

            if (KProcessHacker.Instance != null)
            {
                MinProcessGetHandleInformationRights = MinProcessQueryRights;
                MinProcessReadMemoryRights = MinProcessQueryRights;
                MinProcessWriteMemoryRights = MinProcessQueryRights;
            }

            try
            {
                CurrentUsername = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            }
            catch (Exception ex)
            {
                Logging.Log(ex);
            }

            try
            {
                CurrentProcessId = Win32.GetCurrentProcessId();
                CurrentSessionId = Win32.GetProcessSessionId(Win32.GetCurrentProcessId());
                System.Threading.Thread.CurrentThread.Priority = ThreadPriority.Highest;
            }
            catch (Exception ex)
            {
                Logging.Log(ex);
            }

            if (ProcessCommandLine(pArgs))
                return;

            Win32.FileIconInit(true);
            LoadProviders();
            Windows.GetProcessName = (pid) =>
                ProcessProvider.Dictionary.ContainsKey(pid) ?
                ProcessProvider.Dictionary[pid].Name :
                null;

            SharedWaiter = new ProcessHacker.Native.Threading.Waiter();

            new HackerWindow();
            Application.Run();
        }
        public IntPtr KphOpenProcess(int pid, ProcessAccess desiredAccess)
        {
            KphOpenProcessInput input;
            IntPtr processHandle;
            ClientId clientId;

            clientId.UniqueProcess = (IntPtr)pid;
            clientId.UniqueThread = IntPtr.Zero;

            input.ProcessHandle = &processHandle;
            input.DesiredAccess = (int)desiredAccess;
            input.ClientId = &clientId;
            _fileHandle.IoControl(IoCtlOpenProcess, &input, sizeof(KphOpenProcessInput), null, 0);

            return processHandle;
        }
Esempio n. 48
0
 public static extern IntPtr OpenProcess(ProcessAccess dwDesiredAccess,
                                         [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, int dwProcessId);
Esempio n. 49
0
 private static extern IntPtr OpenProcess(ProcessAccess dwDesiredAccess, Int32 bInheritHandle, UInt32 dwProcessId);
Esempio n. 50
0
 public IntPtr OpenRemoteProcess(IntPtr pid, ProcessAccess desiredAccess)
 {
     return(CurrentFunctions.OpenRemoteProcess(pid, desiredAccess));
 }
Esempio n. 51
0
 public static extern IntPtr OpenProcess(ProcessAccess dwDesiredAccess, bool bInheritHandle, int dwProcessId);
Esempio n. 52
0
 internal static extern IntPtr OpenProcess(
     ProcessAccess processAccess,
     bool bInheritHandle,
     int processId);
Esempio n. 53
0
 /// <summary>
 /// Получение хандла
 /// </summary>
 /// <param name="ProcessName">Имя процесса</param>
 public OldMemory(string ProcessName, ProcessAccess ProcessAccess) : base(ProcessName, ProcessAccess)
 {
 }