Пример #1
0
 public TargetInstanceFactory(IOptions <InjectionOptions> options, ILogger <TargetInstanceFactory <TConfiguration> > logger, IServiceConfigurationProvider <TConfigurationKey, TConfiguration> configurationProvider, IHttpContextAccessor httpContextAccessor)
 {
     _Options = options.Value;
     _Logger  = logger;
     _ConfigurationProvider = configurationProvider;
     _HttpContextAccessor   = httpContextAccessor;
 }
        async void ProcessWatcher_ProcessStarted(object sender, ProcessStartedEventArgument e)
        {
            if (!SuspiciousProcesses.Contains(e.ProcessName))
            {
                return;
            }

            logger.Information($"Injecting keyboard override library into process {e.ProcessName}.");

            var injectedLibraryName = GetInjectedLibraryName();

            string channelName = null;

            RemoteHooking.IpcCreateServer(
                ref channelName,
                WellKnownObjectMode.SingleCall,
                communicator,
                WellKnownSidType.WorldSid);

            const InjectionOptions injectionOptions =
                InjectionOptions.DoNotRequireStrongName &
                InjectionOptions.NoService &
                InjectionOptions.NoWOW64Bypass;

            RemoteHooking.Inject(
                e.ProcessId,
                injectionOptions,
                injectedLibraryName,
                injectedLibraryName,
                channelName);

            logger.Information($"Keyboard override library successfully injected.");
        }
Пример #3
0
        public bool DumpModule(IntPtr moduleHandle, ImageLayout imageLayout, string filePath)
        {
            ClrModule           dacModule;
            InjectionClrVersion clrVersion;
            InjectionOptions    injectionOptions;
            MetadataInfoService metadataInfoService;
            MetadataInfo        metadataInfo;

            byte[] peImageData;

            dacModule = TryGetDacModule(moduleHandle);
            if (dacModule is null)
            {
                return(false);
            }
            switch (dacModule.Runtime.ClrInfo.Version.Major)
            {
            case 2:
                clrVersion = InjectionClrVersion.V2;
                break;

            case 4:
                clrVersion = InjectionClrVersion.V4;
                break;

            default:
                return(false);
            }
            // 判断要dump的模块的CLR版本
            injectionOptions = new InjectionOptions {
                PortName   = Guid.NewGuid().ToString(),
                ObjectName = Guid.NewGuid().ToString()
            };
            using (NativeProcess process = NativeProcess.Open(_processId))
                if (!process.InjectManaged(typeof(MetadataInfoService).Assembly.Location, typeof(Injection).FullName, "Main", XmlSerializer.Serialize(injectionOptions), clrVersion, out int result) || result != 0)
                {
                    return(false);
                }
            metadataInfoService = (MetadataInfoService)Activator.GetObject(typeof(MetadataInfoService), $"Ipc://{injectionOptions.PortName}/{injectionOptions.ObjectName}");
            // 注入DLL,通过.NET Remoting获取MetadataInfoService实例
            metadataInfo = XmlSerializer.Deserialize <MetadataInfo>(metadataInfoService.GetMetadataInfo(moduleHandle));
            if (!metadataInfo.PEInfo.IsValid)
            {
                return(false);
            }
            imageLayout = (ImageLayout)metadataInfo.PEInfo.ImageLayout;
            try {
                peImageData = DumpModule(moduleHandle, imageLayout, metadataInfo, null);
                // 尝试不使用文件中的节头
            }
            catch {
                peImageData = DumpModule(moduleHandle, imageLayout, metadataInfo, dacModule.FileName);
                // 如果出错,使用文件中的节头
            }
            File.WriteAllBytes(filePath, peImageData);
            return(true);
        }
Пример #4
0
 public static Int32 CreateAndInject(
     String InEXEPath,
     InjectionOptions InOptions,
     String InLibraryPath_x86,
     String InLibraryPath_x64,
     params Object[] InPassThruArgs)
 {
     return(Root_Interface.CreateAndInject(InEXEPath, InOptions, InLibraryPath_x86, InLibraryPath_x64, InPassThruArgs));
 }
