Пример #1
0
        public static bool Init(string path, int windowState = 0, bool isInstallM16 = true, bool isDebug = false)
        {
            Global.Registry.Warcraft.SetFullQualityGraphics();
            string EXEPath = Path.Combine(path, "Warcraft III.exe");

            if (!(File.Exists(EXEPath) || File.Exists(EXEPath = Path.Combine(path, "war3.exe"))) ||
                FileVersionInfo.GetVersionInfo(EXEPath).FileVersion != "1.28.5.7680")
            {
                return(false);
            }
            CheckDelete(Path.Combine(path, "m16l.mix"));
            if (isInstallM16)
            {
                string M16Mix    = Path.Combine(path, "M16.mix");
                string M16Mixnew = $"{M16Mix}_new";
                if (File.Exists(M16Mixnew))
                {
                    CheckDelete(M16Mix);
                    File.Move(M16Mixnew, M16Mix);
                }
                else
                {
                    CheckInstall(M16Mix, Resources.M16);
                }
            }
            string JNServicePath       = Path.Combine(Global.Globals.ResourcePath, "JNService");
            string RuntimePath         = Path.Combine(JNServicePath, "Cirnix.JassNative.Runtime.dll");
            string JNServicePluginPath = Path.Combine(JNServicePath, "Plugins");

            CheckDirectory(JNServicePath);
            CheckInstall(RuntimePath, Resources.Cirnix_JassNative_Runtime);
            CheckInstall(Path.Combine(JNServicePath, "Cirnix.JassNative.Plugin.dll"), Resources.Cirnix_JassNative_Plugin);
            CheckDirectory(JNServicePluginPath);
            CheckInstall(Path.Combine(JNServicePluginPath, "Cirnix.JassNative.dll"), Resources.Cirnix_JassNative);
            CheckInstall(Path.Combine(JNServicePluginPath, "Cirnix.JassNative.Common.dll"), Resources.Cirnix_JassNative_Common);
            //Global.LogManager.Write($"InEXEPath = {EXEPath}\n"
            //                      + $"InCommandLine = {((windowState == 0) ? "-window" : ((windowState == 1) ? "-nativefullscr" : ""))}\n"
            //                      + $"InProcessCreationFlags = 0\n"
            //                      + $"InLibraryPath_x86 = {RuntimePath}\n"
            //                      + $"InLibraryPath_x64 = {RuntimePath}\n"
            //                      + $"OutProcessId = \n"
            //                      + $"InPassThruArgs[0] = {isDebug}\n"
            //                      + $"InPassThruArgs[1] = {CurrentPath}\n"
            //                      + $"InPassThruArgs[2] = {path}");
            //Config.HelperLibraryLocation = CurrentPath;
            string WindowsStateString;

            switch (windowState)
            {
            case 0: WindowsStateString = "-windows"; break;

            case 1: WindowsStateString = string.Empty; break;

            case 2: WindowsStateString = "-nativefullscr"; break;

            default: return(false);
            }
            RemoteHooking.CreateAndInject(EXEPath, WindowsStateString, 0, RuntimePath, RuntimePath, out _, isDebug, JNServicePath, path);
            return(true);
        }
Пример #2
0
        public HookEntity Handle(ProxyEntity request)
        {
            return(_repository.ActionResult(x => x.Port == request.Port, x =>
            {
                HookElement _hook = x.Hooker.Hook;

                RemoteHooking.CreateAndInject(
                    x.Hooker.ExePath,
                    string.Empty,
                    0x00000004,
                    InjectionOptions.DoNotRequireStrongName,
                    "./SocketHook.dll",
                    "./SocketHook.dll",
                    out _hook.ProcessId,
                    _hook.ChannelName,
                    request.Port);

                while (_hook.ProcessId == 0)
                {
                    ;
                }

                x.ProcessId = _hook.ProcessId;

                logger.Debug($"Process id : {_hook.ProcessId}");

                return x;
            }).Hooker);
        }
Пример #3
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                args = new[] { @"C:\Program Files (x86)\Steam\steamapps\common\Hades\x64\Hades.exe" }
            }
            ;
            string clientArgs = "";

            if (Debugger.IsAttached)
            {
                DebugHelper.DetachDebugger();
                clientArgs += "--launch-debugger";
            }
            RemoteHooking.CreateAndInject(args[0],
                                          clientArgs,
                                          InProcessCreationFlags: 0,
                                          InjectionOptions.DoNotRequireStrongName,
                                          typeof(EntryPoint).Assembly.Location,
                                          typeof(EntryPoint).Assembly.Location,
                                          out int processID);

            Process.GetProcessById(processID).WaitForExit();
        }
    }
