Exemplo n.º 1
0
        public IProcess Run(ProcessRunSpec runSpec)
        {
            Guid processKey = Guid.NewGuid();

            var defaultEnvironmentBlock = EnvironmentBlock.CreateSystemDefault();
            var environment             = defaultEnvironmentBlock.Merge(runSpec.Environment).ToDictionary();

            CreateProcessParams @params = new CreateProcessParams
            {
                key              = processKey,
                executablePath   = runSpec.ExecutablePath,
                arguments        = runSpec.Arguments,
                environment      = environment,
                workingDirectory = runSpec.WorkingDirectory
            };

            var processDataCallback = BuildProcessDataCallback(runSpec.OutputCallback, runSpec.ErrorCallback);

            hostClient.SubscribeToProcessData(processKey, processDataCallback);

            var result  = hostClient.CreateProcess(@params);
            var process = new ConstrainedProcess(hostClient, processKey, result.id, environment);

            return(process);
        }
Exemplo n.º 2
0
 public bool EqualTo(EnvironmentBlock t)
 {
     if (indexX == t.indexX && indexY == t.indexY)
     {
         return(true);
     }
     return(false);
 }
Exemplo n.º 3
0
    void Diffuse(EnvironmentBlock t)
    {
        if (Oxygen > t.Oxygen + EnvironmentBlock.DiffusionSpeed)
        {
            Oxygen   -= DiffusionSpeed;
            t.Oxygen += DiffusionSpeed;
        }
        else if (Oxygen + DiffusionSpeed < t.Oxygen)
        {
            //Oxygen += DiffusionSpeed;
            //t.Oxygen -= DiffusionSpeed;
        }
        else
        {
            Oxygen   = (Oxygen + t.Oxygen) / 2;
            t.Oxygen = Oxygen;
        }

        if (CarbonDioxide > t.CarbonDioxide + DiffusionSpeed)
        {
            CarbonDioxide   -= DiffusionSpeed;
            t.CarbonDioxide += DiffusionSpeed;
        }
        else if (CarbonDioxide + DiffusionSpeed < t.CarbonDioxide)
        {
            //CarbonDioxide += DiffusionSpeed;
            //t.CarbonDioxide -= DiffusionSpeed;
        }
        else
        {
            CarbonDioxide   = (CarbonDioxide + t.CarbonDioxide) / 2;
            t.CarbonDioxide = CarbonDioxide;
        }

        if (H2O > t.H2O + DiffusionSpeed)
        {
            H2O   -= DiffusionSpeed;
            t.H2O += DiffusionSpeed;
        }
        else if (H2O + DiffusionSpeed < t.H2O)
        {
            //H2O += DiffusionSpeed;
            //t.H2O -= DiffusionSpeed;
        }
        else
        {
            H2O   = (H2O + t.H2O) / 2;
            t.H2O = H2O;
        }
    }
Exemplo n.º 4
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
            )
        {
            // Create the unicode strings.

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

            try
            {
                IntPtr processParameters;

                // Create the process parameter block.
                Win32.RtlCreateProcessParameters(
                    out processParameters,
                    ref imagePathNameStr,
                    ref dllPathStr,
                    ref currentDirectoryStr,
                    ref commandLineStr,
                    environment,
                    ref windowTitleStr,
                    ref desktopInfoStr,
                    ref shellInfoStr,
                    ref runtimeInfoStr
                    ).ThrowIf();

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

                    int    environmentLength = environment.Length;
                    IntPtr 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 regionSize = paramsStruct->Length.ToIntPtr();

                    IntPtr 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();
            }
        }