Пример #5
0
 public static void Inject(
     Int32 InTargetPID,
     InjectionOptions InOptions,
     String InLibraryPath_x86,
     String InLibraryPath_x64,
     params Object[] InPassThruArgs)
 {
     Inject(InTargetPID, 0, InOptions, InLibraryPath_x86, InLibraryPath_x64, InPassThruArgs);
 }
Пример #6
0
 internal static void Inject(
     Int32 InTargetPID,
     Int32 InWakeUpTID,
     InjectionOptions InOptions,
     String InLibraryPath_x86,
     String InLibraryPath_x64,
     params Object[] InPassThruArgs)
 {
     Root_Interface.Inject(InTargetPID, InWakeUpTID, InOptions, InLibraryPath_x86, InLibraryPath_x64, InPassThruArgs);
 }
Пример #7
0
 public void Inject(
     Int32 InTargetPID,
     Int32 InWakeUpTID,
     InjectionOptions InOptions,
     String InLibraryPath_x86,
     String InLibraryPath_x64,
     params Object[] InPassThruArgs)
 {
     RemoteHooking.Inject(InTargetPID, InWakeUpTID, InOptions, InLibraryPath_x86, InLibraryPath_x64, InPassThruArgs);
 }
        public static IServiceCollection AddAllServices(
            this IServiceCollection services,
            Action <InjectionOptions> options)
        {
            var opts = new InjectionOptions();

            options?.Invoke(opts);

            return(services.AddBusiness()


                   .AddWebHelpers()

                   .AddDbConfig(new DbConfigation(opts)));
        }
Пример #9
0
        /// <summary>
        /// Creates a new process which is started suspended until you call <see cref="WakeUpProcess"/>
        /// from within your injected library <c>Run()</c> method. This allows you to hook the target
        /// BEFORE any of its usual code is executed. In situations where a target has debugging and
        /// hook preventions, you will get a chance to block those mechanisms for example...
        /// </summary>
        /// <remarks>
        /// <para>
        /// Please note that this method might fail when injecting into managed processes, especially
        /// when the target is using the CLR hosting API and takes advantage of AppDomains. For example,
        /// the Internet Explorer won't be hookable with this method. In such a case your only options
        /// are either to hook the target with the unmanaged API or to hook it after (non-supended) creation
        /// with the usual <see cref="Inject"/> method.
        /// </para>
        /// <para>
        /// See <see cref="Inject"/> for more information. The exceptions listed here are additional
        /// to the ones listed for <see cref="Inject"/>.
        /// </para>
        /// </remarks>
        /// <param name="InEXEPath">
        /// A relative or absolute path to the desired executable.
        /// </param>
        /// <param name="InCommandLine">
        /// Optional command line parameters for process creation.
        /// </param>
        /// <param name="InProcessCreationFlags">
        /// Internally CREATE_SUSPENDED is already passed to CreateProcess(). With this
        /// parameter you can add more flags like DETACHED_PROCESS, CREATE_NEW_CONSOLE or
        /// whatever!
        /// </param>
        /// <param name="InOptions">
        /// A valid combination of options.
        /// </param>
        /// <param name="InLibraryPath_x86">
        /// A partially qualified assembly name or a relative/absolute file path of the 32-bit version of your library.
        /// For example "MyAssembly, PublicKeyToken=248973975895496" or ".\Assemblies\\MyAssembly.dll".
        /// </param>
        /// <param name="InLibraryPath_x64">
        /// A partially qualified assembly name or a relative/absolute file path of the 64-bit version of your library.
        /// For example "MyAssembly, PublicKeyToken=248973975895496" or ".\Assemblies\\MyAssembly.dll".
        /// </param>
        /// <param name="OutProcessId">
        /// The process ID of the newly created process.
        /// </param>
        /// <param name="InPassThruArgs">
        /// A serializable list of parameters being passed to your library entry points <c>Run()</c> and
        /// <c>Initialize()</c>.
        /// </param>
        /// <exception cref="ArgumentException">
        /// The given EXE path could not be found.
        /// </exception>
        public static void CreateAndInject(
            String InEXEPath,
            String InCommandLine,
            Int32 InProcessCreationFlags,
            InjectionOptions InOptions,
            String InLibraryPath_x86,
            String InLibraryPath_x64,
            out Int32 OutProcessId,
            params Object[] InPassThruArgs)
        {
            Int32 RemotePID;
            Int32 RemoteTID;

            // create suspended process...
            NativeAPI.RtlCreateSuspendedProcess(
                InEXEPath,
                InCommandLine,
                InProcessCreationFlags,
                out RemotePID,
                out RemoteTID);

            try
            {
                InjectEx(
                    NativeAPI.GetCurrentProcessId(),
                    RemotePID,
                    RemoteTID,
                    0x20000000,
                    InLibraryPath_x86,
                    InLibraryPath_x64,
                    ((InOptions & InjectionOptions.NoWOW64Bypass) == 0),
                    ((InOptions & InjectionOptions.NoService) == 0),
                    ((InOptions & InjectionOptions.DoNotRequireStrongName) == 0),
                    InPassThruArgs);

                OutProcessId = RemotePID;
            }
            catch (Exception e)
            {
                try
                {
                    Process.GetProcessById(RemotePID).Kill();
                }
                catch (Exception) { }

                throw e;
            }
        }
