示例#1
0
 internal static Win32Process CreateDebuggableProcess(string applicationName, string?commandLine)
 {
     unsafe
     {
         var startupInfo = new STARTUPINFOW();
         startupInfo.cb = (UInt32)sizeof(STARTUPINFOW);
         var   processInfo = new PROCESS_INFORMATION();
         Int32 success     = FALSE;
         fixed(char *lpApplicationName = applicationName)
         fixed(char *lpCommandLine = commandLine)
         {
             success = CreateProcessW(
                 lpApplicationName,
                 lpCommandLine,
                 null, null,
                 FALSE,
                 DEBUG_ONLY_THIS_PROCESS,
                 null,
                 null,
                 &startupInfo,
                 &processInfo);
         }
         ErrorOnFalse(success);
         var handleId = GetProcessId(processInfo.hProcess);
         ErrorOnFalse((Int32)handleId);
         return(new Win32Process(processInfo.hProcess, handleId));
     }
 }
示例#2
0
 static extern bool CreateProcessW(
     [MarshalAs(UnmanagedType.LPWStr)] string lpApplicationName,
     [MarshalAs(UnmanagedType.LPWStr)] string lpCommandLine,
     IntPtr lpProcessAttributes,
     IntPtr lpThreadAttributes,
     bool bInheritHandles,
     ProcessCreationFlags dwCreationFlags,
     IntPtr lpEnvironment,
     [MarshalAs(UnmanagedType.LPWStr)] string lpCurrentDirectory,
     ref STARTUPINFOW lpStartupInfo,
     out PROCESS_INFORMATION lpProcessInformation);
示例#3
0
文件: Loader.cs 项目: xNWP/advancedfx
 private static extern bool CreateProcessW(
     string lpApplicationName,
     string lpCommandLine,
     SECURITY_ATTRIBUTES lpProcessAttributes,
     SECURITY_ATTRIBUTES lpThreadAttributes,
     bool bInheritHandles,
     uint dwCreationFlags,
     string lpEnvironment,
     string lpCurrentDirectory,
     [In] ref STARTUPINFOW lpStartupInfo,
     out PROCESS_INFORMATION lpProcessInformation);
示例#4
0
        public static unsafe (Win32Job, List <AccountPrivilege>) StartProcess(IList <string> procargs, SessionSettings session)
        {
            var pi = new PROCESS_INFORMATION();
            var si = new STARTUPINFOW();
            var processCreationFlags = PROCESS_CREATION_FLAGS.CREATE_UNICODE_ENVIRONMENT |
                                       PROCESS_CREATION_FLAGS.CREATE_SUSPENDED;

            if (session.SpawnNewConsoleWindow)
            {
                processCreationFlags |= PROCESS_CREATION_FLAGS.CREATE_NEW_CONSOLE;
            }

            var args = string.Join(" ", procargs.Select((string s) => s.Contains(' ') ? "\"" + s + "\"" : s));
            var env  = GetEnvironmentString(session.AdditionalEnvironmentVars);

            fixed(char *pargs = args)
            {
                fixed(char *penv = env)
                {
                    CheckWin32Result(PInvoke.CreateProcess(null, pargs, null, null, false,
                                                           processCreationFlags, penv, null, si, out pi));
                }
            }

            var hProcess = new SafeFileHandle(pi.hProcess, true);

            try
            {
                var job = Win32JobModule.CreateAndAssignToProcess(hProcess, pi.dwProcessId,
                                                                  session.PropagateOnChildProcesses, session.ClockTimeLimitInMilliseconds);
                Win32JobModule.SetLimits(job, session);

                var privs = AccountPrivilegeModule.EnablePrivileges(hProcess, session.Privileges);

                // resume process main thread
                CheckWin32Result(PInvoke.ResumeThread(pi.hThread));

                return(job, privs);
            }
            catch
            {
                PInvoke.TerminateProcess(hProcess, 1);
                throw;
            }
            finally
            {
                // and we can close the thread handle
                PInvoke.CloseHandle(pi.hThread);
            }
        }
