예제 #1
0
 public void ShouldOpenProcessHandleForCurrentProcess()
 {
     using (var processHandle = new ManagedProcess(Process.GetCurrentProcess()).SafeHandle)
     {
         Assert.NotEqual(true, processHandle.IsInvalid);
     }
 }
예제 #2
0
        /// <summary>
        /// Execute an individual action
        /// </summary>
        /// <param name="ProcessGroup">The process group</param>
        /// <param name="Action">The action to execute</param>
        /// <param name="CompletedActions">On completion, the list to add the completed action to</param>
        /// <param name="CompletedEvent">Event to set once an event is complete</param>
        static void ExecuteAction(ManagedProcessGroup ProcessGroup, BuildAction Action, List <BuildAction> CompletedActions, AutoResetEvent CompletedEvent)
        {
            if (Action.Inner.bShouldOutputStatusDescription && !String.IsNullOrEmpty(Action.Inner.StatusDescription))
            {
                Action.LogLines.Add(Action.Inner.StatusDescription);
            }

            try
            {
                using (ManagedProcess Process = new ManagedProcess(ProcessGroup, Action.Inner.CommandPath.FullName, Action.Inner.CommandArguments, Action.Inner.WorkingDirectory.FullName, null, null, ProcessPriorityClass.BelowNormal))
                {
                    Action.LogLines.AddRange(Process.ReadAllLines());
                    Action.ExitCode = Process.ExitCode;
                }
            }
            catch (Exception Ex)
            {
                Log.WriteException(Ex, null);
                Action.ExitCode = 1;
            }

            lock (CompletedActions)
            {
                CompletedActions.Add(Action);
            }

            CompletedEvent.Set();
        }
예제 #3
0
		/// <summary>
		/// Reads a line of output from the given process
		/// </summary>
		/// <param name="Process">The process to read from</param>
		/// <param name="CancellationToken">Cancellation token for when the timeout expires</param>
		/// <returns>The line that was read</returns>
		static string ReadProcessLine(ManagedProcess Process, CancellationToken CancellationToken)
		{
			string Line;
			if (Process.TryReadLine(out Line, CancellationToken))
			{
				Log.TraceInformation("{0}", Line);
			}
			return Line;
		}
예제 #4
0
파일: EjectDll.cs 프로젝트: ohio813/Bleak
        internal EjectDll(InjectionWrapper injectionWrapper)
        {
            _injectionMethod = injectionWrapper.InjectionMethod;

            _injectionFlags = injectionWrapper.InjectionFlags;

            _peImage = injectionWrapper.PeImage;

            _process = injectionWrapper.Process;
        }
예제 #5
0
        internal HijackThread(InjectionWrapper injectionWrapper)
        {
            _dllPath = injectionWrapper.DllPath;

            _injectionFlags = injectionWrapper.InjectionFlags;

            _peImage = injectionWrapper.PeImage;

            _process = injectionWrapper.Process;
        }
예제 #6
0
        public IActionResult Details(Guid id)
        {
            ManagedProcess process = processManagerService.GetProcess(id);

            if (process == null)
            {
                return(NotFound());
            }

            return(View(process));
        }
예제 #7
0
        internal ManualMap(InjectionWrapper injectionWrapper)
        {
            _injectionFlags = injectionWrapper.InjectionFlags;

            _localDllAddress = Marshal.AllocHGlobal(injectionWrapper.DllBytes.Length);

            Marshal.Copy(injectionWrapper.DllBytes, 0, _localDllAddress, injectionWrapper.DllBytes.Length);

            _peImage = injectionWrapper.PeImage;

            _process = injectionWrapper.Process;
        }
        private void TimeBenchmark()
        {
            Tool   t   = (Tool)Tools[cboBenchmarkTool.Text];
            string cmd = t.Time;

            cmd = cmd.Replace("%time", txtBenchmarkDuration.Text);
            cmd = cmd.Replace("%url", (cboUrl.Text.TrimEnd('/') + "/"));
            LogMessage((t.Path + cmd));
            ManagedProcess p = new ManagedProcess(t.Path, cmd);

            txtRaw.Text = p.Output.ToString();
            ParseResults(p.Output.ToString());
        }
 public void Dispose()
 {
     if (ChildProcess != null)
     {
         ChildProcess.Dispose();
         ChildProcess = null;
     }
     if (ChildProcessGroup != null)
     {
         ChildProcessGroup.Dispose();
         ChildProcessGroup = null;
     }
 }