Пример #4
0
        public void Start(string targetExecutable, string commandLine = "")
        {
            try
            {
                // All loaded modules should use .Net Framework <= 3.5
                Config.Register(
                    "Lua injection",

                    "LuaInjectAgent.dll",
                    "System.ComponentModel.Composition.dll"
                    );

                string channelName = null;
                RemoteHooking.IpcCreateServer <Client>(ref channelName, WellKnownObjectMode.SingleCall);

                int targetPid;

                RemoteHooking.CreateAndInject(targetExecutable, commandLine, 0,
                                              "LuaInjectAgent.dll",
                                              "LuaInjectAgent.dll",
                                              out targetPid,

                                              channelName,                                                  //channel
                                              Path.Combine(Directory.GetCurrentDirectory(), "HookPlugins"), //plugins directory
                                              Path.Combine(Directory.GetCurrentDirectory(), "Config"),      //config directory
                                              targetExecutable                                              //target executable
                                              );
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + "\n" + e.StackTrace, "Failed", MessageBoxButtons.OK);
            }
        }
Пример #5
0
        public bool TryCreateAndInject(string exePath, int redirectionPort, params string[] redirectedIps)
        {
            if (!File.Exists(exePath))
            {
                return(false);
            }
            if (redirectionPort == default)
            {
                throw new ArgumentNullException(nameof(redirectionPort));
            }

            RemoteHooking.CreateAndInject(
                exePath,
                string.Empty,
                0x00000004,
                InjectionOptions.DoNotRequireStrongName,
                _settings.HookPath,
                _settings.HookPath,
                out var pId,
                _ipcChannelName,
                redirectedIps,
                redirectionPort);

            _registeredPid.TryAdd(pId, pId);
            return(true);
        }
Пример #6
0
        /// <summary>
        /// Creates and injects the current <see cref="VirtualizedProcess"/>,
        /// and sets the created process component to the <see cref="_process"/> variable.
        /// </summary>
        /// <exception cref="FileNotFoundException"></exception>
        private void CreateAndInject()
        {
            int processId;
            // Get the location of the library to inject
            string libraryLocation = HostCore.Configuration.Application.LibtoInject;

            if (!File.Exists(libraryLocation))
            {
                throw new FileNotFoundException("Unable to locate the library to inject.", libraryLocation);
            }
            RemoteHooking.CreateAndInject(
                Path.Combine(_startInfo.WorkingDirectory.FileName, _startInfo.Files.Executable.FileName),
                // Optional command line parameters for process creation
                _startInfo.Arguments,
                // ProcessCreationFlags, no conditions are set on the created process.
                0,
                // Absolute paths of the libraries to inject, we use the same one for 32bit and 64bit
                libraryLocation, libraryLocation,
                // The process ID of the newly created process
                out processId,
                // Extra parameters being passed to the injected library entry points Run() and Initialize()
                _connection.ChannelName);
            // The process has been created, set the _process variable.
            _process = SystemProcess.GetProcessById(processId, HostCore.Runtime.CurrentProcess.MachineName);
            _process.EnableRaisingEvents = true;
            _process.Exited += Process_Exited;
        }
Пример #7
0
        /// <summary>
        /// Executes VB6. The VB6 log output is written to the specified writer.
        /// </summary>
        public int Execute(TextWriter writer)
        {
            Prepare();

            if (File.Exists(log))
            {
                File.Delete(log);
            }

            // generate new channel to call back into parent
            string channelName = null;

            RemoteHooking.IpcCreateServer <RemoteExecutor>(ref channelName, WellKnownObjectMode.Singleton, this);

            // spawn VB6 process
            RemoteHooking.CreateAndInject(
                Exe,
                BuildArgs(),
                0,
                InjectionOptions.DoNotRequireStrongName,
                typeof(RemoteEntryPoint).Assembly.Location,
                typeof(RemoteEntryPoint).Assembly.Location,
                out var pid,
                channelName);

            // wait for exit of process
            var prc = Process.GetProcessById(pid);

            while (prc != null && !prc.HasExited)
            {
                prc.WaitForExit(500);
            }

            // copy output to writer
            if (writer != null)
            {
                if (File.Exists(log))
                {
                    using (var l = new StreamReader(File.OpenRead(log)))
                        while (l.ReadLine() is string s)
                        {
                            writer.WriteLine(s);
                        }
                }
            }

            try
            {
                if (File.Exists(log))
                {
                    File.Delete(log);
                }
            }
            catch
            {
            }

            return((int)exitCode);
        }