Exemplo n.º 5
0
        public static void Main(Dictionary <string, string> pArgs)
        {
            args = pArgs;

            EnablePrivilege("SeAssignPrimaryTokenPrivilege");
            EnablePrivilege("SeBackupPrivilege");
            EnablePrivilege("SeRestorePrivilege");

            try
            {
                bool bad = false;

                if (!args.ContainsKey("-w"))
                {
                    if (!args.ContainsKey("-c") && !args.ContainsKey("-f"))
                    {
                        bad = true;
                    }

                    if (args.ContainsKey("-c") && args.ContainsKey("-f"))
                    {
                        bad = true;
                    }

                    if (!args.ContainsKey("-u") && !args.ContainsKey("-P"))
                    {
                        bad = true;
                    }

                    if (args.ContainsKey("-u") && args.ContainsKey("-P"))
                    {
                        bad = true;
                    }
                }

                if (args.ContainsKey("-v") || args.ContainsKey("-h"))
                {
                    bad = true;
                }

                if (bad)
                {
                    PrintUsage();
                    Exit();
                }
            }
            catch
            {
                PrintUsage();
                Exit();
            }

            if (args.ContainsKey("-w"))
            {
                try
                {
                    SetDesktopWinStaAccess();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Warning: Could not set desktop and window station access: " + ex.Message);
                }
            }

            TokenHandle token    = null;
            string      domain   = null;
            string      username = "";

            if (args.ContainsKey("-u"))
            {
                string user = args["-u"];

                if (user.Contains("\\"))
                {
                    domain   = user.Split('\\')[0];
                    username = user.Split('\\')[1];
                }
                else if (user.Contains("@"))
                {
                    username = user.Split('@')[0];
                    domain   = user.Split('@')[1];
                }
                else
                {
                    username = user;
                }

                LogonType type = LogonType.Interactive;

                if (args.ContainsKey("-t"))
                {
                    try
                    {
                        type = (LogonType)Enum.Parse(typeof(LogonType), args["-t"], true);
                    }
                    catch
                    {
                        Console.WriteLine("Error: Invalid logon type.");
                        Exit(-1);
                    }
                }

                try
                {
                    token = TokenHandle.Logon(
                        username,
                        domain,
                        args.ContainsKey("-p") ? args["-p"] : "",
                        type,
                        LogonProvider.Default
                        );
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: Could not logon as user: "******"-P"))
                    {
                        pid = int.Parse(args["-P"]);
                    }
                }
                catch
                {
                    Console.WriteLine("Error: Invalid PID.");
                }

                try
                {
                    using (var phandle = new ProcessHandle(pid, OSVersion.MinProcessQueryInfoAccess))
                    {
                        try
                        {
                            token = phandle.GetToken(TokenAccess.All);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error: Could not open process token: " + ex.Message);
                            Exit(Marshal.GetLastWin32Error());
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: Could not open process: " + ex.Message);
                    Exit(Marshal.GetLastWin32Error());
                }

                // Need to duplicate the token if we're going to set the session ID.
                if (args.ContainsKey("-s"))
                {
                    try
                    {
                        TokenHandle dupToken;

                        dupToken = token.Duplicate(
                            TokenAccess.All,
                            SecurityImpersonationLevel.SecurityImpersonation,
                            TokenType.Primary
                            );
                        token.Dispose();
                        token = dupToken;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error: Could not duplicate own token: " + ex.Message);
                        Exit(Marshal.GetLastWin32Error());
                    }
                }
            }

            if (args.ContainsKey("-s"))
            {
                int sessionId = int.Parse(args["-s"]);

                try
                {
                    token.SetSessionId(sessionId);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: Could not set token session ID: " + ex.Message);
                }
            }

            if (args.ContainsKey("-c") || args.ContainsKey("-f"))
            {
                if (!args.ContainsKey("-e"))
                {
                    EnvironmentBlock environment;
                    StartupInfo      startupInfo = new StartupInfo();
                    ProcessHandle    processHandle;
                    ThreadHandle     threadHandle;
                    ClientId         clientId;

                    environment         = new EnvironmentBlock(token);
                    startupInfo.Desktop = "WinSta0\\Default";

                    try
                    {
                        processHandle = ProcessHandle.CreateWin32(
                            token,
                            args.ContainsKey("-f") ? args["-f"] : null,
                            args.ContainsKey("-c") ? args["-c"] : null,
                            false,
                            ProcessCreationFlags.CreateUnicodeEnvironment,
                            environment,
                            args.ContainsKey("-d") ? args["-d"] : null,
                            startupInfo,
                            out clientId,
                            out threadHandle
                            );
                        processHandle.Dispose();
                        threadHandle.Dispose();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error: Could not create process: " + ex.Message);
                        Exit(Marshal.GetLastWin32Error());
                    }
                    finally
                    {
                        environment.Destroy();
                    }
                }
            }

            token.Dispose();

            Exit();
        }
Exemplo n.º 6
0
        private static unsafe int ExecWaitWithCaptureUnimpersonated(SafeUserTokenHandle userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName, string trueCmdLine)
        {
            IntSecurity.UnmanagedCode.Demand();

            FileStream output;
            FileStream error;

            int retValue = 0;

            if (outputName == null || outputName.Length == 0)
            {
                outputName = tempFiles.AddExtension("out");
            }

            if (errorName == null || errorName.Length == 0)
            {
                errorName = tempFiles.AddExtension("err");
            }

            // Create the files
            output = CreateInheritedFile(outputName);
            error  = CreateInheritedFile(errorName);

            bool success = false;

            SafeNativeMethods.PROCESS_INFORMATION pi = new SafeNativeMethods.PROCESS_INFORMATION();
            SafeProcessHandle   procSH       = new SafeProcessHandle();
            SafeThreadHandle    threadSH     = new SafeThreadHandle();
            SafeUserTokenHandle primaryToken = null;

            try {
                // Output the command line...
                StreamWriter sw = new StreamWriter(output, Encoding.UTF8);
                sw.Write(currentDir);
                sw.Write("> ");
                // 'true' command line is used in case the command line points to
                // a response file
                sw.WriteLine(trueCmdLine != null ? trueCmdLine : cmd);
                sw.WriteLine();
                sw.WriteLine();
                sw.Flush();

                NativeMethods.STARTUPINFO si = new NativeMethods.STARTUPINFO();

                si.cb         = Marshal.SizeOf(si);
                si.dwFlags    = NativeMethods.STARTF_USESTDHANDLES;
                si.hStdOutput = output.SafeFileHandle;
                si.hStdError  = error.SafeFileHandle;
                si.hStdInput  = new SafeFileHandle(UnsafeNativeMethods.GetStdHandle(NativeMethods.STD_INPUT_HANDLE), false);

                //
                // Prepare the environment
                //
#if PLATFORM_UNIX
                StringDictionary environment = new CaseSensitiveStringDictionary();
#else
                StringDictionary environment = new StringDictionary();
#endif // PLATFORM_UNIX



                // Add the current environment

                foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables())
                {
                    environment.Add((string)entry.Key, (string)entry.Value);
                }



                // Add the flag to indicate restricted security in the process
                environment["_ClrRestrictSecAttributes"] = "1";

                #if DEBUG
                environment["OANOCACHE"] = "1";
                #endif

                // set up the environment block parameter
                byte[] environmentBytes = EnvironmentBlock.ToByteArray(environment, false);
                fixed(byte *environmentBytesPtr = environmentBytes)
                {
                    IntPtr environmentPtr = new IntPtr((void *)environmentBytesPtr);

                    if (userToken == null || userToken.IsInvalid)
                    {
                        RuntimeHelpers.PrepareConstrainedRegions();
                        try {} finally {
                            success = NativeMethods.CreateProcess(
                                null,                              // String lpApplicationName,
                                new StringBuilder(cmd),            // String lpCommandLine,
                                null,                              // SECURITY_ATTRIBUTES lpProcessAttributes,
                                null,                              // SECURITY_ATTRIBUTES lpThreadAttributes,
                                true,                              // bool bInheritHandles,
                                0,                                 // int dwCreationFlags,
                                environmentPtr,                    // int lpEnvironment,
                                currentDir,                        // String lpCurrentDirectory,
                                si,                                // STARTUPINFO lpStartupInfo,
                                pi);                               // PROCESS_INFORMATION lpProcessInformation);
                            if (pi.hProcess != (IntPtr)0 && pi.hProcess != (IntPtr)NativeMethods.INVALID_HANDLE_VALUE)
                            {
                                procSH.InitialSetHandle(pi.hProcess);
                            }
                            if (pi.hThread != (IntPtr)0 && pi.hThread != (IntPtr)NativeMethods.INVALID_HANDLE_VALUE)
                            {
                                threadSH.InitialSetHandle(pi.hThread);
                            }
                        }
                    }
                    else
                    {
                        throw new NotSupportedException();
                    }
                }
            }
            finally {
                // Close the file handles
                if (!success && (primaryToken != null && !primaryToken.IsInvalid))
                {
                    primaryToken.Close();
                    primaryToken = null;
                }

                output.Close();
                error.Close();
            }

            if (success)
            {
                try {
                    int ret = NativeMethods.WaitForSingleObject(procSH, ProcessTimeOut);

                    // Check for timeout
                    if (ret == NativeMethods.WAIT_TIMEOUT)
                    {
                        throw new ExternalException(SR.GetString(SR.ExecTimeout, cmd), NativeMethods.WAIT_TIMEOUT);
                    }

                    if (ret != NativeMethods.WAIT_OBJECT_0)
                    {
                        throw new ExternalException(SR.GetString(SR.ExecBadreturn, cmd), Marshal.GetLastWin32Error());
                    }

                    // Check the process's exit code
                    int status = NativeMethods.STILL_ACTIVE;
                    if (!NativeMethods.GetExitCodeProcess(procSH, out status))
                    {
                        throw new ExternalException(SR.GetString(SR.ExecCantGetRetCode, cmd), Marshal.GetLastWin32Error());
                    }

                    retValue = status;
                }
                finally {
                    procSH.Close();
                    threadSH.Close();
                    if (primaryToken != null && !primaryToken.IsInvalid)
                    {
                        primaryToken.Close();
                    }
                }
            }
            else
            {
                throw new ExternalException(SR.GetString(SR.ExecCantExec, cmd), Marshal.GetLastWin32Error());
            }

            return(retValue);
        }
Exemplo n.º 7
0
        public static DllInjector CreateProcess(ProcessStartInfo StartInfo, bool CreateSuspended = false, bool FreeOnDispose = false)
        {
            Process process;

            if (CreateSuspended)
            {
                if (StartInfo == null)
                {
                    throw new ArgumentNullException("StartInfo");
                }

                if (string.IsNullOrEmpty(StartInfo.FileName))
                {
                    throw new ArgumentException("FileNameMissing");
                }

                if (StartInfo.StandardOutputEncoding != null && !StartInfo.RedirectStandardOutput)
                {
                    throw new ArgumentException("StandardOutputEncodingNotAllowed");
                }

                if (StartInfo.StandardErrorEncoding != null && !StartInfo.RedirectStandardError)
                {
                    throw new ArgumentException("StandardErrorEncodingNotAllowed");
                }

                /*
                 * private static StringBuilder BuildCommandLine(string executableFileName, string arguments);
                 *
                 * Declaring Type: System.Diagnostics.Process
                 * Assembly: System, Version=4.0.0.0
                 */
                StringBuilder cmdLine = new StringBuilder();
                string        str     = StartInfo.FileName.Trim();
                bool          flag    = str.StartsWith("\"", StringComparison.Ordinal) && str.EndsWith("\"", StringComparison.Ordinal);

                if (!flag)
                {
                    cmdLine.Append("\"");
                }

                cmdLine.Append(str);

                if (!flag)
                {
                    cmdLine.Append("\"");
                }

                if (!string.IsNullOrEmpty(StartInfo.Arguments))
                {
                    cmdLine.Append(" ");
                    cmdLine.Append(StartInfo.Arguments);
                }

                /*
                 * private bool StartWithCreateProcess(ProcessStartInfo startInfo);
                 *
                 * Declaring Type: System.Diagnostics.Process
                 * Assembly: System, Version=4.0.0.0
                 */
                Win32.STARTUPINFO lpStartupInfo = new Win32.STARTUPINFO()
                {
                    hStdError  = new SafeFileHandle(IntPtr.Zero, false),
                    hStdInput  = new SafeFileHandle(IntPtr.Zero, false),
                    hStdOutput = new SafeFileHandle(IntPtr.Zero, false)
                };
                Win32.PROCESS_INFORMATION lpProcessInformation = new Win32.PROCESS_INFORMATION();
                IntPtr         processHandle = IntPtr.Zero;
                IntPtr         handle2       = IntPtr.Zero;
                SafeFileHandle parentHandle  = null;
                SafeFileHandle handle4       = null;
                SafeFileHandle handle5       = null;
                int            error         = 0;
                GCHandle       handle6       = new GCHandle();

                try
                {
                    if (StartInfo.RedirectStandardInput || StartInfo.RedirectStandardOutput || StartInfo.RedirectStandardError)
                    {
                        if (StartInfo.RedirectStandardInput)
                        {
                            CreatePipe(out parentHandle, out lpStartupInfo.hStdInput, true);
                        }
                        else
                        {
                            lpStartupInfo.hStdInput = new SafeFileHandle(Win32.GetStdHandle(Win32.StdHandles.STD_INPUT_HANDLE), false);
                        }

                        if (StartInfo.RedirectStandardOutput)
                        {
                            CreatePipe(out handle4, out lpStartupInfo.hStdOutput, false);
                        }
                        else
                        {
                            lpStartupInfo.hStdOutput = new SafeFileHandle(Win32.GetStdHandle(Win32.StdHandles.STD_OUTPUT_HANDLE), false);
                        }

                        if (StartInfo.RedirectStandardError)
                        {
                            CreatePipe(out handle5, out lpStartupInfo.hStdError, false);
                        }
                        else
                        {
                            lpStartupInfo.hStdError = new SafeFileHandle(Win32.GetStdHandle(Win32.StdHandles.STD_ERROR_HANDLE), false);
                        }

                        lpStartupInfo.dwFlags = 0x100;
                    }

                    Win32.ProcessCreationFlags creationFlags = Win32.ProcessCreationFlags.CREATE_SUSPENDED;

                    if (StartInfo.CreateNoWindow)
                    {
                        creationFlags |= Win32.ProcessCreationFlags.CREATE_NO_WINDOW;
                    }

                    if (Utilities.IsNt)
                    {
                        creationFlags |= Win32.ProcessCreationFlags.CREATE_UNICODE_ENVIRONMENT;
                        handle6        = GCHandle.Alloc(EnvironmentBlock.ToByteArray(StartInfo.EnvironmentVariables, true), GCHandleType.Pinned);
                    }
                    else
                    {
                        handle6 = GCHandle.Alloc(EnvironmentBlock.ToByteArray(StartInfo.EnvironmentVariables, false), GCHandleType.Pinned);
                    }

                    string workingDirectory = StartInfo.WorkingDirectory;

                    if (workingDirectory == string.Empty)
                    {
                        workingDirectory = Environment.CurrentDirectory;
                    }

                    if (StartInfo.UserName.Length != 0)
                    {
                        Win32.LogonFlags logonFlags = 0;

                        if (StartInfo.LoadUserProfile)
                        {
                            logonFlags = Win32.LogonFlags.LOGON_WITH_PROFILE;
                        }

                        IntPtr password = IntPtr.Zero;

                        try
                        {
                            if (StartInfo.Password == null)
                            {
                                password = Marshal.StringToCoTaskMemUni(string.Empty);
                            }
                            else
                            {
                                password = Marshal.SecureStringToCoTaskMemUnicode(StartInfo.Password);
                            }

                            RuntimeHelpers.PrepareConstrainedRegions();

                            try
                            {
                            }
                            finally
                            {
                                flag = Win32.CreateProcessWithLogon(StartInfo.UserName, StartInfo.Domain, password, logonFlags, null, cmdLine, creationFlags, handle6.AddrOfPinnedObject(), workingDirectory, ref lpStartupInfo, out lpProcessInformation);

                                if (!flag)
                                {
                                    error = Marshal.GetLastWin32Error();
                                }

                                if (lpProcessInformation.hProcess != IntPtr.Zero && lpProcessInformation.hProcess != Win32.INVALID_HANDLE_VALUE)
                                {
                                    processHandle = lpProcessInformation.hProcess;
                                }

                                if (lpProcessInformation.hThread != IntPtr.Zero && lpProcessInformation.hThread != Win32.INVALID_HANDLE_VALUE)
                                {
                                    handle2 = lpProcessInformation.hThread;
                                }
                            }

                            if (!flag)
                            {
                                if ((error != 0xc1) && (error != 0xd8))
                                {
                                    throw new Win32Exception(error);
                                }

                                throw new Win32Exception(error, "InvalidApplication");
                            }
                        }
                        finally
                        {
                            if (password != IntPtr.Zero)
                            {
                                Marshal.ZeroFreeCoTaskMemUnicode(password);
                            }
                        }
                    }
                    else
                    {
                        RuntimeHelpers.PrepareConstrainedRegions();

                        try
                        {
                        }
                        finally
                        {
                            flag = Win32.CreateProcess(null, cmdLine, IntPtr.Zero, IntPtr.Zero, true, creationFlags, handle6.AddrOfPinnedObject(), workingDirectory, ref lpStartupInfo, out lpProcessInformation);

                            if (!flag)
                            {
                                error = Marshal.GetLastWin32Error();
                            }

                            if (lpProcessInformation.hProcess != IntPtr.Zero && lpProcessInformation.hProcess != Win32.INVALID_HANDLE_VALUE)
                            {
                                processHandle = lpProcessInformation.hProcess;
                            }

                            if (lpProcessInformation.hThread != IntPtr.Zero && lpProcessInformation.hThread != Win32.INVALID_HANDLE_VALUE)
                            {
                                handle2 = lpProcessInformation.hThread;
                            }
                        }

                        if (!flag)
                        {
                            if ((error != 0xc1) && (error != 0xd8))
                            {
                                throw new Win32Exception(error);
                            }

                            throw new Win32Exception(error, "InvalidApplication");
                        }
                    }
                }
                finally
                {
                    if (handle6.IsAllocated)
                    {
                        handle6.Free();
                    }

                    if (lpStartupInfo.hStdInput != null && !lpStartupInfo.hStdInput.IsInvalid)
                    {
                        lpStartupInfo.hStdInput.Close();
                    }

                    if (lpStartupInfo.hStdOutput != null && !lpStartupInfo.hStdOutput.IsInvalid)
                    {
                        lpStartupInfo.hStdOutput.Close();
                    }

                    if (lpStartupInfo.hStdError != null && !lpStartupInfo.hStdError.IsInvalid)
                    {
                        lpStartupInfo.hStdError.Close();
                    }
                }

                if (processHandle != IntPtr.Zero && processHandle != Win32.INVALID_HANDLE_VALUE)
                {
                    Win32.CloseHandle(handle2);
                }

                process = Process.GetProcessById((int)lpProcessInformation.dwProcessId);

                if (StartInfo.RedirectStandardInput)
                {
                    FieldInfo standardInput = typeof(Process).GetField("standardInput", BindingFlags.Instance | BindingFlags.NonPublic);
                    standardInput.SetValue(process, new StreamWriter(new FileStream(parentHandle, FileAccess.Write, 0x1000, false), Console.InputEncoding, 0x1000)
                    {
                        AutoFlush = true
                    });
                }

                if (StartInfo.RedirectStandardOutput)
                {
                    FieldInfo standardOutput = typeof(Process).GetField("standardOutput", BindingFlags.Instance | BindingFlags.NonPublic);
                    standardOutput.SetValue(process, new StreamReader(new FileStream(handle4, FileAccess.Read, 0x1000, false), (StartInfo.StandardOutputEncoding != null) ? StartInfo.StandardOutputEncoding : Console.OutputEncoding, true, 0x1000));
                }

                if (StartInfo.RedirectStandardError)
                {
                    FieldInfo standardError = typeof(Process).GetField("standardError", BindingFlags.Instance | BindingFlags.NonPublic);
                    standardError.SetValue(process, new StreamReader(new FileStream(handle5, FileAccess.Read, 0x1000, false), (StartInfo.StandardErrorEncoding != null) ? StartInfo.StandardErrorEncoding : Console.OutputEncoding, true, 0x1000));
                }
            }
            else
            {
                process = Process.Start(StartInfo);
            }

            return(new DllInjector(process, FreeOnDispose));
        }
Exemplo n.º 8
0
        /// <summary>
        /// Returns default environment for the process.
        /// If credentials are specified then the default environment is the default for that user.
        /// Otherwise the default is to inherit from this process.
        /// </summary>
        private Dictionary<string, string> CreateDefaultProcessEnvironment(NetworkCredential credential)
        {
            EnvironmentBlock envBlock = new EnvironmentBlock();

            if (credential == null)
            {
                envBlock = EnvironmentBlock.Create(Environment.GetEnvironmentVariables());
            }
            else
            {
                using (var safeUserToken = Utils.LogonAndGetUserPrimaryToken(credential))
                {
                    envBlock = EnvironmentBlock.CreateForUser(safeUserToken.DangerousGetHandle());
                }
            }

            return envBlock.ToDictionary();
        }
Exemplo n.º 9
0
        public Process LaunchProcessSuspended(ProcessStartInfo startInfo, bool inheritHandle = false)
        {
            string commandLine;

            if (!string.IsNullOrWhiteSpace(startInfo.Verb))
            {
                commandLine = string.Format("-runverb -verb \"{0}\" -exefile \"{1}\"",
                                            startInfo.Verb.Trim(), startInfo.FileName.Trim());

                string tempArg = startInfo.Arguments.Trim();
                if (!string.IsNullOrWhiteSpace(tempArg))
                {
                    commandLine += string.Format(" -arg \"{0}\"", tempArg);
                }

                startInfo.FileName = BootstrapProcess;
            }
            else
            {
                commandLine = startInfo.Arguments;
            }

            commandLine = BuildCommandLine(startInfo.FileName.Trim(), commandLine.Trim()).ToString();

            var      startupInfo       = new STARTUPINFO();
            var      processInfo       = new PROCESS_INFORMATION();
            bool     retVal            = false;
            int      errorCode         = 0;
            GCHandle environmentHandle = new GCHandle();

            try
            {
                // set up the creation flags paramater
                var creationFlags = ProcessCreationFlags.CREATE_SUSPENDED;

                if (startInfo.CreateNoWindow)
                {
                    creationFlags |= ProcessCreationFlags.CREATE_NO_WINDOW;
                }

                // set up the environment block parameter
                IntPtr environmentPtr = (IntPtr)0;
                if (startInfo.EnvironmentVariables != null)
                {
                    creationFlags |= ProcessCreationFlags.CREATE_UNICODE_ENVIRONMENT;
                    byte[] environmentBytes = EnvironmentBlock.ToByteArray(startInfo.EnvironmentVariables, true);
                    environmentHandle = GCHandle.Alloc(environmentBytes, GCHandleType.Pinned);
                    environmentPtr    = environmentHandle.AddrOfPinnedObject();
                }

                //fix working dir
                string workingDirectory = startInfo.WorkingDirectory;
                if (workingDirectory == string.Empty)
                {
                    workingDirectory = Environment.CurrentDirectory;
                }

                try { }
                finally
                {
                    retVal = NativeMethods.CreateProcess(
                        null,                    // we don't need this since all the info is in commandLine
                        commandLine,             // pointer to the command line string
                        IntPtr.Zero,             // pointer to process security attributes, we don't need to inheriat the handle
                        IntPtr.Zero,             // pointer to thread security attributes
                        inheritHandle,           // handle inheritance flag
                        creationFlags,           // creation flags
                        environmentPtr,          // pointer to new environment block
                        workingDirectory,        // pointer to current directory name
                        ref startupInfo,         // pointer to STARTUPINFO
                        out processInfo          // pointer to PROCESS_INFORMATION
                        );
                    if (!retVal)
                    {
                        errorCode = Marshal.GetLastWin32Error();
                    }
                    if (processInfo.hProcess != (IntPtr)0 && processInfo.hProcess != (IntPtr)NativeMethods.INVALID_HANDLE_VALUE)
                    {
                        _pid        = processInfo.dwProcessId;
                        _procHandle = processInfo.hProcess;
                    }
                    if (processInfo.hThread != (IntPtr)0 && processInfo.hThread != (IntPtr)NativeMethods.INVALID_HANDLE_VALUE)
                    {
                        _threadHandle = processInfo.hThread;
                        _tid          = processInfo.dwThreadId;
                    }
                }
                if (!retVal)
                {
                    if (errorCode == NativeMethods.ERROR_BAD_EXE_FORMAT || errorCode == NativeMethods.ERROR_EXE_MACHINE_TYPE_MISMATCH)
                    {
                        throw new Win32Exception(errorCode, "Invalid Application");
                    }
                    throw new Win32Exception(errorCode);
                }
                retVal = true;
            }
            finally
            {
                // free environment block
                if (environmentHandle.IsAllocated)
                {
                    environmentHandle.Free();
                }
            }

            if (_pid != 0)
            {
                return(Process.GetProcessById((int)_pid));
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 10
0
        private static unsafe int ExecWaitWithCaptureUnimpersonated(SafeUserTokenHandle userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName, string trueCmdLine)
        {
            IntSecurity.UnmanagedCode.Demand();
            if ((outputName == null) || (outputName.Length == 0))
            {
                outputName = tempFiles.AddExtension("out");
            }
            if ((errorName == null) || (errorName.Length == 0))
            {
                errorName = tempFiles.AddExtension("err");
            }
            FileStream stream  = CreateInheritedFile(outputName);
            FileStream stream2 = CreateInheritedFile(errorName);
            bool       flag    = false;

            Microsoft.Win32.SafeNativeMethods.PROCESS_INFORMATION lpProcessInformation = new Microsoft.Win32.SafeNativeMethods.PROCESS_INFORMATION();
            Microsoft.Win32.SafeHandles.SafeProcessHandle         processHandle        = new Microsoft.Win32.SafeHandles.SafeProcessHandle();
            Microsoft.Win32.SafeHandles.SafeThreadHandle          handle2 = new Microsoft.Win32.SafeHandles.SafeThreadHandle();
            SafeUserTokenHandle hNewToken = null;

            try
            {
                Microsoft.Win32.NativeMethods.STARTUPINFO startupinfo;
                StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);
                writer.Write(currentDir);
                writer.Write("> ");
                writer.WriteLine((trueCmdLine != null) ? trueCmdLine : cmd);
                writer.WriteLine();
                writer.WriteLine();
                writer.Flush();
                startupinfo = new Microsoft.Win32.NativeMethods.STARTUPINFO {
                    cb          = Marshal.SizeOf(startupinfo),
                    dwFlags     = 0x101,
                    wShowWindow = 0,
                    hStdOutput  = stream.SafeFileHandle,
                    hStdError   = stream2.SafeFileHandle,
                    hStdInput   = new SafeFileHandle(Microsoft.Win32.UnsafeNativeMethods.GetStdHandle(-10), false)
                };
                StringDictionary sd = new StringDictionary();
                foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables())
                {
                    sd[(string)entry.Key] = (string)entry.Value;
                }
                sd["_ClrRestrictSecAttributes"] = "1";
                byte[] buffer = EnvironmentBlock.ToByteArray(sd, false);
                try
                {
                    fixed(byte *numRef = buffer)
                    {
                        IntPtr lpEnvironment = new IntPtr((void *)numRef);

                        if ((userToken == null) || userToken.IsInvalid)
                        {
                            RuntimeHelpers.PrepareConstrainedRegions();
                            try
                            {
                                goto Label_0325;
                            }
                            finally
                            {
                                flag = Microsoft.Win32.NativeMethods.CreateProcess(null, new StringBuilder(cmd), null, null, true, 0, lpEnvironment, currentDir, startupinfo, lpProcessInformation);
                                if ((lpProcessInformation.hProcess != IntPtr.Zero) && (lpProcessInformation.hProcess != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE))
                                {
                                    processHandle.InitialSetHandle(lpProcessInformation.hProcess);
                                }
                                if ((lpProcessInformation.hThread != IntPtr.Zero) && (lpProcessInformation.hThread != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE))
                                {
                                    handle2.InitialSetHandle(lpProcessInformation.hThread);
                                }
                            }
                        }
                        flag = SafeUserTokenHandle.DuplicateTokenEx(userToken, 0xf01ff, null, 2, 1, out hNewToken);
                        if (flag)
                        {
                            RuntimeHelpers.PrepareConstrainedRegions();
                            try
                            {
                            }
                            finally
                            {
                                flag = Microsoft.Win32.NativeMethods.CreateProcessAsUser(hNewToken, null, cmd, null, null, true, 0, new HandleRef(null, lpEnvironment), currentDir, startupinfo, lpProcessInformation);
                                if ((lpProcessInformation.hProcess != IntPtr.Zero) && (lpProcessInformation.hProcess != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE))
                                {
                                    processHandle.InitialSetHandle(lpProcessInformation.hProcess);
                                }
                                if ((lpProcessInformation.hThread != IntPtr.Zero) && (lpProcessInformation.hThread != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE))
                                {
                                    handle2.InitialSetHandle(lpProcessInformation.hThread);
                                }
                            }
                        }
                    }
                }
                finally
                {
                    numRef = null;
                }
            }
            finally
            {
                if ((!flag && (hNewToken != null)) && !hNewToken.IsInvalid)
                {
                    hNewToken.Close();
                    hNewToken = null;
                }
                stream.Close();
                stream2.Close();
            }
Label_0325:
            if (flag)
            {
                try
                {
                    bool flag2;
                    ProcessWaitHandle handle4 = null;
                    try
                    {
                        handle4 = new ProcessWaitHandle(processHandle);
                        flag2   = handle4.WaitOne(0x927c0, false);
                    }
                    finally
                    {
                        if (handle4 != null)
                        {
                            handle4.Close();
                        }
                    }
                    if (!flag2)
                    {
                        throw new ExternalException(SR.GetString("ExecTimeout", new object[] { cmd }), 0x102);
                    }
                    int exitCode = 0x103;
                    if (!Microsoft.Win32.NativeMethods.GetExitCodeProcess(processHandle, out exitCode))
                    {
                        throw new ExternalException(SR.GetString("ExecCantGetRetCode", new object[] { cmd }), Marshal.GetLastWin32Error());
                    }
                    return(exitCode);
                }
                finally
                {
                    processHandle.Close();
                    handle2.Close();
                    if ((hNewToken != null) && !hNewToken.IsInvalid)
                    {
                        hNewToken.Close();
                    }
                }
            }
            int error = Marshal.GetLastWin32Error();

            if (error == 8)
            {
                throw new OutOfMemoryException();
            }
            Win32Exception    inner      = new Win32Exception(error);
            ExternalException exception2 = new ExternalException(SR.GetString("ExecCantExec", new object[] { cmd }), inner);

            throw exception2;
        }