示例#5
0
        unsafe Dictionary <string, object> GetConsoleUserData()
        {
            var executableFilePath = Process.GetCurrentProcess().MainModule.FileName;

            nint token = 0;

            if (!PInvoke.WTSQueryUserToken(PInvoke.WTSGetActiveConsoleSessionId(), ref token))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            try
            {
                var tempFile = Path.GetTempFileName();
                var tempDir  = Path.GetTempFileName();
                File.Delete(tempDir);
                try
                {
                    using (var stdout = new FileStream(tempFile, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Inheritable))
                    {
                        var si = new STARTUPINFOW();
                        si.cb         = (uint)Marshal.SizeOf(si);
                        si.hStdOutput = new HANDLE(stdout.SafeFileHandle.DangerousGetHandle());
                        si.dwFlags    = Native.STARTF_USESTDHANDLES;
                        Environment.SetEnvironmentVariable("TMP", tempDir);
                        Environment.SetEnvironmentVariable("TEMP", tempDir);
                        if (!PInvoke.CreateProcessAsUser(new CloseHandleSafeHandle(token, false), null, $"\"{executableFilePath}\" --once", null, null, true, 0, null, null, si, out var pi))
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }
                        if (0 != PInvoke.WaitForSingleObject(new CloseHandleSafeHandle(pi.hProcess), 10000))
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }
                    }
                    return(JsonSerializer.Deserialize <Dictionary <string, object> >(File.ReadAllText(tempFile)));
                }
                finally
                {
                    File.Delete(tempFile);
                }
            }
            finally
            {
                PInvoke.CloseHandle(new HANDLE(token));
            }
        }
示例#6
0
        internal static void Cleanup()
        {
            if (Application.platform == RuntimePlatform.WindowsEditor)
            {
                // Use CreateProcessW as opposed to C# Process class to run
                // the script so that we could disable handle inheritance
                STARTUPINFOW startInfo = default;
                startInfo.cb = (uint)Marshal.SizeOf <STARTUPINFOW>();

                var batFile = Paths.Combine(EditorApplication.applicationContentsPath, "Tools", "RoslynScripts", "kill_csc_server.bat");
                if (!CreateProcessW(null, $"cmd.exe /c \"{batFile}\"", IntPtr.Zero, IntPtr.Zero, false, ProcessCreationFlags.CREATE_NO_WINDOW, IntPtr.Zero, null, ref startInfo, out var _))
                {
                    var lastError = Marshal.GetLastWin32Error();
                    Debug.LogError("Failed to kill csc server process: " + new Win32Exception(lastError).Message);
                }
            }
        }
示例#7
0
        public static unsafe (Win32Job, List <AccountPrivilege>) StartProcessUnderDebuggerAndDetach(IList <string> procargs, SessionSettings session)
        {
            var pi = new PROCESS_INFORMATION();
            var si = new STARTUPINFOW();
            var processCreationFlags = PROCESS_CREATION_FLAGS.CREATE_UNICODE_ENVIRONMENT |
                                       PROCESS_CREATION_FLAGS.DEBUG_ONLY_THIS_PROCESS;

            if (session.SpawnNewConsoleWindow)
            {
                processCreationFlags |= PROCESS_CREATION_FLAGS.CREATE_NEW_CONSOLE;
            }

            var args = string.Join(" ", procargs);
            var env  = GetEnvironmentString(session.AdditionalEnvironmentVars);

            fixed(char *pargs = args)
            {
                fixed(char *penv = env)
                {
                    CheckWin32Result(PInvoke.CreateProcess(null, pargs, null, null, false,
                                                           processCreationFlags, penv, null, si, out pi));
                }
            }

            var hProcess = new SafeFileHandle(pi.hProcess, true);

            CheckWin32Result(PInvoke.DebugSetProcessKillOnExit(false));

            var job = Win32JobModule.CreateAndAssignToProcess(hProcess, pi.dwProcessId,
                                                              session.PropagateOnChildProcesses, session.ClockTimeLimitInMilliseconds);

            Win32JobModule.SetLimits(job, session);

            var privs = AccountPrivilegeModule.EnablePrivileges(hProcess, session.Privileges);

            // resume process main thread by detaching from the debuggee
            CheckWin32Result(PInvoke.DebugActiveProcessStop(pi.dwProcessId));
            // and we can close the thread handle
            PInvoke.CloseHandle(pi.hThread);

            return(job, privs);
        }