Пример #8
0
        //
        // Core hook methods

        public IProcess CreateAndHook(
            SMCollection collection,
            ISMHookSystem systemCallback,
            IEnumerable <ISMHookIO> ioCallbacks)
        {
            try
            {
                SystemCallback = systemCallback;
                IOCallbacks.AddRange(ioCallbacks);

                IOTargetFilePaths.AddRange(IOCallbacks.SelectMany(c => c.GetTargetFilePaths()));

                // Initialize event to non-Signaled
                HookInitEvent = new AutoResetEvent(false);
                SMAInitEvent  = new AutoResetEvent(false);

                HookSuccess   = false;
                HookException = null;

                // Start a new IPC server
                StartIPCServer();

                // Start SuperMemo application with given collection as parameter,
                // and immediatly install hooks
                RemoteHooking.CreateAndInject(
                    SMConst.BinPath,
                    collection.GetKnoFilePath().Quotify(),
                    0,
                    InjectionOptions.Default,
                    SMAConst.Assembly.GetInjectionLibFilePath(),
                    null,
                    out var pId
                    );

                // Wait for Signal from OnHookInstalled with timeout
                HookInitEvent.WaitOne(WaitTimeout);

                if (HookSuccess == false)
                {
                    StopIPCServer();

                    var ex = new HookException("Hook setup failed: " + HookException?.Message,
                                               HookException);
                    HookException = null;

                    throw ex;
                }

                return(new ProcessSharp <SM17Natives>(
                           pId,
                           Process.NET.Memory.MemoryType.Remote,
                           true,
                           SMA.Instance.Config.PatternsHintAddresses));
            }
            finally
            {
                HookInitEvent = null;
            }
        }
        //
        // Core hook methods

        public async Task <IProcess> CreateAndHook(
            SMCollection collection,
            string binPath,
            ISMAHookSystem systemCallback,
            IEnumerable <ISMAHookIO> ioCallbacks)
        {
            LogTo.Debug("Starting and injecting SuperMemo");

            SystemCallback = systemCallback;
            IOCallbacks.AddRange(ioCallbacks);

            IOTargetFilePaths.AddRange(IOCallbacks.SelectMany(c => c.GetTargetFilePaths()));

            HookSuccess   = false;
            HookException = null;

            // Start a new IPC server
            var channelName = StartIPCServer();

            // Start SuperMemo application with given collection as parameter,
            // and immediatly install hooks
            RemoteHooking.CreateAndInject(
                binPath,
                collection.GetKnoFilePath().Quotify(),
                0,
                InjectionOptions.Default,
                SMAFileSystem.InjectionLibFile.FullPath,
                null,
                out var pId,
                channelName
                );

            LogTo.Debug("Waiting for signal from Injected library");

            // Wait for Signal from OnHookInstalled with timeout
            await HookInitEvent.WaitAsync(WaitTimeout);

            if (HookSuccess == false)
            {
                LogTo.Debug("Hook failed, aborting");

                StopIPCServer();

                var ex = new HookException("Hook setup failed: " + HookException?.Message,
                                           HookException);
                HookException = null;

                throw ex;
            }

            LogTo.Debug($"SuperMemo started and injected, pId: {pId}");

            return(new ProcessSharp <SM17Natives>(
                       pId,
                       Process.NET.Memory.MemoryType.Remote,
                       true,
                       SMA.SMA.Instance.StartupConfig.PatternsHintAddresses));
        }
Пример #10
0
        private int DoCreation(CreateDetails createDetails)
        {
            progress.ProgressUpdate("Creating process and injecting logging agent", 100);

            ProcessStartInfo psi = createDetails.Info;
            int processId;

            RemoteHooking.CreateAndInject(psi.FileName,
                                          (psi.Arguments != String.Empty) ? psi.Arguments : null,
                                          (psi.WorkingDirectory != String.Empty) ? psi.WorkingDirectory : null,
                                          0, AGENT_DLL, AGENT_DLL, out processId,
                                          serverChannelName, details.SoftwallRules);

            return(processId);
        }