Пример #10
0
 /// <summary>
 /// Injects the given user library into the target process. No memory leaks are left
 /// in the target, even if injection fails for unknown reasons.
 /// </summary>
 /// <remarks>
 /// <para>
 /// There are two possible user library paths. The first one should map to
 /// a 32-bit library, and the second one should map to 64-bit library. If your
 /// code has been compiled for "AnyCPU", like it's the default for C#, you may
 /// even specify one library path for both parameters. Please note that your
 /// library including all of it's dependencies must be registered in the
 /// Global Assembly Cache (GAC). Refer to <see cref="Config.Register"/> for more
 /// information about how to get them there.
 /// </para><para>
 /// If you inject a library into any target process please keep in mind that
 /// your working directory will be switched. EasyHook will automatically add
 /// the directory of the injecting application as first directory of the target's PATH environment
 /// variable. So make sure that all required dependencies are either located
 /// within the injecting application's directory, a system directory or any directory defaultly
 /// contained in the PATH variable. As all managed assemblies have to be in the GAC
 /// there is no need for them being in any of those directories!
 /// </para> <para>
 /// EasyHook provides extensive error information during injection. Any kind of failure is
 /// being catched and thrown as an exception by this method. If for example your library
 /// does not expose a class implementing <see cref="IEntryPoint"/>, an exception will be
 /// raised in the target process during injection. The exception will be redirected to this method
 /// and you can catch it in a try-catch statement around <see cref="Inject"/>.
 /// </para> <para>
 /// You will often have to pass parameters to your injected library. <see cref="IpcChannel"/>
 /// names are common, but also any other kind of data can be passed. You may add a custom list
 /// of objects marked with the <see cref="SerializableAttribute"/>. All common NET classes
 /// will be serializable by default, but if you are using your own classes you might have to provide
 /// serialization by yourself. The custom parameter list will be passed unchanged to your injected
 /// library entry points <c>Run</c> and <c>Initialize</c>. Verify that all required type libraries to deserialize
 /// your parameter list are in the GAC.
 /// </para><para>
 /// It is supported to inject code into 64-bit processes from within 32-bit processes and
 /// vice versa. It is also supported to inject code into other terminal sessions. Of course
 /// this will require additional processes and services to be created, but as they are managed
 /// internally, you won't notice them! There will be some delays when injecting the first library.
 /// Further injections are completed much faster!
 /// </para><para>
 /// Even if it would technically be possible to inject a library for debugging purposes into
 /// the current process, it will throw an exception. This is because it heavily depends on
 /// your injected library whether the current process will be damaged. Any kind of communication
 /// may lead into deadlocks if you hook the wrong APIs. Just use the capability of Visual Studio
 /// to debug more than one process simultanously which will allow you to debug your library
 /// as if it would be injected into the current process without running into any side-effects.
 /// </para>
 /// <para>
 /// The given exceptions are those which are thrown by EasyHook code. The NET framework might throw
 /// any other exception not listed here. Don't rely on the exception type. If you passed valid parameters,
 /// the only exceptions you should explicitly check for are <see cref="NotSupportedException"/> and
 /// <see cref="AccessViolationException"/>. All others
 /// shall be catched together and threaded as bad environment or invalid parameter error.
 /// </para>
 /// </remarks>
 /// <param name="InTargetPID">
 /// The target process ID.
 /// </param>
 /// <param name="InOptions">
 /// A valid combination of options.
 /// </param>
 /// <param name="InLibraryPath_x86">
 /// A partially qualified assembly name or a relative/absolute file path of the 32-bit version of your library.
 /// For example "MyAssembly, PublicKeyToken=248973975895496" or ".\Assemblies\\MyAssembly.dll".
 /// </param>
 /// <param name="InLibraryPath_x64">
 /// A partially qualified assembly name or a relative/absolute file path of the 64-bit version of your library.
 /// For example "MyAssembly, PublicKeyToken=248973975895496" or ".\Assemblies\\MyAssembly.dll".
 /// </param>
 /// <param name="InPassThruArgs">
 /// A serializable list of parameters being passed to your library entry points <c>Run()</c> and
 /// <c>Initialize()</c>.
 /// </param>
 /// <exception cref="InvalidOperationException">
 /// It is unstable to inject libraries into the same process. This exception is disabled in DEBUG mode.
 /// </exception>
 /// <exception cref="AccessViolationException">
 /// Access to target process denied or the current user is not an administrator.
 /// </exception>
 /// <exception cref="ArgumentException">
 /// The given process does not exist or unable to serialize/deserialize one or more pass thru arguments.
 /// </exception>
 /// <exception cref="System.IO.FileNotFoundException">
 /// The given user library could not be found.
 /// </exception>
 /// <exception cref="OutOfMemoryException">
 /// Unable to allocate unmanaged memory in current or target process.
 /// </exception>
 /// <exception cref="NotSupportedException">
 /// It is not supported to inject into the target process. This is common on Windows Vista and Server 2008.
 /// </exception>
 /// <exception cref="TimeoutException">
 /// Unable to wait for user library to be initialized. Check your library <c>Initialize()</c> handler.
 /// </exception>
 /// <exception cref="EntryPointNotFoundException">
 /// The given user library does not export a class implementing the <see cref="IEntryPoint"/> interface.
 /// </exception>
 public static void Inject(
     Int32 InTargetPID,
     InjectionOptions InOptions,
     String InLibraryPath_x86,
     String InLibraryPath_x64,
     params Object[] InPassThruArgs)
 {
     InjectEx(
         GetCurrentProcessId(),
         InTargetPID,
         0,
         0,
         InLibraryPath_x86,
         InLibraryPath_x64,
         ((InOptions & InjectionOptions.NoWOW64Bypass) == 0),
         ((InOptions & InjectionOptions.NoService) == 0),
         InPassThruArgs);
 }
        private void InjectButton_Click(object sender, EventArgs e)
        {
            Process[] pros = Process.GetProcessesByName("TslGame");
            Console.WriteLine(pros.Length);
            // SANITY CHECKS
            if (pros.Length == 0)
            {
                Log.ShowError("请先运行游戏,并且匹配成功进入游戏等待倒计时大厅", "错误");
                return;
            }
            // LOAD EXPLOITABLE DRIVER
            bool driverLoaded = false;

            if (!(driverLoaded = ElevateHandle.Driver.Load()))
            {
                Log.ShowError("CPUZ141.sys failed to load", "lol f**k");
                return;
            }

            ElevateHandle.UpdateDynamicData(); // UPDATE KERNEL OFFSETS
            ElevateHandle.Attach();            // ATTACH TO CURRENT PROCESS
            ElevateHandle.Elevate((ulong)pros[0].Handle, 0x1fffff);


            InjectionOptions options = new InjectionOptions()
            {
                ElevateHandle         = true,
                EraseHeaders          = true,
                CreateLoaderReference = false,
                LoaderImagePath       = Environment.CurrentDirectory + "\\ts.dll"
            };

            ExecutionType executionType = ExecutionType.HijackThread;

            IInjectionMethod injectionMethod = new ManualMapInjection(pros[0], executionType, options);

            //IInjectionMethod injectionMethod = new LoadLibraryInjection(g_SelectedProcess, executionType, options);
            injectionMethod.InjectImage(Environment.CurrentDirectory + "\\ts.dll");

            if (driverLoaded)
            {
                ElevateHandle.Driver.Unload();
            }
        }