示例#8
0
 private static extern bool CreateProcessWithTokenW(IntPtr hToken, UInt32 dwLogonFlags,
                                                    string lpApplicationName, string lpCommandLine, UInt32 dwCreationFlags, IntPtr lpEnvironment,
                                                    string lpCurrentDirectory, ref STARTUPINFOW lpStartupInfo, ref PROCESS_INFORMATION lpProcessInformation);
示例#9
0
        static bool CreateProcessW_Hooked([MarshalAsAttribute(UnmanagedType.LPWStr)] string lpApplicationName, IntPtr lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, [MarshalAsAttribute(UnmanagedType.Bool)] bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, [MarshalAsAttribute(UnmanagedType.LPWStr)] string lpCurrentDirectory, ref STARTUPINFOW lpStartupInfo, [OutAttribute()] out PROCESS_INFORMATION lpProcessInformation)
        {
            try
            {
                MalMonInject This = (MalMonInject)HookRuntimeInfo.Callback;

                lock (This.Queue)
                {
                    //Time + Pid + Tid + Api + Content
                    This.Queue.Push(ActivityMonitor.FormatMessage(DateTime.Now, "CreateProcessW", Marshal.PtrToStringUni(lpCommandLine)));
                }
            }
            catch
            {
            }

            // call original API...
            return CreateProcessW(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, ref lpStartupInfo, out lpProcessInformation);
        }
 public static extern void GetStartupInfoW(ref STARTUPINFOW lpStartupInfo);
示例#11
0
        bool CreateProcessW_Hooked([MarshalAsAttribute(UnmanagedType.LPWStr)] string lpApplicationName, IntPtr lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, [MarshalAsAttribute(UnmanagedType.Bool)] bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, [MarshalAsAttribute(UnmanagedType.LPWStr)] string lpCurrentDirectory, ref STARTUPINFOW lpStartupInfo, [OutAttribute()] out PROCESS_INFORMATION lpProcessInformation)
        {
            bool result = false;

            result = CreateProcessW(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, ref lpStartupInfo, out lpProcessInformation);

            try
            {
                _server.ReportMessage(string.Format("[{0}:{1}]: CreateProcess ({2} created name) \"{3}\"",
                                                    RemoteHooking.GetCurrentProcessId(), RemoteHooking.GetCurrentThreadId()
                                                    , lpApplicationName, lpStartupInfo.wShowWindow));
            }
            catch
            {
            }

            return(result);
        }
示例#12
0
 public STARTUPINFOEX()
 {
     startupInfo    = new STARTUPINFOW();
     startupInfo.cb = (UInt32)Marshal.SizeOf(this);
 }
