private static bool Prompt(IWin32Window window, int[] pids, string[] names, string action, string content, bool promptOnlyIfDangerous) { if (!Settings.Instance.WarnDangerous) { return(true); } string name = "the selected process(es)"; if (pids.Length == 1) { name = names[0]; } else { name = "the selected processes"; } bool dangerous = false; foreach (int pid in pids) { if (PhUtils.IsDangerousPid(pid)) { dangerous = true; break; } } bool critical = false; foreach (int pid in pids) { try { using (var phandle = new ProcessHandle(pid, ProcessAccess.QueryInformation)) { if (phandle.IsCritical) { critical = true; break; } } } catch { } } if (promptOnlyIfDangerous && !dangerous && !critical) { return(true); } DialogResult result = DialogResult.No; if (OSVersion.HasTaskDialogs) { TaskDialog td = new TaskDialog { PositionRelativeToWindow = true, WindowTitle = "Process Hacker", MainInstruction = "Do you want to " + action + " " + name + "?", Content = content }; if (critical) { td.MainIcon = TaskDialogIcon.Warning; td.Content = "You are about to " + action + " one or more CRITICAL processes. " + "Windows is designed to break (crash) when one of these processes is terminated. " + "Are you sure you want to continue?"; } else if (dangerous) { td.MainIcon = TaskDialogIcon.Warning; td.Content = "You are about to " + action + " one or more system processes. " + "Doing so will cause system instability. Are you sure you want to continue?"; } if (pids.Length > 1) { td.ExpandFooterArea = true; td.ExpandedInformation = "Processes:\r\n"; for (int i = 0; i < pids.Length; i++) { bool criticalPid; bool dangerousPid = PhUtils.IsDangerousPid(pids[i]); try { using (ProcessHandle phandle = new ProcessHandle(pids[i], ProcessAccess.QueryInformation)) criticalPid = phandle.IsCritical; } catch { criticalPid = false; } td.ExpandedInformation += names[i] + " (PID " + pids[i].ToString() + ")" + (dangerousPid ? " (system process) " : string.Empty) + (criticalPid ? " (CRITICAL) " : string.Empty) + "\r\n"; } td.ExpandedInformation = td.ExpandedInformation.Trim(); } td.Buttons = new TaskDialogButton[] { new TaskDialogButton((int)DialogResult.Yes, char.ToUpper(action[0]) + action.Substring(1)), new TaskDialogButton((int)DialogResult.No, "Cancel") }; td.DefaultButton = (int)DialogResult.No; result = (DialogResult)td.Show(window); } else { if (critical) { result = MessageBox.Show("You are about to " + action + " one or more CRITICAL processes. " + "Windows is designed to break (crash) when one of these processes is terminated. " + "Are you sure you want to " + action + " " + name + "?", "Process Hacker", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2); } else if (dangerous) { result = MessageBox.Show("You are about to " + action + " one or more system processes. " + "Are you sure you want to " + action + " " + name + "?", "Process Hacker", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2); } else { result = MessageBox.Show("Are you sure you want to " + action + " " + name + "?", "Process Hacker", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2); } } return(result == DialogResult.Yes); }
private void buttonApply_Click(object sender, EventArgs e) { try { string serviceName = listServices.SelectedItems[0].Name; ProcessHacker.Native.Objects.ServiceType type; if (comboType.SelectedItem.ToString() == "Win32OwnProcess, InteractiveProcess") { type = ProcessHacker.Native.Objects.ServiceType.Win32OwnProcess | ProcessHacker.Native.Objects.ServiceType.InteractiveProcess; } else if (comboType.SelectedItem.ToString() == "Win32ShareProcess, InteractiveProcess") { type = ProcessHacker.Native.Objects.ServiceType.Win32ShareProcess | ProcessHacker.Native.Objects.ServiceType.InteractiveProcess; } else { type = (ProcessHacker.Native.Objects.ServiceType) Enum.Parse(typeof(ProcessHacker.Native.Objects.ServiceType), comboType.SelectedItem.ToString()); } string binaryPath = textServiceBinaryPath.Text; string loadOrderGroup = textLoadOrderGroup.Text; string userAccount = textUserAccount.Text; string password = textPassword.Text; var startType = (ServiceStartType) Enum.Parse(typeof(ServiceStartType), comboStartType.SelectedItem.ToString()); var errorControl = (ServiceErrorControl) Enum.Parse(typeof(ServiceErrorControl), comboErrorControl.SelectedItem.ToString()); // Only change the items which the user modified. if (binaryPath == _oldConfig.BinaryPathName) { binaryPath = null; } if (loadOrderGroup == _oldConfig.LoadOrderGroup) { loadOrderGroup = null; } if (userAccount == _oldConfig.ServiceStartName) { userAccount = null; } if (!checkChangePassword.Checked) { password = null; } if (type == ProcessHacker.Native.Objects.ServiceType.KernelDriver || type == ProcessHacker.Native.Objects.ServiceType.FileSystemDriver) { userAccount = null; } if (Program.ElevationType == TokenElevationType.Full) { using (var shandle = new ServiceHandle(serviceName, ServiceAccess.ChangeConfig)) { if (!Win32.ChangeServiceConfig(shandle.Handle, type, startType, errorControl, binaryPath, loadOrderGroup, IntPtr.Zero, null, userAccount, password, null)) { Win32.ThrowLastError(); } } } else { string args = "-e -type service -action config -obj \"" + serviceName + "\" -hwnd " + this.Handle.ToString(); args += " -servicetype \"" + comboType.SelectedItem.ToString() + "\""; args += " -servicestarttype \"" + comboStartType.SelectedItem.ToString() + "\""; args += " -serviceerrorcontrol \"" + comboErrorControl.SelectedItem.ToString() + "\""; if (binaryPath != null) { args += " -servicebinarypath \"" + binaryPath.Replace("\"", "\\\"") + "\""; } if (loadOrderGroup != null) { args += " -serviceloadordergroup \"" + loadOrderGroup.Replace("\"", "\\\"") + "\""; } if (userAccount != null) { args += " -serviceuseraccount \"" + userAccount.Replace("\"", "\\\"") + "\""; } if (password != null) { args += " -servicepassword \"" + password.Replace("\"", "\\\"") + "\""; } var result = Program.StartProcessHackerAdminWait(args, this.Handle, 2000); if (result == WaitResult.Timeout || result == WaitResult.Abandoned) { return; } } using (var shandle = new ServiceHandle(serviceName, ServiceAccess.QueryConfig)) _provider.UpdateServiceConfig(serviceName, shandle.GetConfig()); if (listServices.Items.Count == 1) { this.Close(); } } catch (Exception ex) { PhUtils.ShowException("Unable to change service configuration", ex); } }
private void uploadTask_RunTask(object param, ref object result) { string boundary = "----------" + DateTime.Now.Ticks.ToString("x"); HttpWebRequest uploadRequest = (HttpWebRequest)WebRequest.Create( "http://www.virustotal.com/vt/en/recepcionf?" + (string)param); uploadRequest.ServicePoint.ConnectionLimit = 20; uploadRequest.UserAgent = "ProcessHacker " + Application.ProductVersion; uploadRequest.ContentType = "multipart/form-data; boundary=" + boundary; uploadRequest.Timeout = System.Threading.Timeout.Infinite; uploadRequest.KeepAlive = true; uploadRequest.Method = WebRequestMethods.Http.Post; // Build up the 'post' message header StringBuilder sb = new StringBuilder(); sb.Append("--"); sb.Append(boundary); sb.Append("\r\n"); sb.Append(@"Content-Disposition: form-data; name=""archivo""; filename=" + processName + ""); sb.Append("\r\n"); sb.Append("Content-Type: application/octet-stream"); sb.Append("\r\n"); sb.Append("\r\n"); string postHeader = sb.ToString(); byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader); // Build the trailing boundary string as a byte array // ensuring the boundary appears on a line by itself byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); if (uploadTask.Cancelled) { uploadRequest.Abort(); return; } try { uploadStopwatch = new Stopwatch(); uploadStopwatch.Start(); using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { uploadRequest.ContentLength = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length; using (Stream requestStream = uploadRequest.GetRequestStream()) { // Write out our post header requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); // Write out the file contents byte[] buffer = new Byte[checked ((uint)Math.Min(32, (int)fileStream.Length))]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { if (uploadTask.Cancelled) { uploadRequest.Abort(); return; } requestStream.Write(buffer, 0, bytesRead); int progress = (int)(((double)fileStream.Position * 100 / fileStream.Length)); if (uploadStopwatch.ElapsedMilliseconds > 0) { bytesPerSecond = fileStream.Position * 1000 / uploadStopwatch.ElapsedMilliseconds; } bytesTransferred = fileStream.Position; if (this.IsHandleCreated) { this.BeginInvoke(new Action <int>(this.ChangeProgress), progress); } } if (uploadTask.Cancelled) { uploadRequest.Abort(); return; } // Write out the trailing boundary requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); requestStream.Close(); } } } catch (WebException ex) { // RequestCanceled will occour when we cancel the WebRequest. // Filter out that exception but log all others. if (ex.Status != WebExceptionStatus.RequestCanceled) { PhUtils.ShowException("Unable to upload the file", ex); Logging.Log(ex); if (this.IsHandleCreated) { this.BeginInvoke(new MethodInvoker(this.Close)); } } } if (uploadTask.Cancelled) { uploadRequest.Abort(); return; } WebResponse response = uploadRequest.GetResponse(); //Stream s = responce.GetResponseStream(); //StreamReader sr = new StreamReader(s); //sr.ReadToEnd(); //Return the response URL result = response.ResponseUri.AbsoluteUri; }
private static void ElevateIfRequired(IWin32Window window, int session, string actionName, Action action) { if (Settings.Instance.ElevationLevel == (int)ElevationLevel.Never) { return; } try { action(); } catch (WindowsException ex) { if (ex.ErrorCode == Win32Error.AccessDenied && OSVersion.HasUac && Program.ElevationType == ProcessHacker.Native.Api.TokenElevationType.Limited) { DialogResult result; if (Settings.Instance.ElevationLevel == (int)ElevationLevel.Elevate) { result = DialogResult.Yes; } else { TaskDialog td = new TaskDialog(); td.WindowTitle = "Process Hacker"; td.MainIcon = TaskDialogIcon.Warning; td.MainInstruction = "Do you want to elevate the action?"; td.Content = "The action could not be performed in the current security context. " + "Do you want Process Hacker to prompt for the appropriate credentials and elevate the action?"; 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 elevate the action.") }; 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); }; result = (DialogResult)td.Show(window); } if (result == DialogResult.Yes) { Program.StartProcessHackerAdmin("-e -type session -action " + actionName + " -obj \"" + session.ToString() + "\" -hwnd " + window.Handle.ToString(), null, window.Handle); } } else { PhUtils.ShowException("Unable to " + actionName + " the session", ex); } } }
private void readWriteAddressMemoryMenuItem_Click(object sender, EventArgs e) { PromptBox prompt = new PromptBox(); if (prompt.ShowDialog() == DialogResult.OK) { IntPtr address = new IntPtr(-1); IntPtr regionAddress = IntPtr.Zero; long regionSize = 0; bool found = false; try { address = ((long)BaseConverter.ToNumberParse(prompt.Value)).ToIntPtr(); } catch { PhUtils.ShowError("You have entered an invalid address."); return; } List <MemoryItem> items = new List <MemoryItem>(); foreach (MemoryItem item in _provider.Dictionary.Values) { items.Add(item); } items.Sort((i1, i2) => i1.Address.CompareTo(i2.Address)); int i = 0; foreach (MemoryItem item in items) { MemoryItem regionItem = null; if (item.Address.CompareTo(address) > 0) { if (i > 0) { regionItem = items[i - 1]; } } else if (item.Address.CompareTo(address) == 0) { regionItem = items[i]; } if (regionItem != null && address.CompareTo(regionItem.Address) >= 0) { listMemory.Items[regionItem.Address.ToString()].Selected = true; listMemory.Items[regionItem.Address.ToString()].EnsureVisible(); regionAddress = regionItem.Address; regionSize = regionItem.Size; found = true; break; } i++; } if (!found) { PhUtils.ShowError("Unable to find the memory address."); return; } MemoryEditor.ReadWriteMemory( _pid, regionAddress, (int)regionSize, false, f => f.Select(address.Decrement(regionAddress).ToInt64(), 1) ); } }
public string GetToolTip(ProcessNode pNode) { try { string cmdText = (pNode.ProcessItem.CmdLine != null ? (Utils.CreateEllipsis(pNode.ProcessItem.CmdLine.Replace("\0", ""), 100) + "\n") : ""); string fileText = ""; try { if (pNode.ProcessItem.VersionInfo != null) { var info = pNode.ProcessItem.VersionInfo; fileText = "File:\n" + PhUtils.FormatFileInfo( info.FileName, info.FileDescription, info.CompanyName, info.FileVersion, 4); } } catch { if (pNode.ProcessItem.FileName != null) { fileText = "File:\n " + pNode.ProcessItem.FileName; } } string runDllText = ""; if (pNode.ProcessItem.FileName != null && pNode.ProcessItem.FileName.EndsWith("\\rundll32.exe", StringComparison.InvariantCultureIgnoreCase) && pNode.ProcessItem.CmdLine != null) { try { // TODO: fix crappy method string targetFile = pNode.ProcessItem.CmdLine.Split(new char[] { ' ' }, 2)[1].Split(',')[0]; // if it doesn't specify an absolute path, assume it's in system32. if (!targetFile.Contains(":")) { targetFile = Environment.SystemDirectory + "\\" + targetFile; } FileVersionInfo info = FileVersionInfo.GetVersionInfo(targetFile); runDllText = "\nRunDLL target:\n " + info.FileName + "\n " + info.FileDescription + " " + info.FileVersion + "\n " + info.CompanyName; } catch (Exception ex) { Logging.Log(ex); } } string dllhostText = ""; if (pNode.ProcessItem.FileName != null && pNode.ProcessItem.FileName.EndsWith("\\dllhost.exe", StringComparison.InvariantCultureIgnoreCase) && pNode.ProcessItem.CmdLine != null) { try { string clsid = pNode.ProcessItem.CmdLine.ToLowerInvariant().Split( new string[] { "/processid:" }, StringSplitOptions.None)[1].Split(' ')[0]; using (var key = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey("CLSID\\" + clsid)) { using (var inprocServer32 = key.OpenSubKey("InprocServer32")) { string name = key.GetValue("") as string; string fileName = inprocServer32.GetValue("") as string; FileVersionInfo info = FileVersionInfo.GetVersionInfo(Environment.ExpandEnvironmentVariables(fileName)); dllhostText = "\nCOM Target:\n " + name + " (" + clsid.ToUpper() + ")\n " + info.FileName + "\n " + info.FileDescription + " " + info.FileVersion + "\n " + info.CompanyName; } } } catch (Exception ex) { Logging.Log(ex); } } string servicesText = ""; try { IDictionary <int, List <string> > processServices; IDictionary <string, ServiceItem> services; if (!_tree.DumpMode) { processServices = Program.HackerWindow.ProcessServices; services = Program.ServiceProvider.Dictionary; } else { processServices = _tree.DumpProcessServices; services = _tree.DumpServices; } if (processServices.ContainsKey(pNode.Pid)) { foreach (string service in processServices[pNode.Pid]) { if (services.ContainsKey(service)) { if (services[service].Status.DisplayName != "") { servicesText += " " + service + " (" + services[service].Status.DisplayName + ")\n"; } else { servicesText += " " + service + "\n"; } } else { servicesText += " " + service + "\n"; } } servicesText = "\nServices:\n" + servicesText.TrimEnd('\n'); } } catch (Exception ex) { Logging.Log(ex); } string otherNotes = ""; try { if (pNode.ProcessItem.IsPacked && pNode.ProcessItem.ImportModules > 0) { otherNotes += "\n Image is probably packed - has " + pNode.ProcessItem.ImportFunctions.ToString() + " imports over " + pNode.ProcessItem.ImportModules.ToString() + " modules."; } else if (pNode.ProcessItem.IsPacked) { otherNotes += "\n Image is probably packed - error reading PE file."; } if (pNode.ProcessItem.FileName != null) { if (pNode.ProcessItem.VerifyResult == VerifyResult.Trusted) { if (!string.IsNullOrEmpty(pNode.ProcessItem.VerifySignerName)) { otherNotes += "\n Signer: " + pNode.ProcessItem.VerifySignerName; } else { otherNotes += "\n Signed."; } } else if (pNode.ProcessItem.VerifyResult == VerifyResult.Unknown && !Settings.Instance.VerifySignatures) { otherNotes += ""; } else if (pNode.ProcessItem.VerifyResult == VerifyResult.Unknown && Settings.Instance.VerifySignatures && !_tree.DumpMode) { otherNotes += "\n File has not been processed yet. Please wait..."; } else if (pNode.ProcessItem.VerifyResult != VerifyResult.NoSignature) { otherNotes += "\n Signature invalid."; } if (Program.ImposterNames.Contains(pNode.Name.ToLowerInvariant()) && pNode.ProcessItem.VerifyResult != VerifyResult.Trusted && pNode.ProcessItem.VerifyResult != VerifyResult.Unknown) { otherNotes += "\n Process is using the name of a known process but its signature could not be verified."; } } if (pNode.ProcessItem.IsInJob) { otherNotes += "\n Process is in a job."; } if (pNode.ProcessItem.ElevationType == TokenElevationType.Full) { otherNotes += "\n Process is elevated."; } if (pNode.ProcessItem.IsDotNet) { otherNotes += "\n Process is managed (.NET)."; } if (pNode.ProcessItem.IsPosix) { otherNotes += "\n Process is POSIX."; } if (pNode.ProcessItem.IsWow64) { otherNotes += "\n Process is 32-bit (running under WOW64)."; } if (otherNotes != "") { otherNotes = "\nNotes:" + otherNotes; } } catch (Exception ex) { Logging.Log(ex); } return((cmdText + fileText + otherNotes + runDllText + dllhostText + servicesText).Trim(' ', '\n', '\r')); } catch (Exception ex) { Logging.Log(ex); } return(string.Empty); }
private void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { // Check if the file is actually an executable file. if (!_redirected) { _redirected = true; try { bool isHtml = false; using (var file = new BinaryReader(File.OpenRead(_fileName))) { if (!file.ReadChars(2).Equals("MZ".ToCharArray())) { isHtml = true; } } if (isHtml) { string text = File.ReadAllText(_fileName); // Assume this is from Ohloh. int iframeIndex = text.IndexOf("window.delayed_iframe"); if (iframeIndex == -1) { return; } int httpIndex = text.IndexOf("http://", iframeIndex); if (httpIndex == -1) { return; } int quoteIndex = text.IndexOf("'", httpIndex); if (quoteIndex == -1) { return; } _webClient.DownloadFileAsync(new Uri(text.Substring(httpIndex, quoteIndex - httpIndex)), _fileName); return; } } catch (Exception ex) { Logging.Log(ex); } } if (!e.Cancelled) { _verifyTask = new ThreadTask(); _verifyTask.RunTask += verifyTask_RunTask; _verifyTask.Completed += verifyTask_Completed; _verifyTask.Start(); } else { var webException = e.Error as WebException; if (webException != null && webException.Status != WebExceptionStatus.RequestCanceled) { PhUtils.ShowException("Unable to download the update", webException); } } }