예제 #10
0
 /// <summary>
 /// Retrieve the class used to load binary modules in a process.
 /// </summary>
 /// <param name="process">The target process.</param>
 /// <returns>The class that handles binary handling.</returns>
 private static IBinaryLoader GetBinaryLoader(Process process)
 {
     if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
     {
         var managedProcess = new ManagedProcess(process);
         return(new BinaryLoader(
                    new ProcessManager(managedProcess,
                                       new MemoryManager(managedProcess))));
     }
     else
     {
         throw new PlatformNotSupportedException("Binary injection");
     }
 }
        private void SpeedBenchmark()
        {
            Tool   t   = (Tool)Tools[cboBenchmarkTool.Text];
            string cmd = t.Speed;

            cmd = cmd.Replace("%num", txtBenchmarkNumber.Text);
            cmd = cmd.Replace("%conc", txtBenchmarkConcurrency.Text);
            cmd = cmd.Replace("%url", (cboUrl.Text.TrimEnd('/') + "/"));
            LogMessage((t.Path + cmd));
            ManagedProcess p = new ManagedProcess(t.Path, cmd);

            //  TODO: this throws an exception due to multithreading...
            //    https://stackoverflow.com/questions/24181910/stringbuilder-thread-safety?rq=1
            txtRaw.Text = p.Output.ToString();
            ParseResults(p.Output.ToString());
        }
예제 #12
0
        public void ShouldGetFunctionAddressForCurrentProcess()
        {
            IntPtr functionAddress = IntPtr.Zero;
            string moduleFileName  = Path.Combine(
                Environment.ExpandEnvironmentVariables("%Windir%"),
                "System32",
                "kernel32.dll");
            const string functionName = "LoadLibraryW";

            using (var processHandle = new ManagedProcess(Process.GetCurrentProcess()).SafeHandle)
            {
                functionAddress = ThreadHelper.GetProcAddress(
                    processHandle,
                    moduleFileName,
                    functionName);
            }

            Assert.NotEqual(IntPtr.Zero, functionAddress);
        }
예제 #13
0
        internal InjectionWrapper(Process process, string dllPath, InjectionMethod injectionMethod, InjectionFlags injectionFlags)
        {
            DllBytes = File.ReadAllBytes(dllPath);

            DllPath = injectionFlags.HasFlag(InjectionFlags.RandomiseDllName) ? CreateTemporaryDll() : dllPath;

            InjectionMethod = injectionMethod;

            InjectionFlags = injectionFlags;

            PeImage = new PeImage(DllBytes);

            Process = new ManagedProcess(process);

            if (injectionMethod == InjectionMethod.ManualMap || injectionFlags.HasFlag(InjectionFlags.HideDllFromPeb))
            {
                ResolveApiSetImportedFunctions();
            }
        }