示例#13
0
        private static void LaunchWithShellToken(string launchPath, string cmd, string workingDir)
        {
            IntPtr hShellProcess = IntPtr.Zero, hShellProcessToken = IntPtr.Zero, hPrimaryToken = IntPtr.Zero;

            IntPtr       hProcessToken = IntPtr.Zero;
            STARTUPINFOW si            = new STARTUPINFOW();

            si.cb = (UInt32)Marshal.SizeOf(typeof(STARTUPINFOW));
            PROCESS_INFORMATION pi = new PROCESS_INFORMATION();

            // hwnd不需要释放
            // hwnd no need to release
            IntPtr hwnd  = IntPtr.Zero;
            UInt32 dwPID = 0;
            bool   ret;
            Int32  dwLastErr;

            try
            {
                // 为当前进程开启SE_INCREASE_QUOTA_NAME权限(调用CreateProcessWithTokenW需要这个权限)
                // Enable the SeIncreaseQuotaPrivilege in your current token (call CreateProcessWithTokenW need this privilege)
                if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, ref hProcessToken))
                {
                    dwLastErr = Marshal.GetLastWin32Error();
                    throw new ApplicationException("OpenProcessToken failed: 0x" + dwLastErr.ToString("X"));
                }
                else
                {
                    TOKEN_PRIVILEGES tkp  = TOKEN_PRIVILEGES.Create();
                    LUID             luid = new LUID();
                    if (!LookupPrivilegeValueW(null, SE_INCREASE_QUOTA_NAME, ref luid))
                    {
                        dwLastErr = Marshal.GetLastWin32Error();
                        throw new ApplicationException("LookupPrivilegeValueW failed: 0x" + dwLastErr.ToString("X"));
                    }

                    tkp.Privileges[0].Luid       = luid;
                    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
                    AdjustTokenPrivileges(hProcessToken, false, ref tkp, 0, IntPtr.Zero, IntPtr.Zero);
                    dwLastErr = Marshal.GetLastWin32Error();
                    if (ERROR_SUCCESS != dwLastErr)
                    {
                        throw new ApplicationException("AdjustTokenPrivileges failed: 0x" + dwLastErr.ToString("X"));
                    }
                }

                // 获取Shell的HWND
                // Get an HWND representing the desktop shell
                hwnd = GetShellWindow();
                if (IntPtr.Zero == hwnd)
                {
                    throw new ApplicationException("No desktop shell is present");
                }

                // 获取Shell的PID
                // Get the Process ID (PID) of the process associated with that window
                GetWindowThreadProcessId(hwnd, ref dwPID);
                if (0 == dwPID)
                {
                    throw new ApplicationException("Unable to get PID of desktop shell");
                }

                // 打开Shell进程对象
                // Open that process
                hShellProcess = OpenProcess(PROCESS_QUERY_INFORMATION, false, dwPID);
                if (hShellProcess == IntPtr.Zero)
                {
                    dwLastErr = Marshal.GetLastWin32Error();
                    throw new ApplicationException("Can't open desktop shell process: 0x" + dwLastErr.ToString("X"));
                }

                // 获取Shell进程的Token
                // Get the access token from that process
                ret = OpenProcessToken(hShellProcess, TOKEN_DUPLICATE, ref hShellProcessToken);
                if (!ret)
                {
                    dwLastErr = Marshal.GetLastWin32Error();
                    throw new ApplicationException("Can't get process token of desktop shell: 0x" + dwLastErr.ToString("X"));
                }

                // 通过Shell进程Token,复制一份Primary Token
                // Make a primary token with that token
                UInt32 dwTokenRights = TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID;
                ret = DuplicateTokenEx(hShellProcessToken, dwTokenRights, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation,
                                       TOKEN_TYPE.TokenPrimary, ref hPrimaryToken);
                if (!ret)
                {
                    dwLastErr = Marshal.GetLastWin32Error();
                    throw new ApplicationException("Can't get primary token: 0x" + dwLastErr.ToString("X"));
                }

                // 用复制得到的Token启动程序
                // Start the new process with that primary token
                ret = CreateProcessWithTokenW(hPrimaryToken, 0, launchPath, cmd, 0, IntPtr.Zero,
                                              workingDir, ref si, ref pi);
                if (!ret)
                {
                    dwLastErr = Marshal.GetLastWin32Error();
                    throw new ApplicationException("CreateProcessWithTokenW failed: 0x" + dwLastErr.ToString("X"));
                }
            }
            finally
            {
                if (hProcessToken != IntPtr.Zero)
                {
                    CloseHandle(hProcessToken);
                }
                if (hPrimaryToken != IntPtr.Zero)
                {
                    CloseHandle(hPrimaryToken);
                }
                if (hShellProcessToken != IntPtr.Zero)
                {
                    CloseHandle(hShellProcessToken);
                }
                if (hShellProcess != IntPtr.Zero)
                {
                    CloseHandle(hShellProcess);
                }
                if (si.hStdError != IntPtr.Zero)
                {
                    CloseHandle(si.hStdError);
                }
                if (si.hStdInput != IntPtr.Zero)
                {
                    CloseHandle(si.hStdInput);
                }
                if (si.hStdOutput != IntPtr.Zero)
                {
                    CloseHandle(si.hStdOutput);
                }
                if (pi.hThread != IntPtr.Zero)
                {
                    CloseHandle(pi.hThread);
                }
                if (pi.hProcess != IntPtr.Zero)
                {
                    CloseHandle(pi.hProcess);
                }
            }
        }