Пример #11
0
        ///// <summary>
        ///// Starts process and injects library with redirection of standard input, output and error to handles provided
        ///// </summary>
        ///// <param name="what_to_start"></param>
        ///// <param name="command_line_parameters"></param>
        ///// <returns>process ID of newly created process</returns>
        //public Process startProcessAndInject(string what_to_start, string command_line_parameters, IntPtr stdIn, IntPtr stdOut, IntPtr stdErr)
        //{
        //    int process_id;
        //    MessageFromInjector message = new MessageFromInjector();
        //    message.channel_name = ChannelName;

        //    RemoteHooking.CreateAndInjectEx(what_to_start, command_line_parameters, getMainModuleDirectory() + "APIMonInject.dll", null, out process_id,
        //        stdIn, stdOut, stdErr, message);
        //    return System.Diagnostics.Process.GetProcessById(process_id);
        //}

        /// <summary>
        /// Starts process and injects library
        /// </summary>
        /// <param name="what_to_start"></param>
        /// <param name="command_line_parameters"></param>
        /// <returns>process ID of newly created process</returns>
        public Process startProcessAndInject(ProgramStartDescription tp)
        {
            int process_id;
            MessageFromInjector message = new MessageFromInjector();

            message.channel_name = ChannelName;
            RemoteHooking.CreateAndInject(tp.image_path, tp.command_line, (int)AliasProcessCreationFlags.CREATE_NEW_CONSOLE, getMainModuleDirectory() + "APIMonInject.dll", null, out process_id, message);
            return(System.Diagnostics.Process.GetProcessById(process_id));

            //Process notePad = new Process();

            //notePad.StartInfo.FileName = tp.image_path;
            //notePad.StartInfo.Arguments = tp.command_line;
            //notePad.Start();
            //return notePad;
        }
Пример #12
0
        private static int CreateProcessAndHook(string channelName)
        {
            int processId;

            RemoteHooking.CreateAndInject(
                Environment.CurrentDirectory + @"\TargetUnManagedProcess.exe",
                "",
                0,
                InjectionOptions.DoNotRequireStrongName,
                Environment.CurrentDirectory + @"\DllInjection.dll", // 32 bits
                Environment.CurrentDirectory + @"\DllInjection.dll", // 64 bits
                out processId,
                channelName);

            return(processId);
        }
Пример #13
0
        private static void LaunchHiSuite()
        {
            System.Int32 targetPID = 0;
            //const string LibraryPath = "Interceptor.dll";

            // EasyHook
            try
            {
                RemoteHooking.CreateAndInject(hiSuitePath, string.Empty, 0, LibraryPath, LibraryPath, out targetPID, string.Empty);
            }
            catch (Exception ex)
            {
                // The given EXE path could not be found.
                Console.WriteLine("Could not launch HiSuite:");
                Console.WriteLine(ex.Message);
            }
        }