예제 #14
0
        /// <summary>
        /// Execute an individual action
        /// </summary>
        /// <param name="Action">The action to execute</param>
        /// <param name="CompletedActions">On completion, the list to add the completed action to</param>
        /// <param name="CompletedEvent">Event to set once an event is complete</param>
        static void ExecuteAction(BuildAction Action, List <BuildAction> CompletedActions, AutoResetEvent CompletedEvent)
        {
            if (Action.Inner.bShouldOutputStatusDescription && !String.IsNullOrEmpty(Action.Inner.StatusDescription))
            {
                Action.LogLines.Add(Action.Inner.StatusDescription);
            }

            using (ManagedProcess Process = new ManagedProcess(Action.Inner.CommandPath, Action.Inner.CommandArguments, Action.Inner.WorkingDirectory, null, null, ManagedProcessPriority.BelowNormal))
            {
                Action.LogLines.AddRange(Process.ReadAllLines());
                Action.ExitCode = Process.ExitCode;
            }

            lock (CompletedActions)
            {
                CompletedActions.Add(Action);
            }

            CompletedEvent.Set();
        }
        public PerforceChildProcess(byte[] InputData, string Format, params object[] Args)
        {
            string PerforceFileName;

            if (Environment.OSVersion.Platform == PlatformID.Win32NT || Environment.OSVersion.Platform == PlatformID.Win32S || Environment.OSVersion.Platform == PlatformID.Win32Windows)
            {
                PerforceFileName = "p4.exe";
            }
            else
            {
                PerforceFileName = File.Exists("/usr/local/bin/p4")? "/usr/local/bin/p4" : "/usr/bin/p4";
            }

            string FullArgumentList = "-G " + String.Format(Format, Args);

            Log.TraceLog("Running {0} {1}", PerforceFileName, FullArgumentList);

            ChildProcessGroup = new ManagedProcessGroup();
            ChildProcess      = new ManagedProcess(ChildProcessGroup, PerforceFileName, FullArgumentList, null, null, InputData, ProcessPriorityClass.Normal);

            Buffer = new byte[2048];
        }
예제 #16
0
        internal InjectionWrapper(Process process, byte[] dllBytes, InjectionMethod injectionMethod, InjectionFlags injectionFlags)
        {
            DllBytes = dllBytes;

            if (injectionMethod != InjectionMethod.ManualMap)
            {
                DllPath = CreateTemporaryDll();
            }

            InjectionMethod = injectionMethod;

            InjectionFlags = injectionFlags;

            PeImage = new PeImage(dllBytes);

            Process = new ManagedProcess(process);

            if (injectionMethod == InjectionMethod.ManualMap || injectionFlags.HasFlag(InjectionFlags.HideDllFromPeb))
            {
                ResolveApiSetImportedFunctions();
            }
        }
예제 #17
0
        public bool Start(Guid processId)
        {
            if (!managedProcesses.ContainsKey(processId))
            {
                return(false);
            }

            ProcessListItem item          = managedProcesses[processId];
            ManagedProcess  configuration = item.Configuration;

            if (item.Process != null)
            {
                if (!item.Process.HasExited)
                {
                    return(false);
                }
            }
            else
            {
                ProcessStartInfo startInfo = new ProcessStartInfo(configuration.FileName);

                if (!string.IsNullOrWhiteSpace(configuration.Args))
                {
                    startInfo.Arguments = configuration.Args;
                }

                if (!string.IsNullOrWhiteSpace(configuration.WorkingDirectory))
                {
                    startInfo.WorkingDirectory = configuration.WorkingDirectory;
                }

                if (!string.IsNullOrWhiteSpace(configuration.Username) && !string.IsNullOrWhiteSpace(configuration.Password))
                {
                    startInfo.UserName            = configuration.Username;
                    startInfo.PasswordInClearText = configuration.Password;
                }

                startInfo.CreateNoWindow  = true;
                startInfo.UseShellExecute = false;

                startInfo.StandardErrorEncoding  = Encoding.UTF8;
                startInfo.StandardInputEncoding  = Encoding.UTF8;
                startInfo.StandardOutputEncoding = Encoding.UTF8;

                startInfo.RedirectStandardError  = true;
                startInfo.RedirectStandardInput  = true;
                startInfo.RedirectStandardOutput = true;

                Process startedProcess = new Process();
                startedProcess.StartInfo = startInfo;

                startedProcess.OutputDataReceived += (source, ea) => processOutputService.AddStandardOutput(configuration.ID, ea.Data);
                startedProcess.ErrorDataReceived  += (source, ea) => processOutputService.AddErrorOutput(configuration.ID, ea.Data);

                startedProcess.EnableRaisingEvents = true;
                startedProcess.Exited += (source, ea) => StartedProcess_Exited(item, ea);

                item.Process = startedProcess;
            }

            bool result;

            try
            {
                result = item.Process.Start();
                if (result)
                {
                    item.Process.StandardInput.AutoFlush = true;

                    item.Process.BeginErrorReadLine();
                    item.Process.BeginOutputReadLine();
                }
            }
            catch (Exception ex)
            {
                result = false;
                processOutputService.AddInternalOutput(configuration.ID, $"Process failed to start with exception: {ex.Message} ({ex.GetType().FullName})");
            }

            return(result);
        }