示例#14
0
文件: Loader.cs 项目: iqhl/advancedfx
        public static bool Load(IEnumerable <GetHookPathDelegate> getHookPathCollection, string programPath, string cmdLine, string environment = null)
        {
            bool bOk = true;

            try
            {
                string programOptions   = "\"" + programPath + "\" " + cmdLine;
                string programDirectory = System.IO.Path.GetDirectoryName(programPath);

                PROCESS_INFORMATION processInfo = new PROCESS_INFORMATION();

                STARTUPINFOW startupInfo = new STARTUPINFOW();
                startupInfo.cb = (UInt32)Marshal.SizeOf(startupInfo);

                if (!CreateProcessW(
                        programPath
                        , programOptions
                        , null
                        , null
                        , true // inherit handles
                        ,      //CREATE_DEFAULT_ERROR_MODE|
                        CREATE_NEW_PROCESS_GROUP |
                        DETACHED_PROCESS |
                        CREATE_SUSPENDED
                        //DEBUG_ONLY_THIS_PROCESS|
                        //DEBUG_PROCESS				// we want to catch debug event's (sadly also of childs)
                        | CREATE_UNICODE_ENVIRONMENT
                        , environment
                        , programDirectory
                        , ref startupInfo
                        , out processInfo)
                    )
                {
                    throw new System.ApplicationException("Failed to launch program, error code: " + Marshal.GetLastWin32Error());
                }

                try
                {
                    bool isProcess64Bit = IsProcess64Bit(processInfo.hProcess);

                    foreach (GetHookPathDelegate getHookPath in getHookPathCollection)
                    {
                        string hookPath = getHookPath(isProcess64Bit);

                        using (System.Diagnostics.Process injector = new System.Diagnostics.Process())
                        {
                            injector.StartInfo.UseShellExecute = false;
                            injector.StartInfo.FileName        = System.AppDomain.CurrentDomain.BaseDirectory + (isProcess64Bit ? "\\x64" : "") + "\\injector.exe";
                            injector.StartInfo.CreateNoWindow  = true;
                            injector.StartInfo.Arguments       = processInfo.dwProcessId.ToString() + " " + hookPath;

                            try
                            {
                                injector.Start();
                            }
                            catch (Exception e)
                            {
                                throw new System.AccessViolationException(
                                          "Failed to start injector: " + injector.StartInfo.FileName + "." + Environment.NewLine
                                          + "Error: " + e.ToString() + Environment.NewLine
                                          + "Solution: Check that your Anti Virus did not remove it due to a false positive. If so restore it and add an exception for injector / the HLAE folder."
                                          );
                            }

                            injector.WaitForExit();

                            if (0 != injector.ExitCode)
                            {
                                InjectorErrors.Error error = InjectorErrors.Instance.GetById(injector.ExitCode);

                                throw new System.AccessViolationException(
                                          "Injector(" + (isProcess64Bit ? "x64" : "x86") + ") failed," + Environment.NewLine
                                          + "Could not inject \"" + hookPath + "\"." + Environment.NewLine
                                          + "Error: " + error.Text + Environment.NewLine
                                          + "Solution: " + error.Solution
                                          );
                            }
                        }
                    }
                }
                finally
                {
                    System.Threading.Thread.Sleep(2000);

                    ResumeThread(processInfo.hThread);

                    CloseHandle(processInfo.hThread);
                    CloseHandle(processInfo.hProcess);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Loader failed", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return(false);
            }

            return(bOk);
        }
示例#15
0
        static bool CreateProcessW_Hooked([MarshalAsAttribute(UnmanagedType.LPWStr)] string lpApplicationName, IntPtr lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, [MarshalAsAttribute(UnmanagedType.Bool)] bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, [MarshalAsAttribute(UnmanagedType.LPWStr)] string lpCurrentDirectory, ref STARTUPINFOW lpStartupInfo, [OutAttribute()] out PROCESS_INFORMATION lpProcessInformation)
        {
            try
            {
                MalMonInject This = (MalMonInject)HookRuntimeInfo.Callback;

                lock (This.Queue)
                {
                    //Time + Pid + Tid + Api + Content
                    This.Queue.Push(ActivityMonitor.FormatMessage(DateTime.Now, "CreateProcessW", Marshal.PtrToStringUni(lpCommandLine)));
                }
            }
            catch
            {
            }

            // call original API...
            return(CreateProcessW(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, ref lpStartupInfo, out lpProcessInformation));
        }
示例#16
0
        public static bool Load(IEnumerable <GetHookPathDelegate> getHookPathCollection, string programPath, string cmdLine, string environment = null, bool showErrorMessage = true)
        {
            try
            {
                string programOptions   = "\"" + programPath + "\" " + cmdLine;
                string programDirectory = System.IO.Path.GetDirectoryName(programPath);

                PROCESS_INFORMATION processInfo = new PROCESS_INFORMATION();

                STARTUPINFOW startupInfo = new STARTUPINFOW();
                startupInfo.cb = (UInt32)Marshal.SizeOf(startupInfo);

                if (!CreateProcessW(
                        programPath
                        , programOptions
                        , null
                        , null
                        , true // inherit handles
                        ,      //CREATE_DEFAULT_ERROR_MODE|
                        CREATE_NEW_PROCESS_GROUP |
                        DETACHED_PROCESS |
                        CREATE_SUSPENDED
                        //DEBUG_ONLY_THIS_PROCESS|
                        //DEBUG_PROCESS				// we want to catch debug event's (sadly also of childs)
                        | CREATE_UNICODE_ENVIRONMENT
                        , environment
                        , programDirectory
                        , ref startupInfo
                        , out processInfo)
                    )
                {
                    throw HlaeErrors.LoaderCreateProcessException(Marshal.GetLastWin32Error());
                }

                try
                {
                    bool isProcess64Bit = IsProcess64Bit(processInfo.hProcess);

                    foreach (GetHookPathDelegate getHookPath in getHookPathCollection)
                    {
                        string hookPath = getHookPath(isProcess64Bit);

                        using (System.Diagnostics.Process injector = new System.Diagnostics.Process())
                        {
                            injector.StartInfo.UseShellExecute        = false;
                            injector.StartInfo.FileName               = System.AppDomain.CurrentDomain.BaseDirectory + (isProcess64Bit ? "\\x64" : "") + "\\injector.exe";
                            injector.StartInfo.CreateNoWindow         = true;
                            injector.StartInfo.RedirectStandardInput  = true;
                            injector.StartInfo.RedirectStandardOutput = true;

                            try
                            {
                                injector.Start();
                            }
                            catch (Exception e)
                            {
                                throw HlaeErrors.InjectorStartException(
                                          injector.StartInfo.FileName,
                                          e
                                          );
                            }

                            AfxError error = null;

                            IFormatter formatter = new advancedfx.injector.interop.Formatter();

                            using (Stream injectorIn = injector.StandardInput.BaseStream)
                            {
                                using (Stream injectorOut = injector.StandardOutput.BaseStream)
                                {
                                    advancedfx.injector.interop.InjectMessage injectMessage = new advancedfx.injector.interop.InjectMessage();
                                    injectMessage.ProcessId = processInfo.dwProcessId;
                                    injectMessage.DllPath   = hookPath;

                                    formatter.Serialize(injectorIn, injectMessage);
                                    injectorIn.Flush();

                                    bool injectorExit = false;

                                    while (!injectorExit)
                                    {
                                        advancedfx.injector.interop.ProcessMessage m = (advancedfx.injector.interop.ProcessMessage)formatter.Deserialize(injectorOut);

                                        switch (m)
                                        {
                                        case advancedfx.injector.interop.ExceptionError exceptionError:
                                            if (null == error)
                                            {
                                                error = HlaeErrors.Unknown;
                                            }
                                            break;

                                        case advancedfx.injector.interop.OpenProcessError openProcessError:
                                            if (null == error)
                                            {
                                                error = HlaeErrors.OpenProcessFailed;
                                            }
                                            break;

                                        case advancedfx.injector.interop.VirtualAllocExArgDllDirError virtualAllocExArgDllDirError:
                                            if (null == error)
                                            {
                                                error = HlaeErrors.VirtualAllocExReadWriteFailed;
                                            }
                                            break;

                                        case advancedfx.injector.interop.VirtualAllocExArgDllFilePathError virtualAllocExArgDllFilePathError:
                                            if (null == error)
                                            {
                                                error = HlaeErrors.VirtualAllocExReadWriteFailed;
                                            }
                                            break;

                                        case advancedfx.injector.interop.GetImageError getImageError:
                                            if (null == error)
                                            {
                                                error = HlaeErrors.GetImageFailed;
                                            }
                                            break;

                                        case advancedfx.injector.interop.VirtualAllocExImageError virtualAllocExImageError:
                                            if (null == error)
                                            {
                                                error = HlaeErrors.VirtualAllocExReadWriteExecuteFailed;
                                            }
                                            break;

                                        case advancedfx.injector.interop.WriteProcessMemoryArgDllDirError writeProcessMemoryArgDllDirError:
                                            if (null == error)
                                            {
                                                error = HlaeErrors.WriteProcessMemoryFailed;
                                            }
                                            break;

                                        case advancedfx.injector.interop.WriteProcessMemoryArgDllFilePathError writeProcessMemoryArgDllFilePathError:
                                            if (null == error)
                                            {
                                                error = HlaeErrors.WriteProcessMemoryFailed;
                                            }
                                            break;

                                        case advancedfx.injector.interop.WriteProcessMemoryImageError writeProcessMemoryImageError:
                                            if (null == error)
                                            {
                                                error = HlaeErrors.WriteProcessMemoryFailed;
                                            }
                                            break;

                                        case advancedfx.injector.interop.FlushInstructionCacheError flushInstructionCacheError:
                                            if (null == error)
                                            {
                                                error = HlaeErrors.FlushInstructionCacheFailed;
                                            }
                                            break;

                                        case advancedfx.injector.interop.CreateRemoteThreadError createRemoteThreadError:
                                            if (null == error)
                                            {
                                                error = HlaeErrors.CreateRemoteThreadFailed;
                                            }
                                            break;

                                        case advancedfx.injector.interop.ContinueWaitingQuestion contineWaitingQuestion:
                                        {
                                            advancedfx.injector.interop.ContinueWaiting r = new advancedfx.injector.interop.ContinueWaiting();
                                            r.Response = DialogResult.Yes == MessageBox.Show(L10n._("Image injection problem.\nContinue waiting?"), L10n._("injector Warning"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                                            formatter.Serialize(injectorIn, r);
                                            injectorIn.Flush();
                                        }
                                        break;

                                        case advancedfx.injector.interop.TerminateThreadError terminateThreadError:
                                            // ignore for now
                                            break;

                                        case advancedfx.injector.interop.GetExitCodeThreadError getExitCodeThreadError:
                                            // ignore for now
                                            break;

                                        case advancedfx.injector.interop.InvalidExitCodeError invalidExitCodeError:
                                            if (null == error)
                                            {
                                                error = InjectorErrors.AfxHookUnknown;
                                            }
                                            break;

                                        case advancedfx.injector.interop.KnownExitCodeError knownExitCodeError:
                                            if (null == error)
                                            {
                                                error = InjectorErrors.Instance.GetById((int)knownExitCodeError.ThreadExitCode);
                                            }
                                            break;

                                        case advancedfx.injector.interop.CloseHandleThreadError closeHandleError:
                                            // ignore for now
                                            break;

                                        case advancedfx.injector.interop.VirtualFreeExImageError virtualFreeExImageError:
                                            // ignore for now
                                            break;

                                        case advancedfx.injector.interop.VirtualFreeExArgFilePathError virtualFreeExArgFilePathError:
                                            // ignore for now
                                            break;

                                        case advancedfx.injector.interop.VirtualFreeExArgDllDirError virtualFreeExArgDllDirError:
                                            // ignore for now
                                            break;

                                        case advancedfx.injector.interop.CloseHandleProcessError closeHandleProcessError:
                                            // ignore for now
                                            break;

                                        case advancedfx.injector.interop.InjectResponse injectResponse:
                                            bool injectorOk = injectResponse.Response;
                                            injector.WaitForExit();
                                            if (!injectorOk)
                                            {
                                                throw null == error ? HlaeErrors.Unknown : error;
                                            }
                                            injectorExit = true;
                                            break;

                                        default:
                                            throw HlaeErrors.Unknown;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                finally
                {
                    System.Threading.Thread.Sleep(2000);

                    ResumeThread(processInfo.hThread);

                    CloseHandle(processInfo.hThread);
                    CloseHandle(processInfo.hProcess);
                }
            }
            catch (AfxError e)
            {
                if (showErrorMessage)
                {
                    using (ErrorDialogue frm = new ErrorDialogue())
                    {
                        frm.Error = e;
                        frm.ShowDialog();
                    }
                }

                return(false);
            }
            catch (Exception e)
            {
                if (showErrorMessage)
                {
                    using (ErrorDialogue frm = new ErrorDialogue())
                    {
                        frm.Error = HlaeErrors.LoaderException(e);
                        frm.ShowDialog();
                    }
                }

                return(false);
            }

            return(true);
        }
示例#17
0
 public static partial void GetStartupInfoW(ref STARTUPINFOW lpStartupInfo);
示例#18
0
 public static extern bool CreateProcessAsUser([In()] IntPtr hToken, IntPtr lpApplicationName, [In()][MarshalAs(UnmanagedType.LPWStr)] string lpCommandLine, [In()] IntPtr lpProcessAttributes, [In()] IntPtr lpThreadAttributes, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandles, uint dwCreationFlags, [In()] IntPtr lpEnvironment, [In()][MarshalAs(UnmanagedType.LPWStr)] string lpCurrentDirectory, [In()] ref STARTUPINFOW lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
示例#19
0
文件: Loader.cs 项目: xNWP/advancedfx
        public static bool Load(IEnumerable <GetHookPathDelegate> getHookPathCollection, string programPath, string cmdLine, string environment = null, bool showErrorMessage = true)
        {
            bool bOk = true;

            try
            {
                string programOptions   = "\"" + programPath + "\" " + cmdLine;
                string programDirectory = System.IO.Path.GetDirectoryName(programPath);

                PROCESS_INFORMATION processInfo = new PROCESS_INFORMATION();

                STARTUPINFOW startupInfo = new STARTUPINFOW();
                startupInfo.cb = (UInt32)Marshal.SizeOf(startupInfo);

                if (!CreateProcessW(
                        programPath
                        , programOptions
                        , null
                        , null
                        , true // inherit handles
                        ,      //CREATE_DEFAULT_ERROR_MODE|
                        CREATE_NEW_PROCESS_GROUP |
                        DETACHED_PROCESS |
                        CREATE_SUSPENDED
                        //DEBUG_ONLY_THIS_PROCESS|
                        //DEBUG_PROCESS				// we want to catch debug event's (sadly also of childs)
                        | CREATE_UNICODE_ENVIRONMENT
                        , environment
                        , programDirectory
                        , ref startupInfo
                        , out processInfo)
                    )
                {
                    throw new System.ApplicationException("Failed to launch program, error code: " + Marshal.GetLastWin32Error());
                }

                try
                {
                    bool isProcess64Bit = IsProcess64Bit(processInfo.hProcess);

                    foreach (GetHookPathDelegate getHookPath in getHookPathCollection)
                    {
                        string hookPath = getHookPath(isProcess64Bit);

                        using (System.Diagnostics.Process injector = new System.Diagnostics.Process())
                        {
                            injector.StartInfo.UseShellExecute = false;
                            injector.StartInfo.FileName        = System.AppDomain.CurrentDomain.BaseDirectory + (isProcess64Bit ? "\\x64" : "") + "\\injector.exe";
                            injector.StartInfo.CreateNoWindow  = true;
                            injector.StartInfo.Arguments       = processInfo.dwProcessId.ToString() + " " + hookPath;

                            try
                            {
                                injector.Start();
                            }
                            catch (Exception e)
                            {
                                throw HlaeErrors.InjectorStartException(
                                          injector.StartInfo.FileName,
                                          e
                                          );
                            }

                            injector.WaitForExit();

                            if (0 != injector.ExitCode)
                            {
                                throw InjectorErrors.Instance.GetById(injector.ExitCode);
                            }
                        }
                    }
                }
                finally
                {
                    System.Threading.Thread.Sleep(2000);

                    ResumeThread(processInfo.hThread);

                    CloseHandle(processInfo.hThread);
                    CloseHandle(processInfo.hProcess);
                }
            }
            catch (Exception e)
            {
                if (showErrorMessage)
                {
                    using (ErrorDialogue frm = new ErrorDialogue())
                    {
                        frm.Error = HlaeErrors.LoaderException(e);
                        frm.ShowDialog();
                    }
                }

                return(false);
            }

            return(bOk);
        }