Пример #14
0
        static void Main(string[] args)
        {
            try
            {
                bool   onlyInject         = int.TryParse(args[0], out int processIdReq);
                string processPathReq     = onlyInject ? string.Empty : args[0];
                int    redirectionPortReq = int.Parse(args[1]);

                HookElement hook = new HookElement();
                {
                    hook.IpcServer = RemoteHooking.IpcCreateServer <HookInterface>(ref hook.ChannelName, WellKnownObjectMode.Singleton);
                }

                if (onlyInject)
                {
                    RemoteHooking.Inject(
                        processIdReq,
                        "./SocketHook.dll",
                        "./SocketHook.dll",
                        hook.ChannelName,
                        redirectionPortReq
                        );
                }
                else
                {
                    RemoteHooking.CreateAndInject(
                        processPathReq,
                        string.Empty,
                        0x00000004,
                        InjectionOptions.DoNotRequireStrongName,
                        "./SocketHook.dll",
                        "./SocketHook.dll",
                        out hook.ProcessId,
                        hook.ChannelName,
                        redirectionPortReq
                        );
                }

                Console.Read();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Пример #15
0
        public void InitHook(string exePath, string hookDllPath, int instanceCount = 1)
        {
            if (instanceCount <= 0)
            {
                return;
            }

            int port = Port;

            HookElement element = new HookElement();

            {
                element.IpcServer = RemoteHooking.IpcCreateServer <CustomHookInterface>(ref element.ChannelName, WellKnownObjectMode.Singleton);
            }

            RemoteHooking.CreateAndInject(
                exePath,
                string.Empty,
                0x00000004,
                InjectionOptions.DoNotRequireStrongName,
                hookDllPath,
                hookDllPath,
                out element.ProcessId,
                element.ChannelName,
                port);

            PortUsedByProcess.Add(element.ProcessId, port);
            Process process = Process.GetProcessById(element.ProcessId);

            process.EnableRaisingEvents = true;

            process.Exited += (obj, arg) =>
            {
                PortUsedByProcess.Remove(process.Id);
                UIManager.Instance.RemovePage(process.Id);
            };

            UIManager.Instance.OpenPage(process.Id);

            Task.Delay(TimeSpan.FromMilliseconds(ConfigurationManager.Instance.Startup.time_wait_in_ms)).ContinueWith(task =>
            {
                InitHook(exePath, hookDllPath, instanceCount - 1);
            });
        }
Пример #16
0
 static void Main(string[] args)
 {
     try
     {
         Write("Enter path to the Ubuntu image file: ");
         var imagePath = Path.GetFullPath(Console.ReadLine());
         Write("Enter path to the icon file: ");
         var iconPath = Path.GetFullPath(Console.ReadLine());
         RemoteHooking.CreateAndInject(@"C:\Windows\System32\LxRun.exe", string.Join(" ", args), 0, "LxRunHook.dll", "LxRunHook.dll", out var pId, imagePath, iconPath);
         var process = Process.GetProcessById(pId);
         process.WaitForExit();
     }
     catch (Exception e)
     {
         WriteLine("Error: Failed to launch LxRun.");
         WriteLine(e);
         Environment.Exit(-1);
     }
 }
Пример #17
0
        /// <summary>
        ///     Starts the game client, injects the current assembly and analyzes it.
        /// </summary>
        /// <param name="token">
        ///     The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.
        /// </param>
        /// <returns>
        ///     A task that represents the asynchronous analysis operation. The task's <see cref="Task{T}.Result" /> contains the
        ///     results of the analysis.
        /// </returns>
        public Task <AnalysisResult> Analyze(CancellationToken token = default(CancellationToken))
        {
            var channelName = default(string);

            RemoteHooking.IpcCreateServer(ref channelName, WellKnownObjectMode.Singleton, this);
            RemoteHooking.CreateAndInject(
                gameClientPath,
                string.Empty,
                0,
                Assembly.GetExecutingAssembly().Location,
                string.Empty,
                out int processId,
                InPassThruArgs: channelName);
            if (token.CanBeCanceled)
            {
                token.Register(() => completionSource.TrySetCanceled());
            }
            return(completionSource.Task);
        }
Пример #18
0
        static void Main(string[] args)
        {
            try
            {
                if (args.Count() == 0)
                {
                    args    = new string[2];
                    args[0] = @"C:\Program Files (x86)\CCP\EVE\bin";
                    args[1] = @"setting.ini";
                }

                if (args.Count() < 2)
                {
                    Console.WriteLine("Usage: Adapteve.exe [ExeFile-path] [IniFile] [Optional-Questor-DLL] [Optional-Questor-Parameters]");
                    Console.ReadLine();
                    return;
                }

                var exefilePath = Utility.GetExefilePath(args[0]);
                var iniFile     = Utility.VerifyIniFile(args[1]);
                var dll         = Directory.GetCurrentDirectory() + "/AdapteveDLL.dll";
                RemoteHooking.CreateAndInject(exefilePath,
                                              "", (int)InjectionOptions.Default,
                                              dll,
                                              dll,
                                              out pid,
                                              "", iniFile);

                if (args.Count() == 4)
                {
                    var qDll   = args[2];
                    var qParam = args[3];
                    System.Threading.Thread.Sleep(500);
                    RemoteHooking.Inject(pid, qDll, qDll, qParam);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }
Пример #19
0
        public void Inject()
        {
            StartupConfiguration configuration = ConfigurationManager.Instance.Startup;

            if (configuration is null)
            {
                logger.Error("startup configuration is null");
                return;
            }

            int port = ProxyPort;

            _hook = new HookElement();
            {
                _hook.IpcServer = RemoteHooking.IpcCreateServer <BotoxHookInterface <T> >(ref _hook.ChannelName, WellKnownObjectMode.Singleton);
            }

            RemoteHooking.CreateAndInject(
                configuration.game_location,
                string.Empty,
                0x00000004,
                InjectionOptions.DoNotRequireStrongName,
                configuration.dll_location,
                configuration.dll_location,
                out _hook.ProcessId,
                _hook.ChannelName,
                port);

            Proxy = new CustomProxy <T>(ProxyPort, _hook.ProcessId);

            Process process = Process.GetProcessById(_hook.ProcessId);

            process.EnableRaisingEvents = true;

            if (process.WaitForInputIdle())
            {
                logger.Info($"process opened : {process.ProcessName} {process.Id}");
                OnProcessStarted?.Invoke(this);
            }

            process.Exited += Process_Exited;
        }
Пример #20
0
        public static string InjectDll(string dllToInject, string targetExe, ref int targetPid, out string channelName,
                                       INotifyClient notifyClient)
        {
            channelName = null;
            RemoteHooking.IpcCreateServer <PostbackMessageHandler>(ref channelName, WellKnownObjectMode.SingleCall);

            var    location           = Assembly.GetExecutingAssembly().Location;
            var    directoryName      = Path.GetDirectoryName(location);
            var    directoryIsNotNull = directoryName != null;
            string formattableString  = null;

            if (directoryIsNotNull)
            {
                var injectionLibrary = Path.Combine(directoryName, dllToInject);
                if (File.Exists(injectionLibrary))
                {
                    if (string.IsNullOrEmpty(targetExe))
                    {
                        RemoteHooking.Inject(
                            targetPid,
                            injectionLibrary,
                            injectionLibrary,
                            channelName);

                        formattableString = $"Injected to process {targetPid}";
                    }
                    else if (File.Exists(targetExe))
                    {
                        RemoteHooking.CreateAndInject(targetExe, "", 0, InjectionOptions.DoNotRequireStrongName,
                                                      injectionLibrary, injectionLibrary, out targetPid, channelName);
                        formattableString = $"Created and injected process {targetPid}";
                    }
                }
            }
            if (notifyClient != null)
            {
                PostbackMessageHandler.RemoteHookerBasesToNotify.Add(
                    new Tuple <INotifyClient, int>(notifyClient, targetPid));
            }
            return(formattableString);
        }
Пример #21
0
        static void Main(string[] args)
        {
            _targetExe = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), args[0]);
            Int32 targetPID = 0;

            try
            {
                if (!File.Exists(_targetExe))
                {
                    Console.WriteLine(String.Format("{0} not found !", _targetExe));
                    Console.WriteLine("Press any key to exit... ");
                    Console.ReadKey();
                    return;
                }

                RemoteHooking.IpcCreateServer <IpcInterface>(ref ChannelName, WellKnownObjectMode.SingleCall);
                string injectionLibrary = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "REHookLib.dll");
                RemoteHooking.CreateAndInject(_targetExe, "", 0, InjectionOptions.DoNotRequireStrongName, injectionLibrary, injectionLibrary, out targetPID, ChannelName);
                Console.WriteLine("Resident Evil successfully launched.");

                ShowWindow(GetConsoleWindow(), SW_HIDE);

                string processName = Path.GetFileNameWithoutExtension(_targetExe);

                while (Process.GetProcessesByName(processName).Length >= 1)
                {
                    Thread.Sleep(2000);
                }

                Environment.Exit(0);
            }
            catch (Exception exception)
            {
                ShowWindow(GetConsoleWindow(), SW_SHOW);

                Console.WriteLine("Unexpected error occurred while launching Resident Evil \r\n{0}", exception.ToString());
                Console.WriteLine("Press any key to exit... ");
                Console.ReadKey();
            }
        }
Пример #22
0
        private string InjectLUAHost()
        {
            string logChannelName = null;
            string res            = "";

            try
            {
                if (IsInjected)
                {
                    return("WoW is already injected.");
                }

                IpcServerChannel ipcLogChannel = RemoteHooking.IpcCreateServer <SystemLog>(ref logChannelName,
                                                                                           WellKnownObjectMode.Singleton);
                remoteLog = RemoteHooking.IpcConnectClient <SystemLog>(logChannelName);
                remoteLog.OnServerEvent += EventShim.Create(prov_OnServerEvent);

                int outprocessid;
                RemoteHooking.CreateAndInject(WoWHelper.GetWowInstallationPath(),
                                              "",
                                              (int)WoWHelper.CreationFlags.NewConsole |
                                              (int)WoWHelper.CreationFlags.Suspended,
                                              "LUAHost.dll",
                                              "LUAHost.dll",
                                              out outprocessid,
                                              logChannelName);

                IPCObject = RemoteHooking.IpcConnectClient <IPCInterface>(remoteLog.InjectedDLLChannelName);
                res       = "Injection has been completed";

                IsInjected = true;
            }
            catch (Exception e)
            {
                res        = e.Message;
                IsInjected = false;
            }

            return(res);
        }
Пример #23
0
        public bool Run()
        {
            if (TargetExePath != null)
            {
                RemoteHooking.CreateAndInject(TargetExePath, CommandLine,
                                              0,
                                              InjectedLibPath,
                                              InjectedLibPath,
                                              out int pid,
                                              new Func <Dictionary <string, FileMapping> >(() => PuppetFiles));
                TargetPid = pid;
            }
            else if (TargetPid > 0)
            {
                RemoteHooking.Inject(TargetPid,
                                     InjectedLibPath,
                                     InjectedLibPath,
                                     _channel);
            }

            return(false);
        }
Пример #24
0
        static void Main(string[] args)
        {
            SetupConsole();

            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("hooksettings.json", optional: false)
                                .Build();

            var settings = new HookSettings();

            configuration.Bind(settings);

            try
            {
                _ipcServer = RemoteHooking.IpcCreateServer <HookInterface>(ref _channelName, WellKnownObjectMode.Singleton);
                RemoteHooking.CreateAndInject(
                    settings.ExePath,
                    string.Empty,
                    0x00000004,
                    InjectionOptions.DoNotRequireStrongName,
                    hookPath,
                    hookPath,
                    out var pId,
                    _channelName,
                    settings.RedirectedIps,
                    settings.RedirectionPort);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            while (true)
            {
                Thread.Sleep(1000);          // TODO: handle close request etc.
            }
        }
Пример #25
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                args = new[] { @"C:\Program Files (x86)\Steam\steamapps\common\Hades\x64\Hades.exe" }
            }
            ;
            if (!File.Exists(args[0]))
            {
                Console.WriteLine(@"Cannot locate Hades executable, please run with 'HadesExtender.exe <HadesDirectory>\x64\Hades.exe'");
                return;
            }
            RemoteHooking.CreateAndInject(args[0],
                                          "",
                                          InProcessCreationFlags: 0,
                                          InjectionOptions.DoNotRequireStrongName,
                                          typeof(EntryPoint).Assembly.Location,
                                          typeof(EntryPoint).Assembly.Location,
                                          out int processID);

            Process.GetProcessById(processID).WaitForExit();
        }
    }