Пример #12
0
        async void ProcessWatcher_ProcessStarted(object sender, ProcessStartedEventArgument e)
        {
            if (!SuspiciousProcesses.Contains(e.ProcessName))
            {
                return;
            }

            logger.Information($"Injecting keyboard override library into process {e.ProcessName}.exe.");

            try
            {
                var injectedLibraryName = GetInjectedLibraryName();

                string channelName = null;
                RemoteHooking.IpcCreateServer(
                    ref channelName,
                    WellKnownObjectMode.SingleCall,
                    communicator,
                    WellKnownSidType.WorldSid);

                const InjectionOptions injectionOptions =
                    InjectionOptions.DoNotRequireStrongName &
                    InjectionOptions.NoService &
                    InjectionOptions.NoWOW64Bypass;

                RemoteHooking.Inject(
                    e.ProcessId,
                    injectionOptions,
                    injectedLibraryName,
                    injectedLibraryName,
                    channelName);

                logger.Information($"Keyboard override library successfully injected.");
            }
            catch (DllNotFoundException ex)
            {
                logger.Error(ex, "Could not load a dependency required for keyboard dominance watching.");
            }
            catch (Exception ex)
            {
                logger.Error(ex, "An error occured while trying to watch for keyboard dominance.");
            }
        }
Пример #13
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="injection">注册方式</param>
 public InjectionAttribute(InjectionOptions injection)
 {
     Injection = injection;
 }