예제 #18
0
        public override int Execute()
        {
            int ExitCode = 0;

            // Auto-register all the known matchers in this assembly
            List <IErrorMatcher> Matchers = new List <IErrorMatcher>();

            foreach (Type Type in Assembly.GetExecutingAssembly().GetTypes())
            {
                if (Type.GetCustomAttribute <AutoRegisterAttribute>() != null)
                {
                    object Instance = Activator.CreateInstance(Type);
                    if (typeof(IErrorMatcher).IsAssignableFrom(Type))
                    {
                        Matchers.Add((IErrorMatcher)Instance);
                    }
                    else
                    {
                        throw new Exception(String.Format("Unable to auto-register object of type {0}", Type.Name));
                    }
                }
            }

            // Read all the ignore patterns
            List <string> IgnorePatterns = new List <string>();

            if (IgnorePatternsFile != null)
            {
                if (!FileReference.Exists(IgnorePatternsFile))
                {
                    throw new FatalErrorException("Unable to read '{0}", IgnorePatternsFile);
                }

                // Read all the ignore patterns
                string[] Lines = FileReference.ReadAllLines(IgnorePatternsFile);
                foreach (string Line in Lines)
                {
                    string TrimLine = Line.Trim();
                    if (TrimLine.Length > 0 && !TrimLine.StartsWith("#"))
                    {
                        IgnorePatterns.Add(TrimLine);
                    }
                }
            }

            // Create the output listeners
            List <IErrorListener> Listeners = new List <IErrorListener>();

            try
            {
                if (bDebugListener)
                {
                    Listeners.Add(new DebugOutputListener());
                }
                if (bElectricCommanderListener)
                {
                    Listeners.Add(new ElectricCommanderListener());
                }
                if (IssuesOutputFile != null)
                {
                    Listeners.Add(new IssuesListener(Stream, Change, JobName, JobUrl, JobStepName, JobStepUrl, LineUrl, BaseDir, IssuesOutputFile));
                }

                // Process the input
                if (InputFile != null)
                {
                    if (!FileReference.Exists(InputFile))
                    {
                        throw new FatalErrorException("Specified input file '{0}' does not exist", InputFile);
                    }

                    using (StreamReader Reader = new StreamReader(InputFile.FullName))
                    {
                        LineFilter Filter = new LineFilter(() => Reader.ReadLine());
                        ProcessErrors(Filter.ReadLine, Matchers, IgnorePatterns, Listeners, bNoWarnings);
                    }
                }
                else
                {
                    CancellationTokenSource CancellationTokenSource = new CancellationTokenSource();
                    if (Timeout.HasValue)
                    {
                        CancellationTokenSource.CancelAfter(Timeout.Value);
                    }

                    CancellationToken CancellationToken = CancellationTokenSource.Token;
                    using (ManagedProcess Process = new ManagedProcess(null, Program.FullName, CommandLineArguments.Join(ProgramArguments), null, null, null, ProcessPriorityClass.Normal))
                    {
                        Func <string> ReadLine = new LineFilter(() => ReadProcessLine(Process, CancellationToken)).ReadLine;
                        ProcessErrors(ReadLine, Matchers, IgnorePatterns, Listeners, bNoWarnings);
                        ExitCode = Process.ExitCode;
                    }
                }
            }
            finally
            {
                foreach (IErrorListener Listener in Listeners)
                {
                    Listener.Dispose();
                }
            }

            // Kill off any remaining child processes
            ProcessUtils.TerminateChildProcesses();
            return(ExitCode);
        }
예제 #19
0
        internal HideDllFromPeb(InjectionWrapper injectionWrapper)
        {
            _dllPath = injectionWrapper.DllPath;

            _process = injectionWrapper.Process;
        }