Пример #26
0
        /// <summary>
        /// Start the application at <paramref name="exePath"/>
        /// and then inject and load the CoreHook hooking module <paramref name="injectionLibrary"/>
        /// in the newly created process.
        /// </summary>
        /// <param name="exePath">The path to the application to be launched.</param>
        /// <param name="injectionLibrary">The CoreHook hooking library to loaded in the target.</param>
        /// <param name="injectionPipeName"></param>
        private static void CreateAndInjectDll(
            string exePath,
            string injectionLibrary,
            string injectionPipeName = InjectionPipeName)
        {
            ValidateFilePath(exePath);
            ValidateFilePath(injectionLibrary);

            if (Examples.Common.ModulesPathHelper.GetCoreLoadPaths(
                    false, out CoreHookNativeConfig configX86) &&
                Examples.Common.ModulesPathHelper.GetCoreLoadPaths(
                    true, out CoreHookNativeConfig configX64) &&
                Examples.Common.ModulesPathHelper.GetCoreLoadModulePath(
                    out string coreLoadLibrary))
            {
                RemoteHooking.CreateAndInject(
                    new ProcessCreationConfig
                {
                    ExecutablePath       = exePath,
                    CommandLine          = null,
                    ProcessCreationFlags = 0x00
                },
                    configX86,
                    configX64,
                    new RemoteHookingConfig
                {
                    CLRBootstrapLibrary = coreLoadLibrary,
                    InjectionPipeName   = injectionPipeName,
                    PayloadLibrary      = injectionLibrary,
                    VerboseLog          = HostVerboseLog,
                    WaitForDebugger     = HostWaitForDebugger
                },
                    PipePlatform,
                    out _,
                    CoreHookPipeName);
            }
        }