Пример #14
0
        private void ButtonInitiateInjection_Click(object sender, EventArgs e)
        {
            // SANITY CHECKS
            if (g_SelectedProcess == null)
            {
                Log.ShowError("Please select a process!", "Lol are you f*****g retarded");
                return;
            }
            if (listImageListView.Items.Count == 0)
            {
                Log.ShowError("Please select atleast one image to inject!", "Lol are you f*****g retarded");
                return;
            }

            // Theme Song ;)
            // SoundPlayer soundPlayer = new SoundPlayer(Resources.Le_Bretonniere);
            // soundPlayer.Play();

            // LOAD EXPLOITABLE DRIVER
            bool driverLoaded = false;

            if (chkElevateHandle.Checked)
            {
                if (!(driverLoaded = ElevateHandle.Driver.Load()))
                {
                    Log.ShowError("CPUZ141.sys failed to load", "lol f**k");
                    return;
                }

                ElevateHandle.UpdateDynamicData(); // UPDATE KERNEL OFFSETS
                ElevateHandle.Attach();            // ATTACH TO CURRENT PROCESS
                ElevateHandle.Elevate((ulong)g_SelectedProcess.Handle, 0x1fffff);
            }

            InjectionOptions options = new InjectionOptions()
            {
                ElevateHandle         = chkElevateHandle.Checked,
                EraseHeaders          = chkEraseHeaders.Checked,
                CreateLoaderReference = false
            };

            ExecutionType executionType = 0;

            switch (comboExecutionMethod.SelectedIndex)
            {
            case 0:
                executionType = ExecutionType.CreateThread;
                break;

            case 1:
                executionType = ExecutionType.HijackThread;
                break;
            }

            IInjectionMethod injectionMethod = null;

            switch (comboInjectionMethod.SelectedIndex)
            {
            case 0:     // LOAD LIBRARY
                injectionMethod = new LoadLibraryInjection(g_SelectedProcess, executionType, options);
                break;

            case 1:     // MANUAL MAP
                injectionMethod = new ManualMapInjection(g_SelectedProcess, executionType, options);
                break;
            }

            foreach (ListViewItem item in listImageListView.Items)
            {
                if (injectionMethod.InjectImage(item.Text))
                {
                    Log.ShowInformation($"Successfully injected {item.Text} -> {g_SelectedProcess.ProcessName}", "Success");
                }
                else
                {
                    Log.ShowError($"Failed injection {item.Text} -> {g_SelectedProcess.ProcessName}", "f**k");
                }
            }

            if (driverLoaded)
            {
                ElevateHandle.Driver.Unload();
            }
        }
Пример #15
0
        private void InjectButton_Click(object sender, EventArgs e)
        {
            // SANITY CHECKS
            if (g_SelectedProcess == null)
            {
                Log.ShowError("Select a process!", "Error");
                return;
            }

            OpenFileDialog fileDialog = new OpenFileDialog()
            {
                Filter      = "Dynamic Link Library|*.dll",
                Multiselect = false
            };

            if (fileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            // LOAD EXPLOITABLE DRIVER
            bool driverLoaded = false;

            if (ElevateHandleCheckbox.Checked)
            {
                if (!(driverLoaded = ElevateHandle.Driver.Load()))
                {
                    Log.ShowError("CPUZ141.sys failed to load", "lol f**k");
                    return;
                }

                ElevateHandle.UpdateDynamicData(); // UPDATE KERNEL OFFSETS
                ElevateHandle.Attach();            // ATTACH TO CURRENT PROCESS
                ElevateHandle.Elevate((ulong)g_SelectedProcess.Handle, 0x1fffff);
            }

            InjectionOptions options = new InjectionOptions()
            {
                ElevateHandle         = ElevateHandleCheckbox.Checked,
                EraseHeaders          = EraseHeadersCheckbox.Checked,
                CreateLoaderReference = LinkModuleCheckbox.Checked,
                LoaderImagePath       = fileDialog.FileName
            };

            ExecutionType executionType = 0;

            switch (TypeCombo.SelectedIndex)
            {
            case 0:
                executionType = ExecutionType.CreateThread;
                break;

            case 1:
                executionType = ExecutionType.HijackThread;
                break;
            }

            IInjectionMethod injectionMethod = null;

            switch (ModeCombo.SelectedIndex)
            {
            case 0:     // MANUAL MAP
                injectionMethod = new ManualMapInjection(g_SelectedProcess, executionType, options);
                break;

            case 1:     // LOAD LIBRARY
                injectionMethod = new LoadLibraryInjection(g_SelectedProcess, executionType, options);
                break;
            }

            injectionMethod.InjectImage(fileDialog.FileName);

            if (driverLoaded)
            {
                ElevateHandle.Driver.Unload();
            }
        }
Пример #16
0
        static void Main(string[] args)
        {
            int targetPID;

            if ((args.Length != 1) || !Int32.TryParse(args[0], out targetPID))
            {
                Console.WriteLine();
                Console.WriteLine("Usage: ComplexParameterTest %ProcessID%");
                Console.WriteLine();
                Console.Write("Please enter the target PID: ");
                if (!Int32.TryParse(Console.ReadLine(), out targetPID))
                {
                    Console.WriteLine("Invalid PID");
                    return;
                }
            }

            try
            {
                bool noGAC = true;
                //try
                //{
                //    Config.Register(
                //        "Test passing an object parameter",
                //        "ComplexParameterInject.dll");
                //}
                //catch (ApplicationException ae)
                //{
                //    Console.WriteLine("This is an administrative task! Attempting without GAC...");

                //    noGAC = true;
                //}
                string channelName = null;
                RemoteHooking.IpcCreateServer <ComplexParameterInject.TestInterface>(ref channelName, WellKnownObjectMode.SingleCall);

                InjectionOptions options = InjectionOptions.Default;
                if (noGAC)
                {
                    options |= InjectionOptions.DoNotRequireStrongName;
                }

                ComplexParameterInject.TestComplexParameter parameter = new ComplexParameterInject.TestComplexParameter
                {
                    Message       = "All your binary serializations are belong to us",
                    HostProcessId = RemoteHooking.GetCurrentProcessId()
                };
                RemoteHooking.Inject(
                    targetPID,
                    options,
                    typeof(ComplexParameterInject.TestComplexParameter).Assembly.Location, //"ComplexParameterInject.dll",
                    typeof(ComplexParameterInject.TestComplexParameter).Assembly.Location, //"ComplexParameterInject.dll",
                    channelName
                    , parameter
                    );
            }
            catch (Exception e)
            {
                Console.WriteLine("Injection failed: {0}:{1}", e.GetType().FullName, e.Message);
            }

            Console.WriteLine("Press <enter> to continue");
            Console.ReadLine();
        }