Пример #27
0
        private static void Main(string[] args)
        {
            try
            {
                args    = new string[4];
                args[0] = @"C:/Program Files (x86)/CCP/EVE/bin";
                args[1] = @"setting.ini";
                args[2] = @"C:/Users/Arjen/Documents/EvE Programming/Adapteve/Adapteve/Adapteve/bin/Debug/QuestorDLL.DLL";
                args[3] = @"1";

                if (args.Count() < 4)
                {
                    Console.WriteLine("Usage: Adapteve.exe [ExeFile-path] [IniFile] [Questor-DLL] [Questor-Parameters]");
                    Console.ReadLine();
                    return;
                }
                var exefilePath = Utility.GetExefilePath(args[0]);
                var iniFile     = Utility.VerifyIniFile(args[1]);
                var dll         = Directory.GetCurrentDirectory() + "/AdapteveDLL.dll";
                var qDll        = args[2];
                var qParam      = args[3];
                RemoteHooking.CreateAndInject(exefilePath,
                                              "", (int)InjectionOptions.Default,
                                              dll,
                                              dll,
                                              out pid,
                                              "", iniFile, qDll, qParam);

                Thread.Sleep(500);
                RemoteHooking.Inject(pid, qDll, qDll, qParam);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }
Пример #28
0
        private static void LaunchHiSuite()
        {
            const string LibraryPath = "Interceptor.dll";

            RemoteHooking.CreateAndInject(hiSuitePath, string.Empty, 0, LibraryPath, LibraryPath, out var _, string.Empty);
        }
Пример #29
0
        private static void CreateAndInjectProcess(string networkId, string filePath, string arguments)
        {
            var injectorAddress = Assembly.GetExecutingAssembly().Location;
            var tries           = 0;
            var processId       = 0;

            while (true)
            {
                try
                {
                    Console.WriteLine("Trying to create the process as suspended.");
                    RemoteHooking.CreateAndInject(
                        filePath,
                        arguments,
                        0,
                        injectorAddress,
                        injectorAddress,
                        out processId,
                        networkId,
                        injectorAddress,
                        CommandLineOptions.Default.Delay,
                        CommandLineOptions.Default.ChangeWindowTitle,
                        CommandLineOptions.Default.Debug);

                    var process = Process.GetProcessById(processId);

                    Thread.Sleep(2000);

                    if (process.HasExited)
                    {
                        return;
                    }

                    if (IsProcessStuckByInjection(process))
                    {
                        Console.WriteLine("Process stuck in suspended state.");

                        // Create and Inject failed
                        if (!process.HasExited)
                        {
                            Console.WriteLine("Killing process ...");
                            process.Kill();
                            process.WaitForExit(3000);
                        }

                        throw new AccessViolationException("Failed to start the application.");
                    }

                    return;
                }
                catch
                {
                    if (tries < 3 && processId == 0)
                    {
                        tries++;
                        Thread.Sleep(1000);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
Пример #30
0
        //
        // Core hook methods

        public async Task <ProcessSharp <SMNatives> > CreateAndHookAsync(
            SMCollection collection,
            string binPath,
            IEnumerable <ISMAHookIO> ioCallbacks,
            NativeData nativeData)
        {
            LogTo.Debug("Starting and injecting SuperMemo");

            IOCallbacks.AddRange(ioCallbacks);

            IOTargetFilePaths.AddRange(IOCallbacks.SelectMany(c => c.GetTargetFilePaths()));

            HookSuccess   = false;
            HookException = null;

            // Start a new IPC server
            var channelName = StartIPCServer();

            // Start SuperMemo application with given collection as parameter,
            // and immediately install hooks
            int pId = -1;

            try
            {
                RemoteHooking.CreateAndInject(
                    binPath,
                    collection.GetKnoFilePath().Quotify(),
                    0,
                    InjectionOptions.Default,
                    SMAFileSystem.InjectionLibFile.FullPath,
                    null,
                    out pId,
                    channelName,
                    nativeData
                    );
            }
            catch (ArgumentException ex)
            {
                LogTo.Warning(ex, "Failed to start and inject SuperMemo. Command line: '{BinPath} {V}'", binPath, collection.GetKnoFilePath().Quotify());
            }

            LogTo.Debug("Waiting for signal from Injected library");

            // Wait for Signal from OnHookInstalled with timeout
            await HookInitEvent.WaitAsync(WaitTimeout).ConfigureAwait(false);

            if (HookSuccess == false)
            {
                LogTo.Debug("Hook failed, aborting");

                StopIPCServer();

                var ex = new HookException("Hook setup failed: " + HookException?.Message,
                                           HookException);
                HookException = null;

                throw ex;
            }

            LogTo.Debug("SuperMemo started and injected, pId: {PId}", pId);

            return(new ProcessSharp <SMNatives>(
                       pId,
                       Process.NET.Memory.MemoryType.Remote,
                       true,
                       Core.CoreConfig.SuperMemo.PatternsHintAddresses,
                       nativeData));
        }